diff --git a/am_renewal_contract_001/_cua_gym_vm_bridge.sh b/am_renewal_contract_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/am_renewal_contract_001/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/am_renewal_contract_001/initial_setup.py b/am_renewal_contract_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..951af4dbf9bb21800cbbe061c19917b338b245bf --- /dev/null +++ b/am_renewal_contract_001/initial_setup.py @@ -0,0 +1,648 @@ +# --- MOCK_HOST_NO_PROXY_OVERRIDE: bypass woa proxy for locally-deployed mocks --- +import os as _os +_np = _os.environ.get("no_proxy", _os.environ.get("NO_PROXY", "")) +for _h in ("127.0.0.1", "localhost", "28.7.184.198"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +# --- wait_mocks_loaded: wait for mock backends ready AND browser tabs rendered --- +def wait_mocks_loaded(timeout=60, render_buffer=12): + """Wait for mock backends ready AND browser tabs rendered (via CDP). + + Phase 1 — backend readiness: poll each mock's /state?sid= until it + returns 200 with 'stored_state' in the body. + + Phase 2 — browser render verification: connect to Chrome's CDP + endpoint and wait for every open tab to reach 'networkidle' load + state with a non-trivial DOM element count. This confirms the SPA + has fetched its /go?sid= data and actually painted, not just that + the backend is up. + + CDP port auto-detection: checks globals for _chrome_debug_port / + cdp_port / debug_port (set by tasks that use a dynamic port, e.g. + se_hard_008's launch_chrome_with_urls); defaults to 1337 for tasks + that use launch_gui's --remote-debugging-port injection. + + Falls back to the old render_buffer sleep if Playwright or the CDP + endpoint is unavailable. + """ + import urllib.request as _u, time as _t + g = globals() + _urls = {} + for _k, _v in list(g.items()): + if isinstance(_v, dict) and _v and all(isinstance(x, str) and x.startswith("http://") for x in _v.values()): + _urls.update(_v) + elif isinstance(_v, str) and _v.startswith("http://") and (_k.endswith("_URL") or _k.endswith("_url")): + _urls[_k] = _v + _sid = "" + for _k in ("sid", "SID", "task_sid", "session_id"): + if isinstance(g.get(_k), str) and g[_k]: + _sid = g[_k]; break + if not _sid: + for _k, _v in g.items(): + if "sid" in _k.lower() and isinstance(_v, str) and _v: + _sid = _v; break + if not _urls or not _sid: + print(" wait_mocks_loaded: no mocks/sid found (%d urls, sid=%r), skipping" % (len(_urls), bool(_sid))) + return + + # ---- Phase 1: backend readiness ---- + _op = _u.build_opener(_u.ProxyHandler({})) + _dl = _t.time() + timeout + _todo = list(_urls.items()) + while _todo and _t.time() < _dl: + _rest = [] + for _n2, _uu in _todo: + try: + _r = _op.open("%s/state?sid=%s" % (_uu, _sid), timeout=5) + if _r.status == 200 and b"stored_state" in _r.read(): + print(" %s: backend ready" % _n2); continue + except Exception: + pass + _rest.append((_n2, _uu)) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = (" (pending: %s)" % [n for n, _ in _todo]) if _todo else "" + print(" mocks backend ready: %d/%d%s" % (_done, len(_urls), _pend)) + + # ---- Phase 2: browser render verification via CDP ---- + # Auto-detect CDP port from globals (set by launch_chrome_with_urls + # in tasks that use a dynamic port); default to 1337. + _cdp_port = 1337 + for _pk in ("_chrome_debug_port", "chrome_debug_port", "cdp_port", "debug_port"): + _pv = g.get(_pk) + if isinstance(_pv, int) and 0 < _pv < 65536: + _cdp_port = _pv; break + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(10.0, _dl - _t.time()) # leftover budget, floor 10s + with sync_playwright() as _p: + _br = None + # Retry-connect: Chrome may still be starting up. + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp("http://localhost:%d" % _cdp_port) + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to localhost:%d failed; " + "is Chrome launched with --remote-debugging-port?" % _cdp_port) + else: + # Wait for ALL expected tabs to appear, then verify each renders. + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break # all expected tabs are open + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break # tab count stable -> no more tabs opening + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + # Re-fetch final snapshot so late-opening tabs are included. + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(" wait_mocks_loaded: %d tab(s) open (expected %d); " + "verifying render" % (len(_pages), _n_expected)) + _ok_cnt = 0 + for _pg in _pages: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _pg.wait_for_load_state( + "networkidle", + timeout=int(max(5000, (_cdp_dl - _t.time()) * 1000))) + _n = _pg.evaluate("document.querySelectorAll('*').length") + if _n < 20: + print(" wait_mocks_loaded: WARNING tab %r has only %d " + "elements (render stall?)" % (_ttl, _n)) + else: + print(" wait_mocks_loaded: tab %r rendered (%d elements)" + % (_ttl, _n)) + _ok_cnt += 1 + except Exception as _e: + print(" wait_mocks_loaded: tab %r render wait failed: %r" + % (_ttl, _e)) + # Require ALL open tabs to render before skipping the + # render_buffer fallback, so no tab is left half-loaded. + if _ok_cnt > 0 and _ok_cnt == len(_pages): + _cdp_ok = True + else: + print(" wait_mocks_loaded: %d/%d tabs rendered, will fall back" + % (_ok_cnt, len(_pages))) + except ImportError: + print(" wait_mocks_loaded: playwright not installed; cannot verify browser render") + except Exception as _e: + print(" wait_mocks_loaded: CDP phase error (%r)" % _e) + + if not _cdp_ok: + print(" wait_mocks_loaded: falling back to render_buffer=%ds sleep" % render_buffer) + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") +# --- end wait_mocks_loaded --- + +# --- _open_remaining_mock_tabs: open all auto-detected mock URLs in new Chrome tabs --- +def _open_remaining_mock_tabs(primary_url=""): + """Open all auto-detected mock URLs in Chrome --new-tab, except primary_url.""" + g = globals() + _urls = set() + for _k, _v in list(g.items()): + if "PROBE" in _k.upper() or _k.startswith("_"): + continue + if isinstance(_v, str) and _v.startswith("http://") and (_k.endswith("_URL") or _k.endswith("_url")): + _urls.add(_v) + elif isinstance(_v, dict) and _v and all(isinstance(x, str) and x.startswith("http://") for x in _v.values()): + _urls.update(_v.values()) + _sid = "" + for _k in ("sid", "SID", "task_sid", "session_id"): + if isinstance(g.get(_k), str) and g[_k]: + _sid = g[_k]; break + for _u in sorted(_urls): + if _u != primary_url: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={_sid}"', delay_sec=1.0) +# --- end _open_remaining_mock_tabs --- + + +""" +Initial Setup: Contract-To-Signature renewal pipeline (Globex Corp) +Task ID: am_renewal_contract_001 +Domain: mock_websites +Mocks: notion_mock, docusign_mock, slack_mock + +Injects initial state into all three mocks under a single shared, DETERMINISTIC sid: + - Notion: current 'Renewal Brief - Globex Corp' page (terms) + a stale FY24 distractor page + - DocuSign: Jordan Avery user, address-book contacts (David Okafor + finance mailbox), + 'Annual Renewal Agreement' template, and several unrelated distractor envelopes. + NO Globex renewal envelope exists yet. + - Slack: Vertex Cloud workspace with a 'deal-desk' channel (Jordan + finance + legal). + NO message about the Globex renewal envelope yet. + +NOTE on sid: initial_env and golden_env are SEPARATE VMs that do NOT share /tmp. +A random per-VM UUID would not match across them. We therefore use a deterministic +sid derived from the task id so initial_setup.py (initial VM) and golden_patch.py +(golden VM) reference the same server-side state. Both scripts also write the sid to +their own /tmp/task_web_sid so reward.py can read it on either VM. +""" +import os +import shlex +import subprocess +import time + +import requests + +TASK_ID = 'am_renewal_contract_003' +# initial_env and golden_env are SEPARATE containers but hit the SAME shared mock +# server. They MUST therefore use DISTINCT sids, otherwise reward.py (run on both +# VMs against the same reward code) would read identical server state and the +# initial env could never score 0. This script owns the *_initial sid. +SID = f'cuagym-{TASK_ID}-initial' # deterministic; valid chars [a-zA-Z0-9_-] + +# Persist sid for reward.py on THIS (initial) VM. +with open('/tmp/task_web_sid', 'w') as f: + f.write(SID) +print(f'sid={SID}') + +MOCK_URLS = { + 'notion': 'http://28.7.184.198:8166', + 'docusign': 'http://28.7.184.198:8130', + 'slack': 'http://28.7.184.198:8178', +} +PROXY = None + + +# ---------------------------------------------------------------------------- +# Network: the mocks may require the corporate proxy. Auto-detect once. +# ---------------------------------------------------------------------------- +def pick_proxies(): + for p in (None, {'http': PROXY, 'https': PROXY}): + try: + r = requests.get(f'{MOCK_URLS["docusign"]}/go?sid=probe', proxies=p, timeout=10) + if r.status_code == 200: + print(f'connectivity OK via proxies={p}') + return p + except Exception as e: + print(f'probe with proxies={p} failed: {repr(e)[:80]}') + raise RuntimeError('Cannot reach mock server directly or via proxy') + + +PROXIES = None + + +# ---------------------------------------------------------------------------- +# NOTION state +# ---------------------------------------------------------------------------- +def build_notion_state(): + cur_page_id = 'page-globex-renewal-2026' + old_page_id = 'page-globex-renewal-fy24' + getting_started_id = 'page-getting-started' + + cur_blocks = [ + ('blk-cur-h1', 'heading-1', 'Renewal Brief - Globex Corp'), + ('blk-cur-intro', 'text', + 'Renewal package for Globex Corp. Use these terms to prepare the renewal agreement for e-signature.'), + ('blk-cur-h2-terms', 'heading-2', 'Key Terms'), + ('blk-cur-customer', 'bullet-list', 'Customer: Globex Corp'), + ('blk-cur-arr', 'bullet-list', 'Renewal ARR / contract value: $85,000'), + ('blk-cur-term', 'bullet-list', 'Term: 12 months'), + ('blk-cur-uplift', 'bullet-list', 'Price uplift: 5% vs. prior term'), + ('blk-cur-payment', 'bullet-list', 'Payment terms: Net-30'), + ('blk-cur-finance', 'bullet-list', 'Finance CC mailbox: finance@vertexcloud.example.com'), + ('blk-cur-autorenew', 'bullet-list', + 'Auto-renewal clause: yes (12-month auto-renew unless cancelled 60 days prior)'), + ('blk-cur-closedate', 'bullet-list', 'Renewal (close) date: 2026-08-30'), + ('blk-cur-h2-signer', 'heading-2', 'Authorized Signer (Customer)'), + ('blk-cur-signer', 'text', 'David Okafor, COO, david.okafor@globex.example.com'), + ('blk-cur-callout', 'callout', + 'Send via DocuSign using the "Annual Renewal Agreement" template. CC finance@vertexcloud.example.com.'), + ] + + old_blocks = [ + ('blk-old-h1', 'heading-1', 'Renewal Brief - Globex Corp (FY24)'), + ('blk-old-note', 'callout', + "ARCHIVED - last year's terms. Do not use for the current renewal."), + ('blk-old-h2', 'heading-2', 'FY24 Terms (stale)'), + ('blk-old-arr', 'bullet-list', 'Renewal ARR / contract value: $72,000'), + ('blk-old-term', 'bullet-list', 'Term: 12 months'), + ('blk-old-uplift', 'bullet-list', 'Price uplift: 3% vs. prior term'), + ('blk-old-payment', 'bullet-list', 'Payment terms: Net-30'), + ('blk-old-closedate', 'bullet-list', 'Renewal (close) date: 2025-08-30'), + ('blk-old-signer', 'text', + 'Authorized signer: David Okafor, COO, david.okafor@globex.example.com'), + ] + + gs_blocks = [ + ('blk-gs-h1', 'heading-1', 'Vertex Cloud - Renewals Workspace'), + ('blk-gs-text', 'text', + 'Home base for the renewals team. Open a customer renewal brief to get started.'), + ] + + created = '2026-06-10T09:00:00.000Z' + blocks = {} + + def add_blocks(block_list): + for bid, btype, content in block_list: + blocks[bid] = { + 'id': bid, 'type': btype, 'content': content, 'properties': {}, + 'createdDate': created, 'lastEditedDate': created, + } + + add_blocks(cur_blocks) + add_blocks(old_blocks) + add_blocks(gs_blocks) + + pages = { + getting_started_id: { + 'id': getting_started_id, 'title': 'Vertex Cloud - Renewals Workspace', + 'icon': '\U0001F680', 'cover': None, 'parentId': None, + 'blockIds': [b[0] for b in gs_blocks], 'favorite': True, + 'createdDate': created, 'lastEditedDate': created, 'properties': {}, + }, + cur_page_id: { + 'id': cur_page_id, 'title': 'Renewal Brief - Globex Corp', + 'icon': '\U0001F4DD', 'cover': None, 'parentId': None, + 'blockIds': [b[0] for b in cur_blocks], 'favorite': False, + 'createdDate': '2026-06-08T10:00:00.000Z', + 'lastEditedDate': '2026-06-08T10:00:00.000Z', 'properties': {}, + }, + old_page_id: { + 'id': old_page_id, 'title': 'Renewal Brief - Globex Corp (FY24)', + 'icon': '\U0001F5C3', 'cover': None, 'parentId': None, + 'blockIds': [b[0] for b in old_blocks], 'favorite': False, + 'createdDate': '2024-07-01T10:00:00.000Z', + 'lastEditedDate': '2024-07-01T10:00:00.000Z', 'properties': {}, + }, + } + + return { + 'user': {'id': 'user-1', 'name': 'Jordan Avery', + 'email': 'jordan.avery@vertexcloud.example.com', + 'avatar': 'https://picsum.photos/seed/jordan/100/100'}, + 'workspace': {'id': 'ws-1', 'name': 'Vertex Cloud', 'icon': '☁️', 'members': ['user-1']}, + 'pages': pages, + 'blocks': blocks, + 'trash': [], + 'comments': {}, + 'settings': {'appearance': 'light', 'startWeekMonday': False, 'fontSize': 'default'}, + 'notifications': [], + 'pageOrder': [getting_started_id, cur_page_id, old_page_id], + 'focusBlockId': None, + } + + +# ---------------------------------------------------------------------------- +# DOCUSIGN state +# ---------------------------------------------------------------------------- +def build_docusign_state(): + user = { + 'id': 'user_1', 'name': 'Jordan Avery', + 'email': 'jordan.avery@vertexcloud.example.com', + 'title': 'Account Manager', 'company': 'Vertex Cloud', + 'avatar': 'https://picsum.photos/seed/jordan/100/100', + 'signatureDataUrl': None, 'initialsDataUrl': None, 'memberSince': '2022-04-12', + 'settings': {'defaultReminderDays': 3, 'defaultExpirationDays': 120, + 'timezone': 'America/Los_Angeles'}, + } + + contacts = [ + {'id': 'contact_1', 'name': 'David Okafor', 'email': 'david.okafor@globex.example.com', + 'company': 'Globex Corp', 'title': 'COO'}, + {'id': 'contact_2', 'name': 'Vertex Cloud Finance', 'email': 'finance@vertexcloud.example.com', + 'company': 'Vertex Cloud', 'title': 'Finance Mailbox'}, + {'id': 'contact_3', 'name': 'Maria Lindqvist', 'email': 'm.lindqvist@initech.example.com', + 'company': 'Initech', 'title': 'VP Procurement'}, + {'id': 'contact_4', 'name': 'Tom Becker', 'email': 't.becker@umbrella.example.com', + 'company': 'Umbrella Inc', 'title': 'Director of IT'}, + {'id': 'contact_5', 'name': 'Priya Nair', 'email': 'priya.nair@hooli.example.com', + 'company': 'Hooli', 'title': 'Head of Legal'}, + ] + + templates = [ + { + 'id': 'tmpl_renewal', 'name': 'Annual Renewal Agreement', + 'description': 'Standard 12-month SaaS subscription renewal agreement for existing customers.', + 'createdAt': '2024-01-15T12:00:00Z', 'lastUsedAt': '2026-05-20T10:00:00Z', + 'usageCount': 24, 'ownerId': 'user_1', 'shared': True, + 'documents': [{'id': 'tdoc_renewal_1', 'name': 'Annual_Renewal_Agreement.pdf', + 'pageCount': 5, 'order': 1, + 'fileUrl': 'https://picsum.photos/seed/renewaltmpl/800/1100', 'fileType': 'pdf'}], + 'roles': [ + {'id': 'role_renewal_1', 'name': 'Customer Signer', 'role': 'signer', 'routingOrder': 1}, + {'id': 'role_renewal_cc', 'name': 'Vertex Cloud Finance', + 'role': 'cc', 'routingOrder': 2}, + ], + 'fields': [], + }, + { + 'id': 'tmpl_nda', 'name': 'Standard NDA', + 'description': 'Mutual non-disclosure agreement.', + 'createdAt': '2023-09-01T12:00:00Z', 'lastUsedAt': '2026-02-11T10:00:00Z', + 'usageCount': 41, 'ownerId': 'user_1', 'shared': True, + 'documents': [{'id': 'tdoc_nda_1', 'name': 'Mutual_NDA.pdf', 'pageCount': 3, 'order': 1, + 'fileUrl': 'https://picsum.photos/seed/ndatmpl/800/1100', 'fileType': 'pdf'}], + 'roles': [{'id': 'role_nda_1', 'name': 'Party A', 'role': 'signer', 'routingOrder': 1}, + {'id': 'role_nda_2', 'name': 'Party B', 'role': 'signer', 'routingOrder': 2}], + 'fields': [], + }, + { + 'id': 'tmpl_order', 'name': 'New Order Form', + 'description': 'Net-new subscription order form for new logos.', + 'createdAt': '2024-03-20T12:00:00Z', 'lastUsedAt': '2026-04-30T10:00:00Z', + 'usageCount': 13, 'ownerId': 'user_1', 'shared': False, + 'documents': [{'id': 'tdoc_order_1', 'name': 'Order_Form.pdf', 'pageCount': 2, 'order': 1, + 'fileUrl': 'https://picsum.photos/seed/ordertmpl/800/1100', 'fileType': 'pdf'}], + 'roles': [{'id': 'role_order_1', 'name': 'Authorized Signer', 'role': 'signer', 'routingOrder': 1}], + 'fields': [], + }, + ] + + folders = [ + {'id': 'folder_1', 'name': 'Renewals', 'parentFolder': None, 'createdAt': '2024-01-01T00:00:00Z'}, + {'id': 'folder_2', 'name': 'New Business', 'parentFolder': None, 'createdAt': '2024-01-01T00:00:00Z'}, + ] + + envelopes = [ + { + 'id': 'env_initech', 'subject': 'Initech - Annual Renewal Agreement', + 'message': 'Please review and sign the renewal agreement.', 'status': 'completed', + 'createdAt': '2026-03-01T09:00:00Z', 'sentAt': '2026-03-01T09:30:00Z', + 'completedAt': '2026-03-04T15:20:00Z', 'voidedAt': None, 'declinedAt': None, + 'lastActivityAt': '2026-03-04T15:20:00Z', 'expiresAt': None, + 'senderId': 'user_1', 'folderId': 'folder_1', 'templateId': 'tmpl_renewal', + 'reminderEnabled': True, 'reminderDays': 3, 'reminderFrequency': 2, + 'documents': [{'id': 'doc_in_1', 'name': 'Initech_Renewal.pdf', 'pageCount': 5, + 'order': 1, 'fileUrl': 'https://picsum.photos/seed/initech/800/1100', 'fileType': 'pdf'}], + 'recipients': [{'id': 'rec_in_1', 'name': 'Maria Lindqvist', + 'email': 'm.lindqvist@initech.example.com', 'role': 'signer', 'routingOrder': 1, + 'status': 'signed', 'signedAt': '2026-03-04T15:20:00Z', + 'viewedAt': '2026-03-02T08:00:00Z', 'deliveredAt': '2026-03-01T09:31:00Z', + 'declinedAt': None, 'declineReason': None}], + 'fields': [], + 'history': [ + {'id': 'evt_in_1', 'timestamp': '2026-03-01T09:00:00Z', 'action': 'created', + 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com', + 'details': 'Envelope created'}, + {'id': 'evt_in_2', 'timestamp': '2026-03-04T15:20:00Z', 'action': 'completed', + 'actorName': 'Maria Lindqvist', 'actorEmail': 'm.lindqvist@initech.example.com', + 'details': 'Signed by all recipients'}, + ], + }, + { + 'id': 'env_umbrella', 'subject': 'Umbrella Inc - Mutual NDA', + 'message': 'NDA for the upcoming evaluation.', 'status': 'sent', + 'createdAt': '2026-06-05T11:00:00Z', 'sentAt': '2026-06-05T11:10:00Z', + 'completedAt': None, 'voidedAt': None, 'declinedAt': None, + 'lastActivityAt': '2026-06-05T11:10:00Z', 'expiresAt': '2026-10-03T11:10:00Z', + 'senderId': 'user_1', 'folderId': 'folder_2', 'templateId': 'tmpl_nda', + 'reminderEnabled': False, 'reminderDays': 3, 'reminderFrequency': 2, + 'documents': [{'id': 'doc_um_1', 'name': 'Umbrella_NDA.pdf', 'pageCount': 3, + 'order': 1, 'fileUrl': 'https://picsum.photos/seed/umbrella/800/1100', 'fileType': 'pdf'}], + 'recipients': [{'id': 'rec_um_1', 'name': 'Tom Becker', 'email': 't.becker@umbrella.example.com', + 'role': 'signer', 'routingOrder': 1, 'status': 'delivered', 'signedAt': None, + 'viewedAt': '2026-06-06T09:00:00Z', 'deliveredAt': '2026-06-05T11:11:00Z', + 'declinedAt': None, 'declineReason': None}], + 'fields': [], + 'history': [ + {'id': 'evt_um_1', 'timestamp': '2026-06-05T11:00:00Z', 'action': 'created', + 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com', + 'details': 'Envelope created'}, + {'id': 'evt_um_2', 'timestamp': '2026-06-05T11:10:00Z', 'action': 'sent', + 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com', + 'details': 'Envelope sent'}, + ], + }, + { + 'id': 'env_hooli', 'subject': 'Hooli - New Order Form (Q3)', + 'message': 'Draft order form, not yet sent.', 'status': 'draft', + 'createdAt': '2026-06-18T14:00:00Z', 'sentAt': None, + 'completedAt': None, 'voidedAt': None, 'declinedAt': None, + 'lastActivityAt': '2026-06-18T14:00:00Z', 'expiresAt': None, + 'senderId': 'user_1', 'folderId': 'folder_2', 'templateId': 'tmpl_order', + 'reminderEnabled': False, 'reminderDays': 3, 'reminderFrequency': 2, + 'documents': [{'id': 'doc_ho_1', 'name': 'Hooli_Order.pdf', 'pageCount': 2, + 'order': 1, 'fileUrl': 'https://picsum.photos/seed/hooli/800/1100', 'fileType': 'pdf'}], + 'recipients': [{'id': 'rec_ho_1', 'name': 'Priya Nair', 'email': 'priya.nair@hooli.example.com', + 'role': 'signer', 'routingOrder': 1, 'status': 'created', 'signedAt': None, + 'viewedAt': None, 'deliveredAt': None, 'declinedAt': None, 'declineReason': None}], + 'fields': [], + 'history': [ + {'id': 'evt_ho_1', 'timestamp': '2026-06-18T14:00:00Z', 'action': 'created', + 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com', + 'details': 'Envelope created'}, + ], + }, + ] + + auditLog = [ + {'id': 'audit_1', 'timestamp': '2026-03-01T09:00:00Z', 'action': 'CREATE_ENVELOPE', + 'details': 'Initech - Annual Renewal Agreement', 'envelopeId': 'env_initech'}, + {'id': 'audit_2', 'timestamp': '2026-03-04T15:20:00Z', 'action': 'COMPLETE_ENVELOPE', + 'details': 'Initech - Annual Renewal Agreement', 'envelopeId': 'env_initech'}, + {'id': 'audit_3', 'timestamp': '2026-06-05T11:10:00Z', 'action': 'SEND_ENVELOPE', + 'details': 'Umbrella Inc - Mutual NDA', 'envelopeId': 'env_umbrella'}, + {'id': 'audit_4', 'timestamp': '2026-06-18T14:00:00Z', 'action': 'CREATE_ENVELOPE', + 'details': 'Hooli - New Order Form (Q3)', 'envelopeId': 'env_hooli'}, + ] + + return {'user': user, 'envelopes': envelopes, 'templates': templates, + 'folders': folders, 'contacts': contacts, 'auditLog': auditLog} + + +# ---------------------------------------------------------------------------- +# SLACK state +# ---------------------------------------------------------------------------- +def build_slack_state(): + users = [ + {'userId': 'user_1', 'fullName': 'Jordan Avery', 'displayName': 'Jordan', + 'email': 'jordan.avery@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Account Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/Los_Angeles'}, + {'userId': 'user_2', 'fullName': 'Dana Whitfield', 'displayName': 'Dana', + 'email': 'dana.whitfield@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Finance Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Liam Castellano', 'displayName': 'Liam', + 'email': 'liam.castellano@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Legal Counsel', 'status': 'away', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_4', 'fullName': 'Sofia Reyes', 'displayName': 'Sofia', + 'email': 'sofia.reyes@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': 'Sales Director', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/Los_Angeles'}, + ] + + channels = [ + {'channelId': 'deal-desk', 'name': 'deal-desk', + 'description': 'Deal desk: pricing approvals, contracts, and renewals coordination', + 'topic': 'Renewals & contracts', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_4', + 'createdAt': '2025-01-10T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'general', 'name': 'general', + 'description': 'Company-wide announcements and general discussion', + 'topic': 'Company-wide announcements', 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_4', + 'createdAt': '2024-12-01T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'sales', 'name': 'sales', + 'description': 'Sales team coordination', 'topic': 'Pipeline & quota', + 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_4'], 'createdBy': 'user_4', + 'createdAt': '2024-12-01T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ] + + messages = { + 'deal-desk': [ + {'messageId': 'msg_dd_1', 'senderId': 'user_4', + 'content': 'Reminder: please post in here once any renewal envelope goes out so finance and legal are looped in.', + 'timestamp': '2026-06-20T16:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_dd_2', 'senderId': 'user_2', + 'content': 'Thanks Sofia. We are watching the Globex renewal closely this quarter.', + 'timestamp': '2026-06-20T16:05:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + 'general': [ + {'messageId': 'msg_g_1', 'senderId': 'user_4', + 'content': 'Welcome to the Vertex Cloud workspace!', + 'timestamp': '2026-06-01T09:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + 'sales': [ + {'messageId': 'msg_s_1', 'senderId': 'user_1', + 'content': 'Globex renewal brief is finalized, prepping paperwork next.', + 'timestamp': '2026-06-19T11:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + } + + return { + 'currentUser': users[0], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Vertex Cloud', + 'icon': 'https://picsum.photos/64/64?random=workspace'}, + 'users': users, 'channels': channels, 'messages': messages, + 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], 'notifications': [], + } + + +# ---------------------------------------------------------------------------- +# Inject + verify (reset first for idempotency across adversarial rounds) +# ---------------------------------------------------------------------------- +def inject(name, state): + url = MOCK_URLS[name] + # Reset clears both initial and current so each round starts clean. + requests.post(f'{url}/post?sid={SID}', json={'action': 'reset'}, proxies=PROXIES, timeout=60) + resp = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': state}, + proxies=PROXIES, timeout=60) + assert resp.status_code == 200, f'{name} set failed: {resp.status_code} {resp.text[:300]}' + go = requests.get(f'{url}/go?sid={SID}', proxies=PROXIES, timeout=30).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'{name}: injected and verified') + + +inject('notion', build_notion_state()) +inject('docusign', build_docusign_state()) +inject('slack', build_slack_state()) + + +# --- Launch browser (GUI-ready). DocuSign is the primary deliverable. --- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + # Accept both a command string and a pre-split arg list (some tasks + # build arg lists themselves, e.g. se_hard_008). + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + # Inject CDP debug port so wait_mocks_loaded can verify browser render + # via Playwright connect_over_cdp. Idempotent: skip if any arg already + # starts with --remote-debugging-port (some tasks inject their own + # dynamic port, e.g. se_hard_008). + if _parts and 'google-chrome' in _parts[0] \ + and not any(p.startswith('--remote-debugging-port') for p in _parts): + _parts[1:1] = ['--no-first-run', '--no-default-browser-check', + '--remote-debugging-port=1337'] + _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env, + start_new_session=True) + time.sleep(delay_sec) + if _proc.poll() is not None: + print(' WARNING: launch_gui process exited early (code=%s)' + % _proc.returncode) + return _proc +notion_tab = f'{MOCK_URLS["notion"]}/?sid={SID}' +docusign_tab = f'{MOCK_URLS["docusign"]}/?sid={SID}' +slack_tab = f'{MOCK_URLS["slack"]}/?sid={SID}' +proxy_flag = f'--proxy-server="{PROXY}" ' if PROXIES else '' +launch_gui(f'google-chrome {proxy_flag}"{docusign_tab}" "{notion_tab}" "{slack_tab}"', delay_sec=3.0) +wait_mocks_loaded() +print('GUI_READY: launched Chrome with DocuSign + Notion + Slack tabs') +print(f'sid={SID}') diff --git a/am_renewal_contract_001/reward.py b/am_renewal_contract_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..3c651cd46b8ff91b53ce7bceac0e34bde5ed8c4d --- /dev/null +++ b/am_renewal_contract_001/reward.py @@ -0,0 +1,494 @@ +# --- MOCK_HOST_NO_PROXY_OVERRIDE: bypass woa proxy for locally-deployed mocks --- +import os as _os +_np = _os.environ.get("no_proxy", _os.environ.get("NO_PROXY", "")) +for _h in ("127.0.0.1", "localhost", "28.7.184.198"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +""" +Reward Script: Send Globex Corp renewal DocuSign envelope + post Slack notification +Task ID: am_renewal_contract_001 +Domain: mock_websites (docusign_mock + slack_mock) + +Scoring rubric (only scores task-introduced changes; each component FAILS on +initial_env and PASSES on golden_env): + + DocuSign (0.70): + C1 NEW envelope clearly relates to Globex renewal 0.15 + C2 Signer recipient = David Okafor (david.okafor@globex...) 0.15 + C3 CC recipient = finance@vertexcloud.example.com (role cc) 0.10 + C4 Envelope contains >= 1 document 0.05 + C5 Envelope is sent/out for signature 0.15 + C6 Terms match current brief ($85,000/85k), NOT FY24 ($72,000) 0.10 + Slack (0.30): + C7 NEW message from Jordan (currentUser) in #deal-desk 0.15 + C8 Message says Globex renewal envelope is sent 0.15 + + Total: 1.0 +""" + +import os +import re +import sys + +import requests + +DOCUSIGN_URL = 'http://28.7.184.198:8130' +SLACK_URL = 'http://28.7.184.198:8178' + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +# --- Egress proxy helper (MANDATORY) --- +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def resolve_proxy(probe_url): + try: + requests.get(probe_url, timeout=8) + return None + except Exception: + pass + for candidate in PROXY_CANDIDATES: + if not candidate: + continue + try: + requests.get( + probe_url, + timeout=12, + proxies={'http': candidate, 'https': candidate}, + ) + return candidate + except Exception: + continue + return None + + +PROXY = resolve_proxy(f'{DOCUSIGN_URL}/go?sid=conn-probe') +PROXIES = {'http': PROXY, 'https': PROXY} if PROXY else None +print(f'Egress proxy: {PROXY or "direct"}') + + +def fetch_state(base_url): + resp = requests.get(f'{base_url}/go?sid={sid}', timeout=15, proxies=PROXIES) + resp.raise_for_status() + return resp.json() + + +# --- Fetch both mocks --- +try: + ds = fetch_state(DOCUSIGN_URL) + sl = fetch_state(SLACK_URL) +except Exception as e: + print(f'CRITICAL: Cannot fetch mock state: {e}') + print('REWARD: 0.0') + sys.exit(0) + +ds_initial = ds.get('initial_state') or {} +ds_current = ds.get('current_state') or {} +sl_initial = sl.get('initial_state') or {} +sl_current = sl.get('current_state') or {} + + +TARGET_SIGNER_NAME = 'David Okafor' +TARGET_SIGNER_EMAIL = 'david.okafor@globex.example.com' +TARGET_CC_EMAIL = 'finance@vertexcloud.example.com' +TARGET_AMOUNT = 85000 +STALE_AMOUNT = 72000 +TARGET_CLOSE_DATE = (2026, 8, 30) +TARGET_CHANNEL = 'deal-desk' + + +def _txt(*vals): + """Lowercased concatenation of stringy values, ignoring None.""" + return ' '.join(str(v) for v in vals if v is not None).lower() + + +def _norm_text(value): + return re.sub(r'\s+', ' ', str(value or '').lower()).strip() + + +def _word_text(value): + return re.sub(r'[^a-z0-9]+', ' ', _norm_text(value)).strip() + + +def _norm_email(value): + return re.sub(r'\s+', '', str(value or '').lower()) + + +def _norm_role(value): + return _word_text(value) + + +def _norm_channel(value): + return re.sub(r'[^a-z0-9]+', '', str(value or '').lower().lstrip('#')) + + +def _name_matches(value, expected): + words = re.findall(r'[a-z]+', expected.lower()) + haystack = set(_word_text(value).split()) + return bool(words) and all(w in haystack for w in words) + + +def _role_is_signer(value): + role = _norm_role(value) + return role in {'signer', 'customer signer', 'authorized signer', 'signatory'} \ + or ' signer' in f' {role} ' or ' signatory' in f' {role} ' + + +def _role_is_cc(value): + role = _norm_role(value) + return role in { + 'cc', 'carbon copy', 'copy', 'copied', 'copy recipient', + 'receives a copy', 'receive a copy', + } or role.endswith(' cc') or ' carbon copy' in f' {role}' + + +def _contains_customer(value): + words = _word_text(value) + return 'globex' in words.split() or 'globex corp' in words \ + or 'globex corporation' in words + + +def _contains_renewal(value): + words = _word_text(value) + return any(term in words for term in ( + 'renewal', 'renew', 'renewed', 'contract', 'agreement', 'paperwork', + )) + + +def _extract_amounts(value): + text = _norm_text(value).replace(',', '') + amounts = [] + for match in re.finditer( + r'(? best_score: + best_env = env + best_score = score + return best_env if best_score >= 3.0 else None + + +def _get_channel_messages(state, target_channel): + messages = state.get('messages') or {} + target_norm = _norm_channel(target_channel) + candidate_keys = [] + for channel in state.get('channels') or []: + if _norm_channel(channel.get('channelId')) == target_norm \ + or _norm_channel(channel.get('name')) == target_norm: + candidate_keys.extend([channel.get('channelId'), channel.get('name')]) + candidate_keys.extend(messages.keys()) + + seen = set() + for key in candidate_keys: + if key is None or key in seen: + continue + seen.add(key) + if _norm_channel(key) == target_norm and isinstance(messages.get(key), list): + return messages.get(key) or [] + return [] + + +def _message_fingerprint(message): + return ( + message.get('senderId'), + _norm_text(message.get('content')), + message.get('timestamp'), + ) + + +def _mentions_sent_notification(value): + words = _word_text(value) + raw = _norm_text(value) + sent_terms = ( + 'sent', 'sent for signature', 'out for signature', 'out for signing', + 'went out', 'dispatched', 'issued', 'signature request', 'ready for signature', + ) + has_sent = any(term in raw or term in words for term in sent_terms) + has_doc_context = any(term in words for term in ( + 'renewal', 'renew', 'envelope', 'docusign', 'agreement', 'contract', 'paperwork', + )) + return _contains_customer(value) and has_doc_context and has_sent + + +def verify_task(): + total = 0.0 + + # ---------- Locate the NEW Globex renewal envelope ---------- + # Only envelopes that did not exist in initial_state count as task output. + globex_env = None + try: + init_ids = {e.get('id') for e in (ds_initial.get('envelopes') or [])} + new_envs = [e for e in (ds_current.get('envelopes') or []) + if e.get('id') not in init_ids] + templates_by_id = {t.get('id'): t for t in (ds_current.get('templates') or [])} + globex_env = _find_relevant_envelope(new_envs, templates_by_id) + except Exception as e: + print(f'ERROR: locating Globex envelope — {e}') + + # Component 1: NEW envelope clearly relates to the Globex renewal (0.15) + try: + if globex_env is not None: + print(f"PASS: C1 new Globex renewal envelope found " + f"(subject={globex_env.get('subject')!r}) (+0.15)") + total += 0.15 + else: + print('FAIL: C1 no NEW envelope clearly matching Globex renewal signals') + except Exception as e: + print(f'ERROR: C1 — {e}') + + recipients = (globex_env.get('recipients') or []) if globex_env else [] + + # Component 2: signer recipient David Okafor (0.15) + try: + signer_ok = _has_signer(recipients) + if signer_ok: + print('PASS: C2 signer = David Okafor (david.okafor@globex.example.com) (+0.15)') + total += 0.15 + else: + print('FAIL: C2 no signer recipient David Okafor with correct email') + except Exception as e: + print(f'ERROR: C2 — {e}') + + # Component 3: CC recipient finance mailbox (0.10) + try: + cc_ok = _has_finance_cc(recipients) + if cc_ok: + print('PASS: C3 CC = finance@vertexcloud.example.com (role cc) (+0.10)') + total += 0.10 + else: + print('FAIL: C3 no CC recipient finance@vertexcloud.example.com') + except Exception as e: + print(f'ERROR: C3 — {e}') + + # Component 4: envelope contains at least one document (0.05) + try: + docs = (globex_env.get('documents') or []) if globex_env else [] + if len(docs) >= 1: + print(f'PASS: C4 envelope has {len(docs)} document(s) (+0.05)') + total += 0.05 + else: + print('FAIL: C4 envelope has no documents') + except Exception as e: + print(f'ERROR: C4 — {e}') + + # Component 5: envelope SENT (status 'sent' + sentAt set) (0.15) + try: + status = _norm_text(globex_env.get('status')) if globex_env else '' + sent_at = globex_env.get('sentAt') if globex_env else None + if globex_env is not None and _is_sent_envelope(globex_env): + print(f"PASS: C5 envelope sent (status={status!r}, sentAt={sent_at!r}) (+0.15)") + total += 0.15 + else: + print(f'FAIL: C5 envelope not sent (status={status!r}, sentAt={sent_at!r})') + except Exception as e: + print(f'ERROR: C5 — {e}') + + # Component 6: terms match current brief ($85,000) and NOT FY24 ($72,000) (0.10) + # Search envelope subject, message, document names, and field values/labels. + try: + if globex_env is not None: + blob_parts = [globex_env.get('subject'), globex_env.get('message')] + for d in (globex_env.get('documents') or []): + blob_parts.append(d.get('name')) + for fld in (globex_env.get('fields') or []): + blob_parts.append(fld.get('value')) + blob_parts.append(fld.get('label')) + blob = _txt(*blob_parts) + has_current = _contains_amount(blob, TARGET_AMOUNT) + has_stale = _contains_amount(blob, STALE_AMOUNT) + if has_current and not has_stale: + print('PASS: C6 terms reference $85,000/85k (current brief), no FY24 $72,000 (+0.10)') + total += 0.10 + elif has_current and has_stale: + print('FAIL: C6 both $85,000 and stale $72,000 present — ambiguous terms') + else: + print('FAIL: C6 current term $85,000 not found in envelope text') + else: + print('FAIL: C6 no Globex envelope to inspect for terms') + except Exception as e: + print(f'ERROR: C6 — {e}') + + # ---------- Slack: new notification from Jordan in #deal-desk ---------- + new_dd_user_msgs = [] + try: + cur_user = (sl_current.get('currentUser') or {}).get('userId') or 'user_1' + init_dd = _get_channel_messages(sl_initial, TARGET_CHANNEL) + cur_dd = _get_channel_messages(sl_current, TARGET_CHANNEL) + init_msg_ids = {m.get('messageId') for m in init_dd if m.get('messageId')} + init_fingerprints = {_message_fingerprint(m) for m in init_dd} + # New messages = those not present in initial, authored by current user (Jordan) + new_dd_user_msgs = [ + m for m in cur_dd + if m.get('senderId') == cur_user + and ( + (m.get('messageId') and m.get('messageId') not in init_msg_ids) + or _message_fingerprint(m) not in init_fingerprints + ) + ] + except Exception as e: + print(f'ERROR: locating Slack message — {e}') + + # Component 7: NEW message from Jordan in #deal-desk (0.15) + try: + if new_dd_user_msgs: + print(f'PASS: C7 {len(new_dd_user_msgs)} new message(s) from Jordan in #deal-desk (+0.15)') + total += 0.15 + else: + print('FAIL: C7 no new message from current user (Jordan) in #deal-desk') + except Exception as e: + print(f'ERROR: C7 — {e}') + + # Component 8: that message says the Globex renewal envelope is sent/out for signature (0.15) + try: + ok_content = False + for m in new_dd_user_msgs: + c = m.get('content') or '' + has_terms = _contains_amount(c, TARGET_AMOUNT) \ + or _contains_date(c, *TARGET_CLOSE_DATE) + if _mentions_sent_notification(c) or ( + _contains_customer(c) and has_terms and _contains_renewal(c)): + ok_content = True + break + if ok_content: + print('PASS: C8 Slack message reports the Globex renewal envelope is sent (+0.15)') + total += 0.15 + else: + print('FAIL: C8 no new Jordan message clearly reports Globex renewal sent/out for signature') + except Exception as e: + print(f'ERROR: C8 — {e}') + + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + return final + + +verify_task() diff --git a/am_renewal_contract_001/reward_label.json b/am_renewal_contract_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..bf81b62de9e92bd22d447e99c4e64a5cc84b43b9 --- /dev/null +++ b/am_renewal_contract_001/reward_label.json @@ -0,0 +1,88 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_contract_003/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-03 20:14:37", + "label": { + "task_id": "am_renewal_contract_001", + "domain": "mock_websites", + "summary": "验证是否通过 DocuSign 向 David Okafor 发送了 Globex Corp 续约信封(含正确金额与抄送),并在 Slack #deal-desk 频道由 Jordan 发布通知。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "docusign_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.15, + "description": "检查是否存在新增的、明确与 Globex 续约相关的 DocuSign 信封", + "check_logic": "对比 ds_initial 与 ds_current 的 envelopes,排除 initial 中已存在的 id,通过 _find_relevant_envelope 对候选信封按 globex 客户名、renewal 关键词、signer、CC、金额 85000、已发送状态、文档数量等维度打分,返回 best_score >= 3.0 的最佳信封。若 globex_env 不为 None 则通过。", + "pass_condition": "在 current_state 中存在一个 initial_state 中没有的、且与 Globex 续约强相关的新信封" + }, + { + "name": "Component 2", + "weight": 0.15, + "description": "检查信封的 signer 收件人是否为 David Okafor", + "check_logic": "调用 _has_signer(recipients),要求收件人 role 经 _norm_role 归一化后属于 signer 类别,email 经 _norm_email 后等于 'david.okafor@globex.example.com',且 name 经 _name_matches 匹配 'David Okafor'。", + "pass_condition": "新增信封的 recipients 中存在 email 为 david.okafor@globex.example.com、name 为 David Okafor、role 为 signer 的收件人" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "检查信封是否存在 finance@vertexcloud.example.com 的 CC 收件人", + "check_logic": "调用 _has_finance_cc(recipients),要求收件人 role 经 _norm_role 归一化后属于 cc 类别,且 email 经 _norm_email 后等于 'finance@vertexcloud.example.com'。", + "pass_condition": "新增信封的 recipients 中存在 email 为 finance@vertexcloud.example.com、role 为 cc 的收件人" + }, + { + "name": "Component 4", + "weight": 0.05, + "description": "检查信封是否包含至少一份文档", + "check_logic": "获取 globex_env.get('documents'),判断列表长度是否 >= 1。", + "pass_condition": "新增信封的 documents 列表长度大于等于 1" + }, + { + "name": "Component 5", + "weight": 0.15, + "description": "检查信封是否已发送/待签署", + "check_logic": "调用 _is_sent_envelope(globex_env),检查 status 是否为 sent/delivered/out for signature 等,或 sentAt 字段存在,或 history 文本包含 sent 相关记录,或 recipients 的 status 为 sent/delivered/viewed。", + "pass_condition": "信封状态为已发送、已投递或待签署,或在历史记录/收件人状态中体现已发送" + }, + { + "name": "Component 6", + "weight": 0.1, + "description": "检查信封文本是否包含当前合同金额 $85,000/85k,且不包含旧金额 $72,000", + "check_logic": "收集信封的 subject、message、documents.name、fields.value/label 拼接为 blob,调用 _contains_amount(blob, 85000) 和 _contains_amount(blob, 72000)。仅当 has_current 为真且 has_stale 为假时通过。", + "pass_condition": "信封文本中包含 85000(或 85k)且不含 72000(或 72k)" + }, + { + "name": "Component 7", + "weight": 0.15, + "description": "检查 Slack #deal-desk 频道是否有 Jordan(当前用户)发送的新消息", + "check_logic": "获取 sl_current 的 currentUser.userId 作为 cur_user,对比 initial 与 current 的 #deal-desk 消息。排除 initial 中已存在的 messageId 或 fingerprint,筛选 senderId == cur_user 的消息。若 new_dd_user_msgs 非空则通过。", + "pass_condition": "#deal-desk 频道中存在 initial_state 中没有的、由当前用户(Jordan)发送的新消息" + }, + { + "name": "Component 8", + "weight": 0.15, + "description": "检查 Jordan 的新消息是否报告 Globex 续约信封已发送/待签署", + "check_logic": "遍历 new_dd_user_msgs,检查 content 是否满足 _mentions_sent_notification(c)(包含 globex、sent 相关词、文档上下文),或同时满足 _contains_customer(c)、_contains_renewal(c) 以及金额 85000 或日期 2026-08-30。", + "pass_condition": "新消息内容明确提及 Globex 续约信封已发送/已发出/待签署" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空时打印 CRITICAL 并返回 0.0", + "请求 docusign_mock 或 slack_mock 状态失败时打印 CRITICAL 并返回 0.0", + "未找到新的 Globex 续约信封导致 C1 失败,并连带使 C2-C6 无法通过", + "#deal-desk 频道没有 Jordan 的新消息导致 C7 失败,并连带使 C8 无法通过", + "C6 中同时出现 $85,000 与 $72,000 会被判定为 ambiguous terms 而失败" + ], + "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。", + "confidence": 1.0 + }, + "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- 不要输出 标签\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一切看起来都正确。 {\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}" +} diff --git a/ar_closeout_006/_cua_gym_vm_bridge.sh b/ar_closeout_006/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_closeout_006/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ar_closeout_006/initial_setup.py b/ar_closeout_006/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..37388987a5c8f594d27b51c6fcedc0c68d5bb11a --- /dev/null +++ b/ar_closeout_006/initial_setup.py @@ -0,0 +1,928 @@ +""" +Initial Setup: month-end AR closeout across seven live mock web apps. +Task ID: ar_closeout_006 +Domain: mock_websites + +The previous setup only opened a static dashboard backed by local JSON files. +This version injects the pre-task state into the shared mock services, persists +one sid for reward.py, verifies every service, and opens each app in Chrome. +""" +import base64 +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + + +TASK_ID = "prof20_ar_closeout_003" +BASE = "http://28.7.184.198" +MOCKS = { + "salesforce": f"{BASE}:8175", + "hubspot": f"{BASE}:8150", + "docusign": f"{BASE}:8130", + "google_sheets": f"{BASE}:8145", + "slack": f"{BASE}:8178", + "gmail": f"{BASE}:8138", + "google_docs": f"{BASE}:8142", +} + +# The VM bridge configures this globally; set it in-process as well so requests +# never sends the private mock host through the corporate HTTP proxy. +for proxy_var in ("no_proxy", "NO_PROXY"): + bypass = os.environ.get(proxy_var, "") + if "28.7.184.198" not in bypass: + os.environ[proxy_var] = ",".join(filter(None, [bypass, "28.7.184.198"])) + +SID = str(uuid.uuid4()) + + +def avatar(name): + return ( + "https://ui-avatars.com/api/?name=" + + name.replace(" ", "+") + + "&background=1A73E8&color=fff" + ) + + +def build_salesforce(): + users = [ + { + "userId": "user-ar", + "firstName": "Dana", + "lastName": "Whitman", + "email": "ar@saas-co.com", + "phone": "(555) 100-1000", + "title": "AR Specialist", + "department": "Finance", + "role": "Finance Operations", + "avatar": avatar("Dana Whitman"), + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + }, + { + "userId": "user-tom", + "firstName": "Tom", + "lastName": "Reyes", + "email": "tom.reyes@saas-co.com", + "phone": "(555) 100-1001", + "title": "Account Executive", + "department": "Sales", + "role": "User", + "avatar": avatar("Tom Reyes"), + "timezone": "America/Los_Angeles", + "locale": "en-US", + "theme": "lightning", + }, + ] + accounts = [ + { + "accountId": "acct-cobalt", + "name": "Cobalt Freight LLC", + "phone": "(303) 555-0174", + "website": "https://cobaltfreight.example", + "type": "Customer", + "industry": "Transportation", + "revenue": 120000000, + "employees": 900, + "description": "Enterprise freight and logistics account.", + "ownerId": "user-tom", + "billingStreet": "1700 Blake St", + "billingCity": "Denver", + "billingState": "CO", + "billingZip": "80202", + "billingCountry": "United States", + "shippingStreet": "1700 Blake St", + "shippingCity": "Denver", + "shippingState": "CO", + "shippingZip": "80202", + "shippingCountry": "United States", + "createdDate": "2025-02-10T09:00:00.000Z", + "modifiedDate": "2026-07-01T09:00:00.000Z", + }, + { + "accountId": "acct-sable", + "name": "Sable Robotics", + "phone": "(512) 555-0193", + "website": "https://sablerobotics.example", + "type": "Customer", + "industry": "Manufacturing", + "revenue": 28000000, + "employees": 180, + "description": "Industrial robotics customer.", + "ownerId": "user-tom", + "billingStreet": "600 Congress Ave", + "billingCity": "Austin", + "billingState": "TX", + "billingZip": "78701", + "billingCountry": "United States", + "shippingStreet": "600 Congress Ave", + "shippingCity": "Austin", + "shippingState": "TX", + "shippingZip": "78701", + "shippingCountry": "United States", + "createdDate": "2025-11-04T09:00:00.000Z", + "modifiedDate": "2026-07-01T09:00:00.000Z", + }, + ] + opportunities = [ + { + "opportunityId": "OPP-7740", + "name": "Cobalt Freight — Trial", + "accountId": "acct-cobalt", + "amount": 12000, + "closeDate": "2026-06-20T00:00:00.000Z", + "stage": "Closed Lost", + "probability": 0, + "ownerId": "user-tom", + "type": "New Business", + "leadSource": "Outbound", + "nextStep": "None — closed lost", + "description": "Trial opportunity. Closed Lost — do not process.", + "createdDate": "2026-05-10T09:00:00.000Z", + "modifiedDate": "2026-06-20T12:00:00.000Z", + }, + { + "opportunityId": "OPP-7741", + "name": "Cobalt Freight — Enterprise", + "accountId": "acct-cobalt", + "amount": 95000, + "closeDate": "2026-07-01T00:00:00.000Z", + "stage": "Closed Won", + "probability": 100, + "ownerId": "user-tom", + "type": "New Business", + "leadSource": "Outbound", + "nextStep": "Create draft invoice; finance approval required", + "description": ( + "Closed-Won enterprise deal. Payment Terms: Net 30. " + "Discount applied: 22% (approval threshold: 15%). " + "DocuSign: MSA — Cobalt Freight (OPP-7741)." + ), + "createdDate": "2026-05-20T09:00:00.000Z", + "modifiedDate": "2026-07-01T09:00:00.000Z", + }, + { + "opportunityId": "OPP-7743", + "name": "Sable Robotics — Pilot+", + "accountId": "acct-sable", + "amount": 18000, + "closeDate": "2026-07-01T00:00:00.000Z", + "stage": "Closed Won", + "probability": 100, + "ownerId": "user-tom", + "type": "New Business", + "leadSource": "Referral", + "nextStep": "Create $21,000 draft invoice; finance approval required", + "description": ( + "Closed-Won pilot. Payment Terms: Net 60. +$3,000 manual " + "invoice adjustment (approval threshold: $2,000; base $18,000; " + "invoice total $21,000). DocuSign: " + "MSA — Sable Robotics (OPP-7743)." + ), + "createdDate": "2026-06-02T09:00:00.000Z", + "modifiedDate": "2026-07-01T09:00:00.000Z", + }, + ] + return { + "user": users[0], + "users": users, + "leads": [], + "accounts": accounts, + "contacts": [], + "opportunities": opportunities, + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + "dashboards": [], + "emailDrafts": [], + "reportSnapshots": [], + } + + +def build_hubspot(): + stages = { + "appointment_scheduled": { + "id": "appointment_scheduled", + "label": "Appointment Scheduled", + "probability": 20, + "color": "#E5F4FF", + "order": 1, + }, + "qualified_to_buy": { + "id": "qualified_to_buy", + "label": "Qualified to Buy", + "probability": 40, + "color": "#FFF0E6", + "order": 2, + }, + "presentation_scheduled": { + "id": "presentation_scheduled", + "label": "Presentation Scheduled", + "probability": 60, + "color": "#FFF8E6", + "order": 3, + }, + "decision_maker_bought_in": { + "id": "decision_maker_bought_in", + "label": "Decision Maker Bought-In", + "probability": 80, + "color": "#E8F5E9", + "order": 4, + }, + "contract_sent": { + "id": "contract_sent", + "label": "Contract Sent", + "probability": 90, + "color": "#E6FFFA", + "order": 5, + }, + "closed_won": { + "id": "closed_won", + "label": "Closed Won", + "probability": 100, + "color": "#E6FFEC", + "order": 6, + }, + "closed_lost": { + "id": "closed_lost", + "label": "Closed Lost", + "probability": 0, + "color": "#FFE6E6", + "order": 7, + }, + } + ticket_statuses = { + "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1}, + "waiting_on_contact": { + "id": "waiting_on_contact", + "label": "Waiting on Contact", + "color": "#FFF8E6", + "order": 2, + }, + "waiting_on_us": { + "id": "waiting_on_us", + "label": "Waiting on Us", + "color": "#FFF0E6", + "order": 3, + }, + "in_progress": { + "id": "in_progress", + "label": "In Progress", + "color": "#E6FFFA", + "order": 4, + }, + "closed": { + "id": "closed", + "label": "Closed", + "color": "#E6FFEC", + "order": 5, + }, + } + return { + "contacts": [ + { + "id": "contact-verdant", + "firstName": "Contracts", + "lastName": "Team", + "email": "contracts@verdant-health.co", + "phone": "+1 (617) 555-0142", + "jobTitle": "Contracts Operations", + "companyId": "company-verdant", + "lifecycleStage": "customer", + "leadStatus": "open_deal", + "owner": "Lena Park", + "city": "Boston", + "state": "MA", + "country": "United States", + "createDate": "2026-03-10T09:00:00Z", + "lastActivityDate": "2026-07-01T09:00:00Z", + "timeline": [], + } + ], + "companies": [ + { + "id": "company-verdant", + "name": "Verdant Health Co.", + "domain": "verdant-health.co", + "industry": "Healthcare", + "phone": "+1 (617) 555-0100", + "city": "Boston", + "state": "MA", + "country": "United States", + "numberOfEmployees": 420, + "annualRevenue": 65000000, + "lifecycleStage": "customer", + "owner": "Lena Park", + "description": "Healthcare platform customer.", + "createDate": "2026-03-10T09:00:00Z", + } + ], + "deals": [ + { + "id": "D-7742", + "name": "Verdant Health — Platform", + "companyId": "company-verdant", + "contactIds": ["contact-verdant"], + "amount": 41000, + "stage": "closed_won", + "closeDate": "2026-07-01", + "dealType": "new_business", + "priority": "high", + "owner": "Lena Park", + "probability": 100, + "description": ( + "Closed Won. Payment Terms: Net 45. Discount: 0%. " + "DocuSign envelope " + "MSA — Verdant Health (D-7742) is still awaiting signature." + ), + "createDate": "2026-05-20T10:00:00Z", + "lastActivityDate": "2026-07-01T09:00:00Z", + } + ], + "tickets": [], + "tasks": [], + "notes": [], + "templates": [], + "meetings": [], + "forms": [], + "dealStages": stages, + "ticketStatuses": ticket_statuses, + "appState": { + "sidebarOpen": True, + "currentUser": { + "name": "Dana Whitman", + "email": "ar@saas-co.com", + "avatar": None, + }, + }, + } + + +def envelope(eid, subject, status, signer_name, signer_email, deal_id): + completed = status == "completed" + return { + "id": eid, + "subject": subject, + "message": f"Master Service Agreement for {deal_id}.", + "status": status, + "createdAt": "2026-06-25T09:00:00Z", + "sentAt": "2026-06-25T09:05:00Z", + "completedAt": "2026-06-30T15:30:00Z" if completed else None, + "voidedAt": None, + "declinedAt": None, + "lastActivityAt": ( + "2026-06-30T15:30:00Z" if completed else "2026-06-25T09:05:00Z" + ), + "expiresAt": "2026-10-23T09:05:00Z", + "senderId": "user-ar", + "folderId": None, + "templateId": None, + "reminderEnabled": True, + "reminderDays": 3, + "reminderFrequency": 2, + "documents": [ + { + "id": f"doc-{eid}", + "name": f"{subject}.pdf", + "pageCount": 8, + "order": 1, + "fileUrl": f"https://picsum.photos/seed/{eid}/800/1100", + "fileType": "pdf", + } + ], + "recipients": [ + { + "id": f"rec-{eid}", + "name": signer_name, + "email": signer_email, + "role": "signer", + "routingOrder": 1, + "status": "signed" if completed else "sent", + "signedAt": "2026-06-30T15:30:00Z" if completed else None, + "viewedAt": "2026-06-30T15:20:00Z" if completed else None, + "deliveredAt": "2026-06-25T09:10:00Z", + "declinedAt": None, + "declineReason": None, + } + ], + "fields": [], + "history": [], + } + + +def build_docusign(): + user = { + "id": "user-ar", + "name": "Dana Whitman", + "email": "ar@saas-co.com", + "title": "AR Specialist", + "company": "SaaS-Co", + "avatar": avatar("Dana Whitman"), + "memberSince": "2023-02-01", + "settings": { + "defaultReminderDays": 3, + "defaultExpirationDays": 120, + "timezone": "America/New_York", + }, + } + return { + "user": user, + "envelopes": [ + envelope( + "env-7741", + "MSA — Cobalt Freight (OPP-7741)", + "completed", + "Morgan Lee", + "contracts@cobaltfreight.com", + "OPP-7741", + ), + envelope( + "env-7742", + "MSA — Verdant Health (D-7742)", + "sent", + "Verdant Contracts", + "contracts@verdant-health.co", + "D-7742", + ), + envelope( + "env-7743", + "MSA — Sable Robotics (OPP-7743)", + "completed", + "Avery Stone", + "legal@sablerobotics.com", + "OPP-7743", + ), + ], + "templates": [], + "folders": [], + "contacts": [], + "auditLog": [], + } + + +def cell(value, bold=False): + result = {"value": str(value), "formula": str(value)} + if bold: + result["style"] = {"bold": True, "bg": "#E8EAED", "align": "center"} + return result + + +LEDGER_ROWS = [ + ["INV-7701", "Northwind Traders", "$12,400", "Net 30", "Paid", "Salesforce OPP-7690", "2026-06-03"], + ["INV-7702", "Acme Logistics", "$8,900", "Net 30", "Paid", "HubSpot D-7691", "2026-06-03"], + ["INV-7703", "Helios Energy", "$33,250", "Net 45", "Draft", "Salesforce OPP-7692", "2026-06-04"], + ["INV-7704", "Brightline Media", "$4,150", "Net 15", "Paid", "HubSpot D-7693", "2026-06-05"], + ["INV-7705", "Quanta Systems", "$21,700", "Net 60", "Draft", "Salesforce OPP-7694", "2026-06-06"], + ["INV-7706", "Meridian Labs", "$15,300", "Net 30", "Paid", "HubSpot D-7695", "2026-06-08"], + ["INV-7707", "Cascade Foods", "$9,800", "Net 30", "Draft", "Salesforce OPP-7696", "2026-06-09"], + ["INV-7708", "Pioneer Steel", "$47,000", "Net 45", "Paid", "Salesforce OPP-7697", "2026-06-10"], + ["INV-7709", "Lumen Health", "$28,400", "Net 30", "Draft", "HubSpot D-7698", "2026-06-11"], + ["INV-7710", "Atlas Freight", "$11,300", "Net 30", "Paid", "Salesforce OPP-7699", "2026-06-12"], + ["INV-7711", "Vertex Pharmaceuticals", "$62,500", "Net 60", "Draft", "Salesforce OPP-7700", "2026-06-13"], + ["INV-7712", "Cedar Works", "$6,750", "Net 15", "Paid", "HubSpot D-7701", "2026-06-15"], + ["INV-7713", "Orion Analytics", "$19,200", "Net 30", "Draft", "Salesforce OPP-7702", "2026-06-16"], + ["INV-7714", "Granite Bank", "$54,900", "Net 45", "Paid", "Salesforce OPP-7703", "2026-06-17"], + ["INV-7715", "Solstice Retail", "$13,600", "Net 30", "Draft", "HubSpot D-7704", "2026-06-18"], + ["INV-7716", "Tundra Mining", "$38,300", "Net 60", "Paid", "Salesforce OPP-7705", "2026-06-19"], + ["INV-7717", "Harbor Logistics", "$7,450", "Net 30", "Draft", "HubSpot D-7706", "2026-06-20"], + ["INV-7718", "Evergreen Utilities", "$24,800", "Net 45", "Paid", "Salesforce OPP-7707", "2026-06-21"], +] + + +def build_sheets(): + headers = [ + "Invoice ID", + "Account Name", + "Amount", + "Payment Terms", + "Status", + "Source", + "Created Date", + ] + cols = "ABCDEFG" + data = {} + for idx, value in enumerate(headers): + data[f"{cols[idx]}1"] = cell(value, bold=True) + for row_idx, row in enumerate(LEDGER_ROWS, start=2): + for col_idx, value in enumerate(row): + data[f"{cols[col_idx]}{row_idx}"] = cell(value) + return { + "id": "workbook-invoice-ledger", + "title": "Invoice Ledger", + "activeSheetId": "sheet-fy26", + "selectedCell": "A20", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [ + { + "id": "sheet-fy26", + "name": "FY26 Invoices", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": "#1A73E8", + "isHidden": False, + "columnWidths": { + "0": 110, + "1": 190, + "2": 100, + "3": 120, + "4": 100, + "5": 180, + "6": 120, + }, + "data": data, + } + ], + } + + +def slack_user(uid, name, display, email, title): + return { + "userId": uid, + "fullName": name, + "displayName": display, + "email": email, + "avatar": avatar(name), + "title": title, + "status": "online", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York", + } + + +def build_slack(): + users = [ + slack_user("user-ar", "Dana Whitman", "Dana", "ar@saas-co.com", "AR Specialist"), + slack_user("user-tom", "Tom Reyes", "Tom", "tom.reyes@saas-co.com", "Account Executive"), + slack_user("user-lena", "Lena Park", "Lena", "lena.park@saas-co.com", "Account Executive"), + slack_user("user-controller", "Rebecca Liu", "Rebecca", "rebecca.liu@saas-co.com", "Controller"), + ] + members = [u["userId"] for u in users] + + def channel(cid, description): + return { + "channelId": cid, + "name": cid, + "description": description, + "topic": "Month-end AR close", + "isPrivate": False, + "isStarred": True, + "members": members, + "createdBy": "user-controller", + "createdAt": "2026-01-05T09:00:00Z", + "pinnedMessages": [], + "unreadCount": 0, + } + + return { + "currentUser": users[0], + "workspace": {"workspaceId": "ws-saas", "workspaceName": "SaaS-Co", "icon": ""}, + "users": users, + "channels": [ + channel("finance-approvals", "Discount and invoice-adjustment approvals"), + channel("finance-ar", "Accounts receivable reminders and escalations"), + ], + "messages": { + "finance-approvals": [ + { + "messageId": "msg-hist-approval", + "senderId": "user-controller", + "content": "Q2 closeout approvals have all been archived.", + "timestamp": "2026-06-02T14:03:00Z", + "threadId": None, + "reactions": [], + "attachments": [], + "isEdited": False, + } + ], + "finance-ar": [ + { + "messageId": "msg-hist-ar", + "senderId": "user-ar", + "content": "INV-7703 moved to the collections queue.", + "timestamp": "2026-06-05T09:15:00Z", + "threadId": None, + "reactions": [], + "attachments": [], + "isEdited": False, + } + ], + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": { + "theme": "light", + "notifications": "all", + "displayDensity": "comfortable", + "showAvatars": True, + "use24Hour": False, + }, + "invitations": [], + "notifications": [], + } + + +def build_gmail(): + return { + "user": { + "userId": "user-ar", + "username": "Dana Whitman", + "email": "ar@saas-co.com", + "avatar": avatar("Dana Whitman"), + }, + "emails": [ + { + "id": "mail-historical", + "threadId": "thread-historical", + "from": {"name": "Controller", "email": "controller@saas-co.com"}, + "to": [{"name": "Dana Whitman", "email": "ar@saas-co.com"}], + "cc": [], + "bcc": [], + "subject": "Month-end AR close", + "body": "

Please complete the July 1 AR closeout.

", + "timestamp": "2026-07-01T08:00:00Z", + "read": True, + "starred": True, + "important": True, + "labels": ["l1"], + "category": "primary", + "folder": "inbox", + "attachments": [], + } + ], + "labels": [ + {"id": "l1", "name": "Finance", "color": "#1A73E8"}, + {"id": "l2", "name": "Contracts", "color": "#22C55E"}, + ], + "drafts": [], + "settings": { + "density": "default", + "undoSend": 10, + "signature": "", + "categoryTabs": { + "primary": True, + "social": True, + "promotions": True, + "updates": False, + "forums": False, + }, + "replyBehavior": "Reply", + "language": "English (US)", + "sysLabelShown": {}, + "userLabelShown": {}, + }, + } + + +def build_docs(): + user = { + "id": "user-ar", + "name": "Dana Whitman", + "email": "ar@saas-co.com", + "avatar": avatar("Dana Whitman"), + } + return { + "currentUser": user, + "users": [user], + # Docs deep-merges its default document map. Reuse all five default IDs + # so unrelated demo documents cannot leak into this task's UI/state. + "documents": { + "doc-1": { + "id": "doc-1", + "title": "Q1 Closeout — 2026-04-01", + "content": ( + "

Q1 Closeout — 2026-04-01

" + "

1. Signed & Awaiting Approval

" + "

Prior-quarter approvals archived.

" + "

2. Unsigned & Reminded

" + "

Prior-quarter reminders complete.

" + "

3. Summary

Q1 close complete.

" + ), + "ownerId": "user-ar", + "starred": False, + "created": "2026-04-01T10:00:00Z", + "updated": "2026-04-01T16:00:00Z", + "sharedWith": [], + "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + "doc-2": { + "id": "doc-2", + "title": "Collections Notes — 2026-06", + "content": "

Collections Notes — 2026-06

Archived.

", + "ownerId": "user-ar", + "starred": False, + "created": "2026-06-01T10:00:00Z", + "updated": "2026-06-30T16:00:00Z", + "sharedWith": [], + "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + "doc-3": { + "id": "doc-3", + "title": "Invoice Review Notes", + "content": "

Invoice Review Notes

Archived.

", + "ownerId": "user-ar", + "starred": False, + "created": "2026-05-01T10:00:00Z", + "updated": "2026-05-31T16:00:00Z", + "sharedWith": [], + "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + "doc-4": { + "id": "doc-4", + "title": "Approval Archive", + "content": "

Approval Archive

Archived.

", + "ownerId": "user-ar", + "starred": False, + "created": "2026-04-01T10:00:00Z", + "updated": "2026-04-30T16:00:00Z", + "sharedWith": [], + "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + "doc-5": { + "id": "doc-5", + "title": "AR Process Reference", + "content": "

AR Process Reference

Archived.

", + "ownerId": "user-ar", + "starred": False, + "created": "2026-01-01T10:00:00Z", + "updated": "2026-03-31T16:00:00Z", + "sharedWith": [], + "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + }, + "comments": [], + "ui": { + "currentDocId": None, + "sidebarOpen": False, + "sidebarTab": "comments", + "shareDialogOpen": False, + "findReplaceOpen": False, + "viewMode": "editing", + "zoom": 100, + "documentListView": "grid", + "searchQuery": "", + }, + } + + +BUILDERS = { + "salesforce": build_salesforce, + "hubspot": build_hubspot, + "docusign": build_docusign, + "google_sheets": build_sheets, + "slack": build_slack, + "gmail": build_gmail, + "google_docs": build_docs, +} + + +def inject(name, state): + url = f"{MOCKS[name]}/post?sid={SID}" + reset = requests.post(url, json={"action": "reset"}, timeout=30) + reset.raise_for_status() + response = requests.post( + url, json={"action": "set", "state": state}, timeout=30 + ) + response.raise_for_status() + print(f"[initial_setup] injected {name}") + + +def verify(name): + response = requests.get(f"{MOCKS[name]}/go?sid={SID}", timeout=20) + response.raise_for_status() + state = response.json() + assert state.get("initial_state") is not None, f"{name}: missing initial_state" + assert state.get("current_state") is not None, f"{name}: missing current_state" + + +def launch_gui(command, delay_sec=3.0): + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + + +def seed_docs_browser_state(state): + """Work around Docs' first-load race by seeding its sid-scoped localStorage. + + google_docs_mock currently writes default data to localStorage during its + synchronous reducer initialization. Its later custom-state effect then + mistakes that key for a refresh and skips fetching the injected state, + before posting the defaults back to /post. Seed the already-open Docs tab + with the same state and reload it so both the visible UI and server-side + current_state remain aligned with the injected initial_state. + """ + import pyautogui + + encoded = base64.b64encode( + json.dumps(state, separators=(",", ":")).encode("utf-8") + ).decode("ascii") + state_key = f"google_docs_mock_state_{SID}" + initial_key = f"google_docs_mock_initial_{SID}" + javascript = ( + "javascript:(()=>{" + f"const s=JSON.parse(atob('{encoded}'));" + f"localStorage.setItem('{state_key}',JSON.stringify(s));" + f"localStorage.setItem('{initial_key}',JSON.stringify(s));" + "location.reload()" + "})()" + ) + + # Docs is launched as the final Chrome tab. Ctrl+9 selects the last tab + # even when setup is rerun in an already-open Chrome session. + pyautogui.hotkey("ctrl", "9") + time.sleep(1.0) + pyautogui.hotkey("ctrl", "l") + pyautogui.write(javascript, interval=0.0001) + pyautogui.press("enter") + + expected_titles = { + document["title"] for document in state["documents"].values() + } + deadline = time.time() + 20 + while time.time() < deadline: + try: + payload = requests.get( + f'{MOCKS["google_docs"]}/go?sid={SID}', timeout=5 + ).json() + current = payload.get("current_state") or {} + current_titles = { + document.get("title") + for document in (current.get("documents") or {}).values() + } + if current_titles == expected_titles: + return + except Exception: + pass + time.sleep(1.0) + raise RuntimeError("google_docs: browser state did not match injected state") + + +def main(): + with open("/tmp/task_web_sid", "w") as f: + f.write(SID) + print(f"[initial_setup] sid={SID}") + + for name, builder in BUILDERS.items(): + inject(name, builder()) + for name in MOCKS: + verify(name) + + sheets = requests.get( + f'{MOCKS["google_sheets"]}/go?sid={SID}', timeout=20 + ).json()["current_state"] + sheet_data = sheets["sheets"][0]["data"] + assert sheet_data["A19"]["value"] == "INV-7718" + assert "A20" not in sheet_data + + urls = [ + f'{MOCKS["salesforce"]}/opportunities', + f'{MOCKS["hubspot"]}/deals', + f'{MOCKS["docusign"]}/agreements/sent', + f'{MOCKS["google_sheets"]}/spreadsheet', + f'{MOCKS["slack"]}/channel/finance-approvals', + MOCKS["gmail"], + MOCKS["google_docs"], + ] + tabs = " ".join(f'"{url}?sid={SID}"' for url in urls) + launch_gui( + "google-chrome --no-first-run --no-default-browser-check " + tabs, + delay_sec=4.0, + ) + seed_docs_browser_state(build_docs()) + print( + "GUI_READY: launched Salesforce, HubSpot, DocuSign, Sheets, Slack, " + f"Gmail, and Docs (sid={SID})" + ) + + +if __name__ == "__main__": + main() diff --git a/ar_closeout_006/reward.py b/ar_closeout_006/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..078e63f9e0c46d1b648e351524acf1a048a29ff8 --- /dev/null +++ b/ar_closeout_006/reward.py @@ -0,0 +1,624 @@ +""" +Reward: AR Closeout across live Google Sheets, Slack, Gmail, and Google Docs. +Task ID: ar_closeout_006 +Domain: mock_websites + +All checks read each CUA-Gym-Hub backend through /go?sid=... and score only +task-introduced changes relative to initial_state. +""" +import html +import json +import os +import re +from datetime import date, datetime +from decimal import Decimal, InvalidOperation + +import requests + + +BASE = "http://28.7.184.198" +MOCKS = { + "google_sheets": f"{BASE}:8145", + "slack": f"{BASE}:8178", + "gmail": f"{BASE}:8138", + "google_docs": f"{BASE}:8142", +} + +for proxy_var in ("no_proxy", "NO_PROXY"): + bypass = os.environ.get(proxy_var, "") + if "28.7.184.198" not in bypass: + os.environ[proxy_var] = ",".join(filter(None, [bypass, "28.7.184.198"])) + +APPROVAL_7741 = ( + "APPROVAL NEEDED: OPP-7741 Cobalt Freight LLC — 22% discount on $95,000 " + "invoice INV-7741 exceeds 15% threshold. AE: Tom Reyes. Envelope signed." +) +APPROVAL_7743 = ( + "APPROVAL NEEDED: OPP-7743 Sable Robotics — $3,000 invoice adjustment on " + "$18,000 base (INV-7743, total $21,000) exceeds $2,000 threshold. " + "AE: Tom Reyes. Envelope signed." +) +AR_REMINDER = ( + "Reminder: MSA — Verdant Health (D-7742) unsigned; Gmail nudge sent to " + "contracts@verdant-health.co. AE: Lena Park. $41,000 Net 45." +) +SUMMARY = ( + "3 deals processed; 2 approval posts to #finance-approvals; 1 Gmail reminder " + "sent; 3 invoice rows added to Invoice Ledger." +) + + +def read_sid(): + try: + with open("/tmp/task_web_sid") as f: + sid = f.read().strip() + if not sid: + raise ValueError("empty sid") + return sid + except Exception as exc: + print(f"CRITICAL: cannot read /tmp/task_web_sid: {exc}") + return None + + +def fetch_states(name, sid): + response = requests.get(f"{MOCKS[name]}/go?sid={sid}", timeout=30) + response.raise_for_status() + payload = response.json() + initial = payload.get("initial_state") + current = payload.get("current_state") + if not isinstance(initial, dict) or not isinstance(current, dict): + raise ValueError(f"{name}: /go returned invalid initial/current state") + return initial, current + + +def norm(value): + text = html.unescape(str(value or "")) + text = text.replace("—", "-").replace("–", "-").replace("‐", "-") + text = text.replace("\u00a0", " ").replace("’", "'").replace("‘", "'") + return re.sub(r"\s+", " ", text).strip().lower() + + +def norm_ignoring_long_dash(value): + """Normalize text while ignoring missing or substituted long dashes.""" + text = html.unescape(str(value or "")) + text = re.sub(r"[—–‐]", "", text) + text = re.sub(r"(?]*>", + "\n", + markup, + flags=re.IGNORECASE, + ) + return norm(re.sub(r"<[^>]+>", " ", markup)) + + +def parse_money(value): + """Return a Decimal amount while rejecting digit-collision false positives.""" + if isinstance(value, bool) or value in (None, ""): + return None + text = str(value).strip().replace("$", "").replace(",", "") + text = re.sub(r"\s+", "", text) + if not re.fullmatch(r"[-+]?\d+(?:\.\d+)?", text): + return None + try: + return Decimal(text) + except InvalidOperation: + return None + + +def parse_ymd(value): + """Parse common spreadsheet date representations into (year, month, day).""" + if isinstance(value, datetime): + return value.date().timetuple()[:3] + if isinstance(value, date): + return value.timetuple()[:3] + text = str(value or "").strip() + for pattern in ( + r"^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$", + r"^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$", + ): + match = re.match(pattern, text) + if not match: + continue + parts = tuple(int(part) for part in match.groups()) + year, month, day = parts if len(match.group(1)) == 4 else (parts[2], parts[0], parts[1]) + try: + date(year, month, day) + return year, month, day + except ValueError: + return None + return None + + +def component(idx, name, weight, passed, detail, description=""): + score = weight if passed else 0.0 + print(f"{'PASS' if passed else 'FAIL'}: Component {idx} — {name} — {detail}") + print( + "COMPONENT: " + + json.dumps( + { + "id": idx, + "name": name, + "weight": weight, + "passed": passed, + "score": score, + "detail": detail, + "description": description, + } + ) + ) + return score + + +def sheet_rows(state): + sheets = state.get("sheets") or [] + sheet = next((s for s in sheets if s.get("name") == "FY26 Invoices"), None) + if not sheet: + return {} + data = sheet.get("data") or {} + row_numbers = sorted( + { + int(match.group(1)) + for key in data + for match in [re.match(r"^[A-Z]+(\d+)$", key)] + if match + } + ) + rows = {} + for row_num in row_numbers: + values = [ + (data.get(f"{col}{row_num}") or {}).get("value") + for col in "ABCDEFG" + ] + if any(value not in (None, "") for value in values): + rows[row_num] = values + return rows + + +def invoice_map(rows): + invoices = {} + for row_num, row in rows.items(): + invoice_id = str(row[0] or "").strip().upper() + if invoice_id.startswith("INV-"): + invoices.setdefault(invoice_id, []).append((row_num, row)) + return invoices + + +def invoice_row_matches(actual, expected): + checks = [ + norm(actual[0]) == norm(expected[0]), + norm(actual[1]) == norm(expected[1]), + parse_money(actual[2]) == parse_money(expected[2]), + norm(actual[3]) == norm(expected[3]), + norm(actual[4]) == norm(expected[4]), + norm(actual[5]) == norm(expected[5]), + parse_ymd(actual[6]) == parse_ymd(expected[6]), + ] + return all(checks) + + +def check_sheets(initial, current): + """Verify exactly three invoice rows were added and all original rows stayed intact.""" + initial_rows = sheet_rows(initial) + current_rows = sheet_rows(current) + initial_map = invoice_map(initial_rows) + current_map = invoice_map(current_rows) + expected = { + "INV-7741": [ + "INV-7741", + "Cobalt Freight LLC", + "$95,000", + "Net 30", + "Draft", + "Salesforce OPP-7741", + "2026-07-01", + ], + "INV-7742": [ + "INV-7742", + "Verdant Health Co.", + "$41,000", + "Net 45", + "Draft", + "HubSpot D-7742", + "2026-07-01", + ], + "INV-7743": [ + "INV-7743", + "Sable Robotics", + "$21,000", + "Net 60", + "Draft", + "Salesforce OPP-7743", + "2026-07-01", + ], + } + + if any(invoice_id in initial_map for invoice_id in expected): + return False, "target invoice already existed in initial_state" + + for row_num, initial_row in initial_rows.items(): + if current_rows.get(row_num) != initial_row: + return False, f"original ledger row {row_num} was modified or removed" + + if len(current_rows) != len(initial_rows) + 3: + return False, ( + f"expected exactly 3 new non-empty rows, initial={len(initial_rows)}, " + f"current={len(current_rows)}" + ) + + new_rows = { + row_num: row + for row_num, row in current_rows.items() + if row_num not in initial_rows + } + if any( + "opp-7740" in norm(" ".join(str(value or "") for value in row)) + or "inv-7740" in norm(" ".join(str(value or "") for value in row)) + for row in new_rows.values() + ): + return False, "distractor OPP-7740/INV-7740 was processed in the ledger" + + failures = [] + for invoice_id, expected_row in expected.items(): + rows = current_map.get(invoice_id, []) + if len(rows) != 1: + failures.append(f"{invoice_id}: expected one row, found {len(rows)}") + elif rows[0][0] not in new_rows: + failures.append(f"{invoice_id}: row was not task-introduced") + elif not invoice_row_matches(rows[0][1], expected_row): + failures.append(f"{invoice_id}: values={rows[0][1]!r}") + if failures: + return False, "; ".join(failures) + return True, "three exact new invoice rows added; original ledger preserved" + + +def item_identity(item, id_field): + item_id = item.get(id_field) if isinstance(item, dict) else None + if item_id not in (None, ""): + return ("id", str(item_id)) + return ( + "value", + json.dumps(item, sort_keys=True, ensure_ascii=False, default=str), + ) + + +def initial_items_preserved(initial_items, current_items, id_field): + current_by_identity = { + item_identity(item, id_field): item for item in current_items + } + for item in initial_items: + identity = item_identity(item, id_field) + if current_by_identity.get(identity) != item: + return False, identity + return True, None + + +def new_slack_messages(initial, current, channel_id): + initial_messages = (initial.get("messages") or {}).get(channel_id) or [] + current_messages = (current.get("messages") or {}).get(channel_id) or [] + initial_ids = { + item_identity(message, "messageId") for message in initial_messages + } + return [ + message + for message in current_messages + if item_identity(message, "messageId") not in initial_ids + ] + + +def message_matches(content, required): + text = norm(content) + return all(norm(token) in text for token in required) + + +def check_approval_slack(initial, current): + """Verify exactly two new, distinct approval posts with all required details.""" + initial_messages = (initial.get("messages") or {}).get("finance-approvals") or [] + current_messages = (current.get("messages") or {}).get("finance-approvals") or [] + preserved, changed = initial_items_preserved( + initial_messages, current_messages, "messageId" + ) + if not preserved: + return False, f"historical approval message changed or disappeared: {changed}" + messages = new_slack_messages(initial, current, "finance-approvals") + if len(messages) != 2: + return False, f"expected exactly 2 new approval posts, found {len(messages)}" + requirements = [ + [ + "approval needed", + "OPP-7741", + "Cobalt Freight LLC", + "22%", + "$95,000", + "INV-7741", + "15% threshold", + "Tom Reyes", + "Envelope signed", + ], + [ + "approval needed", + "OPP-7743", + "Sable Robotics", + "$3,000", + "$18,000", + "INV-7743", + "$21,000", + "$2,000 threshold", + "Tom Reyes", + "Envelope signed", + ], + ] + matched_indices = set() + for required in requirements: + match_idx = next( + ( + idx + for idx, message in enumerate(messages) + if idx not in matched_indices + and message_matches(message.get("content"), required) + ), + None, + ) + if match_idx is None: + return False, ( + f"only {len(matched_indices)}/2 distinct approval posts matched" + ) + matched_indices.add(match_idx) + return True, "two distinct task-introduced approval posts matched" + + +def check_ar_slack(initial, current): + """Verify exactly one new AR reminder with all required unsigned-deal details.""" + initial_messages = (initial.get("messages") or {}).get("finance-ar") or [] + current_messages = (current.get("messages") or {}).get("finance-ar") or [] + preserved, changed = initial_items_preserved( + initial_messages, current_messages, "messageId" + ) + if not preserved: + return False, f"historical AR message changed or disappeared: {changed}" + messages = new_slack_messages(initial, current, "finance-ar") + if len(messages) != 1: + return False, f"expected exactly 1 new AR reminder, found {len(messages)}" + required = [ + "Reminder", + "MSA", + "Verdant Health", + "D-7742", + "unsigned", + "Gmail nudge sent", + "contracts@verdant-health.co", + "Lena Park", + "$41,000", + "Net 45", + ] + if any(message_matches(message.get("content"), required) for message in messages): + return True, "new #finance-ar reminder contains all required details" + return False, f"no qualifying new reminder among {len(messages)} message(s)" + + +def recipient_emails(email_obj): + recipients = email_obj.get("to") or [] + if isinstance(recipients, (str, dict)): + recipients = [recipients] + result = [] + for recipient in recipients: + if isinstance(recipient, dict): + result.append(norm(recipient.get("email"))) + else: + result.append(norm(recipient)) + return result + + +def check_gmail(initial, current): + """Verify one exact task-introduced sent email from AR to the contract signer.""" + preserved, changed = initial_items_preserved( + initial.get("emails") or [], current.get("emails") or [], "id" + ) + if not preserved: + return False, f"historical email changed or disappeared: {changed}" + initial_ids = { + item_identity(email_obj, "id") for email_obj in initial.get("emails") or [] + } + sent = [ + email_obj + for email_obj in current.get("emails") or [] + if item_identity(email_obj, "id") not in initial_ids + and norm(email_obj.get("folder")) == "sent" + ] + if len(sent) != 1: + return False, f"expected exactly 1 new sent email, found {len(sent)}" + + target = "contracts@verdant-health.co" + expected_subject = "Action required: Please sign MSA — Verdant Health (D-7742)" + body_tokens = [ + "Your MSA for the Verdant Health platform", + "D-7742", + "$41,000", + "Net 45", + "awaiting signature", + "MSA — Verdant Health (D-7742)", + ] + for email_obj in sent: + if recipient_emails(email_obj) != [norm(target)]: + continue + sender = email_obj.get("from") or {} + sender_email = sender.get("email") if isinstance(sender, dict) else sender + account = current.get("user") or {} + account_email = account.get("email") if isinstance(account, dict) else "" + effective_sender = sender_email or account_email + if norm(effective_sender) != norm("ar@saas-co.com"): + continue + if email_obj.get("cc") or email_obj.get("bcc"): + continue + if norm_ignoring_long_dash(email_obj.get("subject")) != norm_ignoring_long_dash( + expected_subject + ): + continue + body = norm_ignoring_long_dash(plain_html(email_obj.get("body"))) + if "opp-7740" in body or "inv-7740" in body: + continue + if all(norm_ignoring_long_dash(token) in body for token in body_tokens): + return True, "task-introduced Gmail reminder has exact recipient/subject/details" + return False, "the new sent email has incorrect sender/recipient/subject/body" + + +def title_matches(value): + return norm_ignoring_long_dash(value) == norm_ignoring_long_dash( + "AR Closeout — 2026-07-01" + ) + + +def marked_as_heading_or_bold(content, heading): + normalized_html = html.unescape(str(content or "")).replace("—", "-").replace("–", "-") + normalized_heading = heading.replace("—", "-").replace("–", "-") + escaped = re.escape(normalized_heading) + patterns = [ + rf"]*>.*?{escaped}.*?", + rf"<(?:strong|b)[^>]*>.*?{escaped}.*?", + ] + return any( + re.search(pattern, normalized_html, flags=re.IGNORECASE | re.DOTALL) + for pattern in patterns + ) + + +def check_docs(initial, current): + """Verify one new closeout document with ordered bold sections and scoped content.""" + initial_docs = initial.get("documents") or {} + current_docs = current.get("documents") or {} + for doc_id, initial_document in initial_docs.items(): + if current_docs.get(doc_id) != initial_document: + return False, ( + f"existing document {doc_id} changed or was overwritten " + "(possible first-load state race)" + ) + new_docs = [ + document + for doc_id, document in current_docs.items() + if doc_id not in initial_docs + ] + if len(new_docs) != 1: + return False, f"expected exactly one new document, found {len(new_docs)}" + candidates = [ + document for document in new_docs if title_matches(document.get("title")) + ] + if len(candidates) != 1: + return False, "the single new document does not have the required title" + + document = candidates[0] + content = str(document.get("content") or "") + text = norm_ignoring_long_dash(plain_html(content)) + if "opp-7740" in text or norm_ignoring_long_dash("Cobalt Freight — Trial") in text: + return False, "distractor OPP-7740 was included in the closeout document" + headings = [ + "1. Signed & Awaiting Approval", + "2. Unsigned & Reminded", + "3. Summary", + ] + missing_headings = [heading for heading in headings if norm(heading) not in text] + if missing_headings: + return False, f"missing section headings: {missing_headings}" + unformatted = [ + heading + for heading in headings + if not marked_as_heading_or_bold(content, heading) + ] + if unformatted: + return False, f"section headings are not bold/heading-formatted: {unformatted}" + + positions = [text.find(norm(heading)) for heading in headings] + if not (positions[0] < positions[1] < positions[2]): + return False, "section headings are not in the required order" + sections = [ + text[positions[0] + len(norm(headings[0])) : positions[1]], + text[positions[1] + len(norm(headings[1])) : positions[2]], + text[positions[2] + len(norm(headings[2])) :], + ] + + missing_approvals = [ + block + for block in (APPROVAL_7741, APPROVAL_7743) + if norm_ignoring_long_dash(block) not in sections[0] + ] + if missing_approvals: + return False, ( + "Signed & Awaiting Approval is missing exact approval text " + f"for {len(missing_approvals)} deal(s)" + ) + + reminder_tokens = [ + "D-7742", + "unsigned", + "reminded", + ] + if not all(norm(token) in sections[1] for token in reminder_tokens): + return False, "Unsigned & Reminded section lacks D-7742 status" + if norm_ignoring_long_dash(SUMMARY) not in sections[2]: + return False, "Summary section lacks the exact required summary sentence" + return True, "new AR Closeout doc has 3 formatted sections and required content" + + +def main(): + sid = read_sid() + if not sid: + print("REWARD: 0.0") + return 0.0 + + states = {} + for name in MOCKS: + try: + states[name] = fetch_states(name, sid) + except Exception as exc: + print(f"CRITICAL: cannot fetch {name}: {exc}") + print("REWARD: 0.0") + return 0.0 + + checks = [ + (1, "Invoice Ledger — 3 new rows", 0.30, check_sheets, states["google_sheets"]), + ( + 2, + "Slack #finance-approvals — 2 posts", + 0.20, + check_approval_slack, + states["slack"], + ), + ( + 3, + "Slack #finance-ar — reminder", + 0.10, + check_ar_slack, + states["slack"], + ), + (4, "Gmail — signing reminder", 0.10, check_gmail, states["gmail"]), + (5, "Google Docs — AR Closeout", 0.30, check_docs, states["google_docs"]), + ] + + total = 0.0 + for idx, name, weight, check, args in checks: + try: + passed, detail = check(*args) + except Exception as exc: + passed, detail = False, f"error: {exc}" + total += component( + idx, + name, + weight, + passed, + detail, + description=(check.__doc__ or "").strip(), + ) + + final = round(min(total, 1.0), 4) + print(f"\nScore: {total}/1.0") + print(f"REWARD: {final}") + return final + + +if __name__ == "__main__": + main() diff --git a/ar_closeout_006/reward_label.json b/ar_closeout_006/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..2b4f42e37de0de3502f40295bd3c4578fa1d568b --- /dev/null +++ b/ar_closeout_006/reward_label.json @@ -0,0 +1,61 @@ +{ + "reward_file": "/apdcephfs_fsgm/share_304220499/xiangwu/workspace/mini-osworld-generalBenchmark/out_benchmark_cache/prof20_ar_closeout_003/reward.py", + "created_at": "2026-07-19", + "label": { + "task_id": "ar_closeout_006", + "domain": "mock_websites", + "summary": "通过同一 sid 的 CUA-Gym-Hub /go 状态验证 AR closeout 的五个任务变更组件,并将 initial_state 作为不可变基线。", + "is_placeholder": false, + "data_sources": [ + "http://28.7.186.212:8165/go?sid=", + "http://28.7.186.212:8198/go?sid=", + "http://28.7.186.212:8158/go?sid=", + "http://28.7.186.212:8162/go?sid=" + ], + "scoring_components": [ + { + "id": 1, + "name": "Invoice Ledger — 3 new rows", + "weight": 0.3, + "pass_condition": "FY26 Invoices 恰好新增三条非空行;INV-7741、INV-7742、INV-7743 的七列值正确;所有初始行保持原位置和原值;不得处理 OPP-7740/INV-7740。" + }, + { + "id": 2, + "name": "Slack #finance-approvals — 2 posts", + "weight": 0.2, + "pass_condition": "历史消息保持不变,且恰好新增两条不同的审批消息,分别完整覆盖 OPP-7741 和 OPP-7743 的金额、阈值、AE、发票及签署状态。" + }, + { + "id": 3, + "name": "Slack #finance-ar — reminder", + "weight": 0.1, + "pass_condition": "历史消息保持不变,且恰好新增一条 D-7742 未签署提醒,包含 Gmail、收件人、AE、金额和账期信息。" + }, + { + "id": 4, + "name": "Gmail — signing reminder", + "weight": 0.1, + "pass_condition": "历史邮件保持不变,且恰好新增一封由 ar@saas-co.com 发往 contracts@verdant-health.co 的 sent 邮件;无抄送/密送;主题和正文符合 instruction。" + }, + { + "id": 5, + "name": "Google Docs — AR Closeout", + "weight": 0.3, + "pass_condition": "所有初始文档保持不变,恰好新增一份指定标题文档;三个章节按顺序出现且为加粗或标题格式;各章节内容位于正确章节;不得包含 OPP-7740。" + } + ], + "score_aggregation": "五个组件分别为全有或全无得分,权重相加并限制在 0.0 到 1.0;最后一行输出 REWARD: 。", + "regression_targets": { + "initial_state": 0.0, + "complete_state": 1.0, + "known_partial_gui_state": 0.6 + }, + "notes": [ + "不读取 /home/user/mock_state/*.json,不依赖静态 dashboard。", + "金额使用 Decimal 解析,避免仅拼接数字导致的误判。", + "日期按年月日比较,兼容 YYYY-MM-DD、MM/DD/YYYY 等常见 GUI 表示。", + "Google Docs 会检查初始文档是否被首次加载竞态覆盖。" + ] + }, + "raw_response": "Manually refreshed after live VM, backend-state, and in-memory initial/golden regression validation." +} diff --git a/ar_remittance_008__long/_cua_gym_vm_bridge.sh b/ar_remittance_008__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_remittance_008__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ar_remittance_008__long/initial_setup.py b/ar_remittance_008__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d067a91a81cd887e31badfbd0942bad827fb86 --- /dev/null +++ b/ar_remittance_008__long/initial_setup.py @@ -0,0 +1,644 @@ +""" +Initial Setup: T06 — QuickBooks AR Aging report -> Google Sheet (+ Gmail reconcile) +Task ID: ar_remittance_008__long +Mocks: quickbooks_mock, google_sheets_mock, gmail_mock + +The agent must build an Accounts Receivable aging report from QuickBooks open +invoices into the 'AR Aging' tab of the Google Sheet — but FIRST reconcile two +payments announced in Gmail. + + * "Today" is fixed at 2026-04-30 (stated in the instruction). + * A Gmail remittance email lists two invoice numbers that were just wired in. + The agent must record those in QuickBooks with the status-gated 'Receive + payment' action so each becomes status 'Paid' (this control only appears on + an unpaid invoice's detail view). + * THEN: only invoices whose status is 'Sent' or 'Overdue' qualify for the aging + report (Paid/Draft skipped) — so the two just-paid invoices drop out. + * days_overdue = today - dueDate; bucket by Current(<=0)/1-30/31-60/61-90/90+. + * Detail rows: Customer, InvoiceNumber, Total, DueDate, DaysOverdue, Bucket, + one row per qualifying invoice, sorted by DaysOverdue DESC. + * Summary block: one row per bucket (col A label, col C SUM of Total) in fixed + order Current,1-30,31-60,61-90,90+, then a 'Grand Total' row. + +GROUND TRUTH EMBEDDING: + * quickbooks.invoices[*]: each invoice that ends qualifying (Sent/Overdue after + reconciliation) carries a hidden `_age` = {'days_overdue': int, 'bucket': str}. + The two reconcile invoices carry `_receive_payment=True` and NO `_age` (they + must be marked Paid and excluded). Paid/Draft distractors carry neither. + * google_sheets._task_adapter holds `expected_rows` (ordered detail rows) and + `expected_summary` (per-bucket totals, fixed order) + `grand_total`. + +Everything below is PRECOMPUTED with datetime so the embedded answer key is +internally consistent with the visible invoice data. The 'AR Aging' tab ships +header-row-only (Rule 3: the observable result is ABSENT at injection); the two +reconcile invoices ship UNPAID (status 'Sent', so 'Receive payment' is available). +""" +import datetime as _dt +import os +import shlex +import subprocess +import time +import uuid + +import requests + + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# --------------------------------------------------------------------------- +# Fixed "today" and bucket logic (matches the instruction exactly) +# --------------------------------------------------------------------------- +TODAY = _dt.date(2026, 4, 30) + + +def _days_overdue(due_date_str): + """today - dueDate (positive = overdue, <=0 = not yet due).""" + due = _dt.date.fromisoformat(due_date_str) + return (TODAY - due).days + + +def _bucket(days): + """Aging bucket per instruction (Current<=0, then 1-30/31-60/61-90/90+).""" + if days <= 0: + return 'Current' + if days <= 30: + return '1-30' + if days <= 60: + return '31-60' + if days <= 90: + return '61-90' + return '90+' + + +# Fixed bucket display order for the summary block. +BUCKET_ORDER = ['Current', '1-30', '31-60', '61-90', '90+'] + + +# --------------------------------------------------------------------------- +# Customers (seeded so qualifying invoices resolve to real display names) +# --------------------------------------------------------------------------- +_CUSTOMERS = [ + {'id': 'c1', 'name': 'Acme Corporation', 'company': 'Acme Corporation', 'email': 'ap@acmecorp.com', 'phone': '(555) 100-1001'}, + {'id': 'c2', 'name': 'Globex Industries', 'company': 'Globex Industries', 'email': 'billing@globexind.com', 'phone': '(555) 100-1002'}, + {'id': 'c3', 'name': 'Initech LLC', 'company': 'Initech LLC', 'email': 'finance@initech.com', 'phone': '(555) 100-1003'}, + {'id': 'c4', 'name': 'Umbrella Health', 'company': 'Umbrella Health', 'email': 'accounts@umbrella.com', 'phone': '(555) 100-1004'}, + {'id': 'c5', 'name': 'Soylent Foods', 'company': 'Soylent Foods', 'email': 'ap@soylentfoods.com', 'phone': '(555) 100-1005'}, + {'id': 'c6', 'name': 'Stark Industries', 'company': 'Stark Industries', 'email': 'billing@stark.com', 'phone': '(555) 100-1006'}, + {'id': 'c7', 'name': 'Wayne Enterprises', 'company': 'Wayne Enterprises', 'email': 'ap@wayne.com', 'phone': '(555) 100-1007'}, + {'id': 'c8', 'name': 'Hooli Inc.', 'company': 'Hooli Inc.', 'email': 'finance@hooli.com', 'phone': '(555) 100-1008'}, + {'id': 'c9', 'name': 'Cyberdyne Systems', 'company': 'Cyberdyne Systems', 'email': 'accounts@cyberdyne.com', 'phone': '(555) 100-1009'}, + {'id': 'c10', 'name': 'Vandelay Industries', 'company': 'Vandelay Industries', 'email': 'ap@vandelay.com', 'phone': '(555) 100-1010'}, +] +for _c in _CUSTOMERS: + _c.setdefault('address', '100 Market St, San Francisco, CA 94105') + _c.setdefault('balance', 0) + _c.setdefault('notes', '') + _c.setdefault('isActive', True) + _c.setdefault('createdAt', '2025-11-01') + +_CUST_NAME = {c['id']: c['name'] for c in _CUSTOMERS} + + +# --------------------------------------------------------------------------- +# Invoice spec. qualifies=True -> Sent/Overdue (counts); False -> distractor. +# reconcile=True -> announced as paid in Gmail; agent must 'Receive payment' +# (mark Paid) FIRST, so it drops OUT of the aging report. Ships UNPAID. +# Format: (number, customerId, dueDate, total, status, qualifies, reconcile) +# --------------------------------------------------------------------------- +# 10 Sent/Overdue invoices span ALL five buckets (2 each); each has a UNIQUE +# days-overdue so the DaysOverdue-desc ordering is unambiguous. Future due +# dates (-> Current) carry status 'Sent'; past-due carry status 'Overdue'. +# Two of them (1003, 1007) are the reconcile invoices the agent must mark Paid. +_INVOICE_SPEC = [ + # --- Current (not yet due, days <= 0) --- + ('1001', 'c1', '2026-05-15', 1500.00, 'Sent', True, False), # days -15 + ('1002', 'c2', '2026-05-30', 2400.00, 'Sent', True, False), # days -30 + # --- 1-30 --- + ('1003', 'c3', '2026-04-20', 3200.00, 'Overdue', True, True), # days 10 -> RECONCILE (mark Paid) + ('1004', 'c4', '2026-04-05', 1800.00, 'Overdue', True, False), # days 25 + # --- 31-60 --- + ('1005', 'c5', '2026-03-20', 4500.00, 'Overdue', True, False), # days 41 + ('1006', 'c6', '2026-03-10', 2750.00, 'Overdue', True, False), # days 51 + # --- 61-90 --- + ('1007', 'c7', '2026-02-20', 5200.00, 'Overdue', True, True), # days 69 -> RECONCILE (mark Paid) + ('1008', 'c8', '2026-02-10', 3600.00, 'Overdue', True, False), # days 79 + # --- 90+ --- + ('1009', 'c9', '2026-01-15', 6800.00, 'Overdue', True, False), # days 105 + ('1010', 'c10', '2025-12-20', 4100.00, 'Overdue', True, False), # days 131 + + # --- DISTRACTORS: Paid / Draft -> NO _age, must be skipped by the agent --- + ('1011', 'c1', '2026-03-01', 2200.00, 'Paid', False, False), # paid, ignore + ('1012', 'c3', '2026-02-15', 9900.00, 'Paid', False, False), # paid, ignore + ('1013', 'c5', '2026-05-25', 1750.00, 'Draft', False, False), # draft, ignore + ('1014', 'c7', '2026-04-10', 8800.00, 'Draft', False, False), # draft, ignore +] + + +def _build_invoice(idx, number, customer_id, due_date, total, status, qualifies, reconcile): + """Builder helper -> a schema-complete Invoice (cf. quickbooks_mock schema). + + Invoices that END qualifying carry the hidden `_age` answer-key field. + Reconcile invoices ship UNPAID but carry `_receive_payment=True` and NO + `_age` (they must be marked Paid and excluded). Distractors carry neither. + """ + inv_date = (_dt.date.fromisoformat(due_date) - _dt.timedelta(days=30)).isoformat() + paid = (status == 'Paid') + inv = { + 'id': f'inv{idx}', + 'number': number, + 'customerId': customer_id, + 'date': inv_date, + 'dueDate': due_date, + 'items': [{ + 'id': f'inv{idx}_li1', + 'productId': 'p1', + 'description': 'Professional services', + 'qty': 1, + 'rate': total, + 'amount': total, + }], + 'subtotal': total, + 'tax': 0, + 'total': total, + 'status': status, + 'paidAmount': total if paid else 0, + 'paidDate': inv_date if paid else None, + 'terms': 'Net 30', + 'message': '', + 'createdAt': f'{inv_date}T09:00:00Z', + } + if reconcile: + # Announced paid in Gmail; agent must Receive payment -> Paid, then it is + # excluded from the aging report. No _age (it must not appear in rows). + inv['_receive_payment'] = True + elif qualifies: + days = _days_overdue(due_date) + inv['_age'] = {'days_overdue': days, 'bucket': _bucket(days)} + return inv + + +_INVOICES = [ + _build_invoice(i, number, cid, due, total, status, qualifies, reconcile) + for i, (number, cid, due, total, status, qualifies, reconcile) + in enumerate(_INVOICE_SPEC, start=1) +] + + +# --------------------------------------------------------------------------- +# Precompute the answer key (expected_rows + expected_summary) from the SAME +# source data so the embedded values are internally consistent. +# --------------------------------------------------------------------------- +_qualifying = [] +_RECONCILE_NUMBERS = [] +_RECONCILE = [] # (number, customer_name, total) for the Gmail notice + answer key +for (number, cid, due, total, status, qualifies, reconcile) in _INVOICE_SPEC: + if reconcile: + _RECONCILE_NUMBERS.append(number) + _RECONCILE.append({'number': number, 'customer': _CUST_NAME[cid], 'total': total}) + continue # reconcile invoices are marked Paid -> excluded from the report + if not qualifies: + continue + days = _days_overdue(due) + _qualifying.append({ + 'Customer': _CUST_NAME[cid], + 'InvoiceNumber': number, + 'Total': total, + 'DueDate': due, + 'DaysOverdue': days, + 'Bucket': _bucket(days), + }) + +# Detail rows sorted by DaysOverdue DESC (most overdue first). Unique day values +# guarantee a stable, unambiguous order. +EXPECTED_ROWS = sorted(_qualifying, key=lambda r: r['DaysOverdue'], reverse=True) + +# Per-bucket SUM of Total in the fixed bucket order. +_bucket_totals = {b: 0.0 for b in BUCKET_ORDER} +for r in _qualifying: + _bucket_totals[r['Bucket']] += r['Total'] +EXPECTED_SUMMARY = [ + {'bucket': b, 'total': round(_bucket_totals[b], 2)} for b in BUCKET_ORDER +] +GRAND_TOTAL = round(sum(r['Total'] for r in _qualifying), 2) + +# Self-check: 2 reconcile invoices, 8 rows remain in the report (10 Sent/Overdue - 2). +assert len(_RECONCILE_NUMBERS) == 2, _RECONCILE_NUMBERS +assert len(EXPECTED_ROWS) == 8, len(EXPECTED_ROWS) +assert all(r['InvoiceNumber'] not in _RECONCILE_NUMBERS for r in EXPECTED_ROWS) +print(f'Reconcile-first invoices (mark Paid, exclude): {_RECONCILE_NUMBERS}; ' + f'aging rows after reconcile: {len(EXPECTED_ROWS)}; grand total {GRAND_TOTAL}') + + +# --------------------------------------------------------------------------- +# Google Sheet — 'AR Aging' tab, header row only (observable result ABSENT). +# Headers map to columns A..F: Customer, InvoiceNumber, Total, DueDate, +# DaysOverdue, Bucket. +# --------------------------------------------------------------------------- +AR_HEADERS = ['Customer', 'InvoiceNumber', 'Total', 'DueDate', 'DaysOverdue', 'Bucket'] +_HEADER_STYLE = {'bold': True, 'bg': '#F3F3F3', 'align': 'center'} + + +def _header_cell(text): + return {'value': text, 'formula': text, 'computed': text, 'style': dict(_HEADER_STYLE)} + + +_ar_data = {} +for col_idx, header in enumerate(AR_HEADERS): + col_letter = chr(ord('A') + col_idx) + _ar_data[f'{col_letter}1'] = _header_cell(header) + + +_SHEET_STATE = { + 'id': 'workbook_ar_aging', + 'title': 'AR Aging Workbook', + 'activeSheetId': 'sheet_ar', + 'selectedCell': 'A1', + 'selectionRange': None, + 'clipboard': None, + 'isDragging': False, + 'undoStack': [], + 'redoStack': [], + 'namedRanges': [], + 'conditionalFormats': [], + 'charts': [], + 'showGridlines': True, + 'showFormulas': False, + 'zoom': 100, + 'sheets': [{ + 'id': 'sheet_ar', + 'name': 'AR Aging', + 'data': _ar_data, # header row 1 only; rows + summary ABSENT + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None, + }], + '_task_adapter': { + 'source_schema': 'ar_aging', + 'task_id': '29e36334-3263-4955-9d91-a14163000860', + 'variant': 'eval', + 'today': TODAY.isoformat(), + 'target_sheet': 'AR Aging', + 'headers': AR_HEADERS, + 'bucket_order': BUCKET_ORDER, + 'sheet_names': ['AR Aging'], + 'headers_by_sheet': {'AR Aging': AR_HEADERS}, + # ---- ANSWER KEY ---- + 'expected_rows': EXPECTED_ROWS, + 'expected_summary': EXPECTED_SUMMARY, + 'grand_total': GRAND_TOTAL, + 'reconcile_invoice_numbers': _RECONCILE_NUMBERS, + }, +} + + +# --------------------------------------------------------------------------- +# QuickBooks state (partial inject; deep-merged with mock defaults). +# --------------------------------------------------------------------------- +_QB_STATE = { + 'company': { + 'name': 'Acme Corp', + 'address': '123 Business Rd, San Francisco, CA 94105', + 'email': 'admin@acmecorp.com', + 'industry': 'Technology Services', + 'accountingMethod': 'Accrual', + }, + 'customers': _CUSTOMERS, + 'invoices': _INVOICES, +} + + +# --------------------------------------------------------------------------- +# Gmail state — a remittance notice naming the two invoices that were wired in. +# The agent reads this, then uses QB 'Receive payment' to mark them Paid. NO +# aging-report artefact here; this mailbox is read-only context. +# --------------------------------------------------------------------------- +_RECON_LINES = '
'.join( + f"- Invoice {r['number']} ({r['customer']}): ${r['total']:.2f}" for r in _RECONCILE +) +_GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Dana Reyes', + 'email': 'dana.reyes@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=3'}, + 'emails': [ + {'id': 'm_remit', 'threadId': 'thread_remit', + 'from': {'name': 'Accounts Receivable', 'email': 'ar-bank@acmecorp.com', 'avatar': ''}, + 'to': [{'name': 'Dana Reyes', 'email': 'dana.reyes@acmecorp.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Wire payments received — please reconcile before AR aging', + 'body': ('Hi Dana,

Two customer wires cleared this morning. Please ' + 'mark these invoices as paid in QuickBooks before you run the AR ' + f'aging report so they are not counted as outstanding:

{_RECON_LINES}' + '

Thanks,
AR Bank Desk'), + 'snippet': 'Two customer wires cleared this morning. Please mark these invoices as paid...', + 'timestamp': '2026-04-30T07:30:00Z', 'read': False, 'starred': False, + 'important': True, 'labels': [], 'category': 'primary', 'folder': 'inbox', + 'attachments': []}, + {'id': 'm_decoy1', 'threadId': 'thread_d1', + 'from': {'name': 'Office Newsletter', 'email': 'news@acmecorp.com', 'avatar': ''}, + 'to': [{'name': 'Dana Reyes', 'email': 'dana.reyes@acmecorp.com'}], + 'cc': [], 'bcc': [], + 'subject': 'April company update', 'body': 'Highlights from the month and a few reminders.', + 'snippet': 'Highlights from the month...', 'timestamp': '2026-04-29T15:00:00Z', + 'read': True, 'starred': False, 'important': False, 'labels': [], + 'category': 'updates', 'folder': 'inbox', 'attachments': []}, + ], + 'labels': [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Finance', 'color': '#eab308'}, + ], + 'drafts': [], + 'settings': {'density': 'default', 'undoSend': 10}, + 'today': '2026-04-30', +} + + +# --------------------------------------------------------------------------- +# State payloads to inject (ports from the shipped registry). +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8172', _QB_STATE), # quickbooks_mock + ('http://28.7.184.198:8145', _SHEET_STATE), # google_sheets_mock + ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock +] + + +for app_url, state in APP_STATES: + resp = requests.post( + f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {app_url}: {resp.text}' + ) + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}' + ) + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/ar_remittance_008__long/reward.py b/ar_remittance_008__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..31a7406e60edc2c3faf10ebf32f74f927960a2c8 --- /dev/null +++ b/ar_remittance_008__long/reward.py @@ -0,0 +1,664 @@ +""" +Reward Script: T06 — QuickBooks AR aging report into Google Sheets (+ Gmail reconcile) +Task ID: ar_remittance_008__long +Mocks: quickbooks_mock,google_sheets_mock,gmail_mock +Scoring (all components 0 at do-nothing; reconcile invoices ship unpaid): + 0.40 detail rows == expected_rows as an ORDERED list (DaysOverdue desc), + matching on (Customer, InvoiceNumber, Total, Bucket); frac of correctly-placed rows + 0.15 DaysOverdue + Bucket values correct per row (avg of two per-row sub-checks) + 0.20 per-bucket SUM rows match expected_summary (5 buckets, col A label + col C sum, exact) + 0.10 Grand Total row ('Grand Total' label + col C sum == grand_total) + 0.15 the two Gmail-announced invoices marked Paid via 'Receive payment' (status-gated) + (− modest over-inclusion penalty for Paid/Draft distractor invoice rows, capped 0.10) +Answer key: google_sheets.initial_state._task_adapter.expected_rows / expected_summary / + grand_total / reconcile_invoice_numbers (primary) + quickbooks invoices[*]._age. +""" +import copy +import datetime as _dt +import re +import sys + +import requests + + +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +APP_URLS = {'quickbooks': 'http://28.7.184.198:8172', 'google_sheets': 'http://28.7.184.198:8145'} +_GO_CACHE = {} + + +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def f1(true_set, pred_set): + if not true_set and not pred_set: + return 1.0 + tp = len(true_set & pred_set) + if tp == 0: + return 0.0 + prec = tp / len(pred_set) + rec = tp / len(true_set) + return 2 * prec * rec / (prec + rec) + + +def by_id(items, key='id'): + return {it.get(key): it for it in (items or []) if isinstance(it, dict)} + + +def has_text(haystack, *needles): + s = (haystack or '').lower() + return any(n.lower() in s for n in needles) + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _to_float(v): + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _msg_text(m): + return m.get('content') or m.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + # Slack messages may live under channels[*].messages OR the top-level + # messages[channelId] map — read both. + if not isinstance(slack_state, dict): + return [] + channels = slack_state.get('channels') if isinstance(slack_state.get('channels'), list) else [] + messages_map = slack_state.get('messages') if isinstance(slack_state.get('messages'), dict) else {} + out = [] + for ch in channels: + if not isinstance(ch, dict): + continue + if norm(ch.get('name')) != norm(channel_name): + continue + cid = ch.get('channelId') or ch.get('id') + for m in (ch.get('messages') if isinstance(ch.get('messages'), list) else []): + if isinstance(m, dict): + out.append(m) + if cid and isinstance(messages_map.get(cid), list): + for m in messages_map[cid]: + if isinstance(m, dict): + out.append(m) + return out + + +def _sheet_rows(sheet): + if not isinstance(sheet, dict): + return [] + rows = sheet.get('rows', []) + return rows if isinstance(rows, list) else [] + + +def _sheet_tabs(sheets): + if isinstance(sheets, dict): + return sheets + if isinstance(sheets, list): + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') + if name: + out[name] = sh + return out + return {} + + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _parse_cell_id(cell_id): + if not isinstance(cell_id, str) or not cell_id: + return None + idx = 0 + while idx < len(cell_id) and cell_id[idx].isalpha(): + idx += 1 + if idx == 0 or idx >= len(cell_id): + return None + col = 0 + for ch in cell_id[:idx].upper(): + col = col * 26 + (ord(ch) - ord('A') + 1) + try: + row = int(cell_id[idx:]) + except ValueError: + return None + return row, col - 1 + + +def _extract_rows_from_workbook(state): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} + + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') or 'Sheet1' + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + + headers = headers_by_sheet.get(name) + if not headers: + cols = [] + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx != 1: + continue + value = '' + if isinstance(cell, dict): + value = cell.get('value', '') + elif cell is not None: + value = str(cell) + if value is not None and str(value) != '': + cols.append((col_idx, str(value))) + headers = [v for _, v in sorted(cols)] + + if not headers: + continue + + by_row = {} + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx <= 1 or col_idx >= len(headers): + continue + if isinstance(cell, dict): + value = cell.get('value', '') + else: + value = cell + by_row.setdefault(row_idx, {})[headers[col_idx]] = value + + rows = [] + for row_idx in sorted(by_row.keys()): + row = by_row[row_idx] + if not any(str(row.get(h, '')).strip() for h in headers): + continue + rows.append({h: row.get(h, '') for h in headers}) + + out[name] = {'headers': headers, 'rows': rows} + + if not out: + return None + return {'sheets': out} + + +def _materialize_google_sheets(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + maybe_rows = _extract_rows_from_workbook(state) + if maybe_rows is not None: + state['_ui_workbook'] = { + 'sheets': copy.deepcopy(state.get('sheets', [])), + 'title': state.get('title'), + } + state['sheets'] = maybe_rows['sheets'] + + +def _materialize_slack(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, + 'messageId': mid, + 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), + 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward === +# +# The agent reads QuickBooks open invoices (Sent/Overdue only), buckets them by +# days overdue (today = 2026-04-30), and writes an AR-aging report into the +# 'AR Aging' tab of the Google Sheet: +# - one detail row per qualifying invoice (Customer, InvoiceNumber, Total, +# DueDate, DaysOverdue, Bucket), sorted by DaysOverdue DESC, and +# - a summary block: one row per bucket (label in col A, SUM of Total in col C) +# in fixed bucket order, then a 'Grand Total' row (sum in col C). +# +# Ground truth lives in google_sheets.initial_state._task_adapter (expected_rows, +# expected_summary, grand_total). QuickBooks invoices carry a hidden `_age` on the +# Sent/Overdue invoices; we read it to recover the qualifying-invoice set used for +# the distractor (Paid/Draft) over-inclusion guard. +def reward(go): + TOL = 0.01 # penny tolerance for currency / sums + W_DETAIL = 0.40 + W_VALUES = 0.15 + W_SUMMARY = 0.20 + W_GRAND = 0.10 + W_RECEIVE = 0.15 # reconcile invoices marked Paid via 'Receive payment' + PENALTY_PER_DISTRACTOR = 0.05 + PENALTY_CAP = 0.10 + + # ---- helpers for raw cell-grid reading ---- + def _cell_disp(cell): + # Resolve a cell to its displayed value: prefer `computed` when `value` + # is a formula (=SUM(...)) or empty. + if isinstance(cell, dict): + comp = cell.get('computed') + val = cell.get('value', '') + if isinstance(val, str) and val.strip().startswith('='): + if comp is not None and str(comp).strip() != '': + return comp + return val + if (val is None or str(val).strip() == '') and comp is not None: + return comp + return val + return cell + + def _to_num(v): + if v is None: + return None + if isinstance(v, bool): + return None + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip() + if not s: + return None + s = s.replace('$', '').replace(',', '').strip() + if s in ('', '-', '+'): + return None + try: + return float(s) + except Exception: + return None + + def _s(v): + if v is None: + return '' + return str(v).strip() + + def _raw_sheet(state, name): + if not isinstance(state, dict): + return None + candidates = [] + ui = state.get('_ui_workbook') + if isinstance(ui, dict) and isinstance(ui.get('sheets'), list): + candidates = ui['sheets'] + elif isinstance(state.get('sheets'), list): + candidates = state['sheets'] + for sh in candidates: + if not isinstance(sh, dict): + continue + if norm(sh.get('name')) == norm(name) or norm(sh.get('id')) == norm(name): + return sh + if len(candidates) == 1 and isinstance(candidates[0], dict): + return candidates[0] + return None + + def _grid(sheet): + grid = {} + data = sheet.get('data') if isinstance(sheet, dict) else None + if not isinstance(data, dict): + return grid + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + r, c = rc # r 1-based, c 0-based + grid.setdefault(r, {})[c] = _cell_disp(cell) + return grid + + # ---- 1) Pull answer key (primary) from sheets adapter ---- + gs = go('google_sheets') + gs_init = gs.get('initial_state', {}) if isinstance(gs.get('initial_state'), dict) else {} + gs_cur = gs.get('current_state', {}) if isinstance(gs.get('current_state'), dict) else {} + adapter = gs_init.get('_task_adapter', {}) if isinstance(gs_init.get('_task_adapter'), dict) else {} + + expected_rows = adapter.get('expected_rows') if isinstance(adapter.get('expected_rows'), list) else [] + expected_summary = adapter.get('expected_summary') if isinstance(adapter.get('expected_summary'), list) else [] + grand_total_truth = adapter.get('grand_total') + bucket_order = adapter.get('bucket_order') if isinstance(adapter.get('bucket_order'), list) else \ + ['Current', '1-30', '31-60', '61-90', '90+'] + target_sheet = adapter.get('target_sheet') or 'AR Aging' + bucket_label_set = {norm(b) for b in bucket_order} + + # ---- secondary key: qualifying invoice numbers from QB `_age` ---- + qb_payload = go('quickbooks') + qb_init = qb_payload.get('initial_state', {}) or {} + qb_cur = qb_payload.get('current_state', {}) or {} + qb_inv = qb_init.get('invoices', []) or [] + qualifying_nums = {norm(inv.get('number')) for inv in qb_inv + if isinstance(inv, dict) and '_age' in inv} + # expected detail invoice numbers (string) — used for distractor detection + expected_nums = {norm(er.get('InvoiceNumber')) for er in expected_rows + if isinstance(er, dict)} + if not expected_nums: + expected_nums = qualifying_nums + + n = len(expected_rows) + if n == 0: + print('DEBUG_T06_AR_AGING fatal=no_expected_rows total=0.0') + return 0.0 + + # ---- 2) Parse agent output grid for the AR Aging tab ---- + sheet = _raw_sheet(gs_cur, target_sheet) + grid = _grid(sheet) if sheet is not None else {} + + # Columns: A=0 Customer, B=1 InvoiceNumber, C=2 Total, D=3 DueDate, + # E=4 DaysOverdue, F=5 Bucket + detail_rows = [] # ordered list of agent detail rows (dicts) + summary_cells = {} # bucket-label-norm -> total float + grand_total_val = None + distractor_detail = 0 + + for r in sorted(grid.keys()): + if r <= 1: + continue # header row + row = grid[r] + a = _s(row.get(0)) + b = _s(row.get(1)) + a_norm = norm(a) + is_grand = ('grand' in a_norm and 'total' in a_norm) + is_bucket_label = a_norm in bucket_label_set + + if is_grand: + gv = _to_num(row.get(2)) + if gv is not None: + grand_total_val = gv + continue + if is_bucket_label and not b: + cv = _to_num(row.get(2)) + if a_norm not in summary_cells and cv is not None: + summary_cells[a_norm] = cv + continue + if b: + # detail (invoice) row + inv_num = b + detail_rows.append({ + 'Customer': a, + 'InvoiceNumber': inv_num, + 'Total': _to_num(row.get(2)), + 'DueDate': _s(row.get(3)), + 'DaysOverdue': _to_num(row.get(4)), + 'Bucket': _s(row.get(5)), + }) + if norm(inv_num) not in expected_nums: + distractor_detail += 1 + # else: blank / unrecognized row -> ignore + + # ---- 3) Component 1 (0.45): ordered detail match on (Customer, InvoiceNumber, Total, Bucket) ---- + hits_detail = 0 + for i, exp in enumerate(expected_rows): + if i >= len(detail_rows): + continue + got = detail_rows[i] + exp_total = _to_num(exp.get('Total')) + got_total = got.get('Total') + total_ok = (got_total is not None and exp_total is not None + and abs(got_total - exp_total) <= TOL) + if (norm(got.get('Customer')) == norm(exp.get('Customer')) + and norm(got.get('InvoiceNumber')) == norm(exp.get('InvoiceNumber')) + and total_ok + and norm(got.get('Bucket')) == norm(exp.get('Bucket'))): + hits_detail += 1 + s_detail = W_DETAIL * frac(hits_detail, n) + + # ---- 4) Component 2 (0.20): DaysOverdue + Bucket correct per row (avg two sub-checks) ---- + hits_days = 0 + hits_bucket = 0 + for i, exp in enumerate(expected_rows): + if i >= len(detail_rows): + continue + got = detail_rows[i] + exp_days = exp.get('DaysOverdue') + got_days = got.get('DaysOverdue') + try: + if got_days is not None and exp_days is not None and \ + int(round(float(got_days))) == int(round(float(exp_days))): + hits_days += 1 + except Exception: + pass + if norm(got.get('Bucket')) == norm(exp.get('Bucket')): + hits_bucket += 1 + s_values = W_VALUES * 0.5 * (frac(hits_days, n) + frac(hits_bucket, n)) + + # ---- 5) Component 3 (0.25): per-bucket SUM rows == expected_summary ---- + n_buckets = len(expected_summary) + hits_summary = 0 + for item in expected_summary: + if not isinstance(item, dict): + continue + blabel = norm(item.get('bucket')) + btot = _to_num(item.get('total')) + got = summary_cells.get(blabel) + if got is not None and btot is not None and abs(got - btot) <= TOL: + hits_summary += 1 + s_summary = W_SUMMARY * frac(hits_summary, n_buckets) if n_buckets else 0.0 + + # ---- 6) Component 4 (0.10): Grand Total ---- + gt_truth = _to_num(grand_total_truth) + grand_ok = (grand_total_val is not None and gt_truth is not None + and abs(grand_total_val - gt_truth) <= TOL) + s_grand = W_GRAND * (1.0 if grand_ok else 0.0) + + # ---- 6b) Component 5 (0.15): reconcile invoices marked Paid via 'Receive payment' ---- + # The two invoices named in the Gmail notice must be status 'Paid' in QB + # current_state. They ship UNPAID (Sent), so a do-nothing agent scores 0 here. + recon_numbers = set() + adapter_recon = adapter.get('reconcile_invoice_numbers') if isinstance(adapter, dict) else None + if isinstance(adapter_recon, list): + recon_numbers = {str(x) for x in adapter_recon} + if not recon_numbers: + # fallback: invoices carrying the hidden _receive_payment flag in QB initial_state + for inv in (qb_init.get('invoices', []) or []): + if isinstance(inv, dict) and inv.get('_receive_payment'): + recon_numbers.add(str(inv.get('number'))) + qb_cur_invoices = qb_cur.get('invoices', []) or [] + cur_status_by_num = {} + for inv in qb_cur_invoices: + if isinstance(inv, dict): + cur_status_by_num[str(inv.get('number'))] = norm(inv.get('status')) + recv_ok = sum(1 for num in recon_numbers if cur_status_by_num.get(num) == 'paid') + s_receive = W_RECEIVE * frac(recv_ok, len(recon_numbers)) if recon_numbers else 0.0 + + # ---- 7) Over-inclusion guard: penalize Paid/Draft distractor rows ---- + penalty = min(PENALTY_CAP, PENALTY_PER_DISTRACTOR * distractor_detail) + + raw = s_detail + s_values + s_summary + s_grand + s_receive - penalty + score = clamp01(raw) + + print( + 'DEBUG_T06_AR_AGING ' + f'n_exp={n} n_detail={len(detail_rows)} qual_nums={len(qualifying_nums)} ' + f'detail_hits={hits_detail}/{n} days_hits={hits_days}/{n} bucket_hits={hits_bucket}/{n} ' + f'summary_hits={hits_summary}/{n_buckets} grand_ok={int(grand_ok)} ' + f'recv_ok={recv_ok}/{len(recon_numbers)} ' + f'distractors={distractor_detail} penalty={round(penalty, 4)} ' + f'w_detail={round(s_detail, 4)} w_values={round(s_values, 4)} ' + f'w_summary={round(s_summary, 4)} w_grand={round(s_grand, 4)} w_receive={round(s_receive, 4)} ' + f'raw={round(raw, 4)} total={round(score, 4)}' + ) + + return score + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/calc_boomerang_sales_004__long/.PLACEHOLDER b/calc_boomerang_sales_004__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/calc_boomerang_sales_004__long/.PLACEHOLDER @@ -0,0 +1,5 @@ +This directory is intentionally empty. +It exists only to satisfy start_our_benchmark_test.sh's uniform +'cache_dir// must exist' precheck. Non-mock tasks do not use +cua_gym cache; their evaluators read a vm_file tarball instead. +See docs/0716_迁移执行日志.md § S15 for details. diff --git a/calc_boomerang_sales_004__long/338372e2-5164-5bba-be72-3024f425418f_BoomerangSales_4.xlsx b/calc_boomerang_sales_004__long/338372e2-5164-5bba-be72-3024f425418f_BoomerangSales_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..ed62408a417890e8d4ba30debfe560356ca3e4a3 Binary files /dev/null and b/calc_boomerang_sales_004__long/338372e2-5164-5bba-be72-3024f425418f_BoomerangSales_4.xlsx differ diff --git a/calc_boomerang_sales_004__long/3c734b28-876f-590a-8a9b-a7dea013cdd9_BoomerangSales_5.xlsx b/calc_boomerang_sales_004__long/3c734b28-876f-590a-8a9b-a7dea013cdd9_BoomerangSales_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..ed62408a417890e8d4ba30debfe560356ca3e4a3 Binary files /dev/null and b/calc_boomerang_sales_004__long/3c734b28-876f-590a-8a9b-a7dea013cdd9_BoomerangSales_5.xlsx differ diff --git a/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_1.xlsx b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4757540a9ba8220cc4afa7f6352e771ec21f2808 Binary files /dev/null and b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_1.xlsx differ diff --git a/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_2.xlsx b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4757540a9ba8220cc4afa7f6352e771ec21f2808 Binary files /dev/null and b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_2.xlsx differ diff --git a/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_3.xlsx b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4757540a9ba8220cc4afa7f6352e771ec21f2808 Binary files /dev/null and b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_3.xlsx differ diff --git a/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_4.xlsx b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4757540a9ba8220cc4afa7f6352e771ec21f2808 Binary files /dev/null and b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_4.xlsx differ diff --git a/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_5.xlsx b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4757540a9ba8220cc4afa7f6352e771ec21f2808 Binary files /dev/null and b/calc_boomerang_sales_004__long/6_BoomerangSales_gt1_5.xlsx differ diff --git a/calc_boomerang_sales_004__long/7594f1e5-2945-5a98-9eec-5aac2e8aaf1b_BoomerangSales_3.xlsx b/calc_boomerang_sales_004__long/7594f1e5-2945-5a98-9eec-5aac2e8aaf1b_BoomerangSales_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..ed62408a417890e8d4ba30debfe560356ca3e4a3 Binary files /dev/null and b/calc_boomerang_sales_004__long/7594f1e5-2945-5a98-9eec-5aac2e8aaf1b_BoomerangSales_3.xlsx differ diff --git a/calc_boomerang_sales_004__long/b9ee9e4b-d3c9-5341-a797-ba31c5448117_BoomerangSales_1.xlsx b/calc_boomerang_sales_004__long/b9ee9e4b-d3c9-5341-a797-ba31c5448117_BoomerangSales_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..ed62408a417890e8d4ba30debfe560356ca3e4a3 Binary files /dev/null and b/calc_boomerang_sales_004__long/b9ee9e4b-d3c9-5341-a797-ba31c5448117_BoomerangSales_1.xlsx differ diff --git a/calc_boomerang_sales_004__long/e22b8fec-7bed-5cb0-a402-a977fa125750_BoomerangSales_2.xlsx b/calc_boomerang_sales_004__long/e22b8fec-7bed-5cb0-a402-a977fa125750_BoomerangSales_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..ed62408a417890e8d4ba30debfe560356ca3e4a3 Binary files /dev/null and b/calc_boomerang_sales_004__long/e22b8fec-7bed-5cb0-a402-a977fa125750_BoomerangSales_2.xlsx differ diff --git a/calc_student_grades_005__long/.PLACEHOLDER b/calc_student_grades_005__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/calc_student_grades_005__long/.PLACEHOLDER @@ -0,0 +1,5 @@ +This directory is intentionally empty. +It exists only to satisfy start_our_benchmark_test.sh's uniform +'cache_dir// must exist' precheck. Non-mock tasks do not use +cua_gym cache; their evaluators read a vm_file tarball instead. +See docs/0716_迁移执行日志.md § S15 for details. diff --git a/calc_student_grades_005__long/0a94aee5-1a46-57a5-b453-2402af0ffede_Student_Grades_and_Remarks_4.xlsx b/calc_student_grades_005__long/0a94aee5-1a46-57a5-b453-2402af0ffede_Student_Grades_and_Remarks_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f12f0c61ea4ce5aa5240728b1234d3f9b7c99c95 Binary files /dev/null and b/calc_student_grades_005__long/0a94aee5-1a46-57a5-b453-2402af0ffede_Student_Grades_and_Remarks_4.xlsx differ diff --git a/calc_student_grades_005__long/26aa94e9-ffcf-57a5-b2dd-e92752c4b57f_Student_Grades_and_Remarks_2.xlsx b/calc_student_grades_005__long/26aa94e9-ffcf-57a5-b2dd-e92752c4b57f_Student_Grades_and_Remarks_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f12f0c61ea4ce5aa5240728b1234d3f9b7c99c95 Binary files /dev/null and b/calc_student_grades_005__long/26aa94e9-ffcf-57a5-b2dd-e92752c4b57f_Student_Grades_and_Remarks_2.xlsx differ diff --git a/calc_student_grades_005__long/639ca2f8-0ba9-5a67-b827-a64f4cd425b5_Student_Grades_and_Remarks_3.xlsx b/calc_student_grades_005__long/639ca2f8-0ba9-5a67-b827-a64f4cd425b5_Student_Grades_and_Remarks_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f12f0c61ea4ce5aa5240728b1234d3f9b7c99c95 Binary files /dev/null and b/calc_student_grades_005__long/639ca2f8-0ba9-5a67-b827-a64f4cd425b5_Student_Grades_and_Remarks_3.xlsx differ diff --git a/calc_student_grades_005__long/914ebed1-4ae1-5a3e-b9ab-bbbfe8206f7b_Student_Grades_and_Remarks_1.xlsx b/calc_student_grades_005__long/914ebed1-4ae1-5a3e-b9ab-bbbfe8206f7b_Student_Grades_and_Remarks_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f12f0c61ea4ce5aa5240728b1234d3f9b7c99c95 Binary files /dev/null and b/calc_student_grades_005__long/914ebed1-4ae1-5a3e-b9ab-bbbfe8206f7b_Student_Grades_and_Remarks_1.xlsx differ diff --git a/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_1.xlsx b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..db8b26cc45407fb1261028c5554f2f29ff7791c2 Binary files /dev/null and b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_1.xlsx differ diff --git a/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_2.xlsx b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..db8b26cc45407fb1261028c5554f2f29ff7791c2 Binary files /dev/null and b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_2.xlsx differ diff --git a/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_3.xlsx b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..db8b26cc45407fb1261028c5554f2f29ff7791c2 Binary files /dev/null and b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_3.xlsx differ diff --git a/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_4.xlsx b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..db8b26cc45407fb1261028c5554f2f29ff7791c2 Binary files /dev/null and b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_4.xlsx differ diff --git a/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_5.xlsx b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..db8b26cc45407fb1261028c5554f2f29ff7791c2 Binary files /dev/null and b/calc_student_grades_005__long/Student_Grades_and_Remarks_gold_5.xlsx differ diff --git a/calc_student_grades_005__long/f4dfeace-a9ac-57e3-9cb7-b78690026317_Student_Grades_and_Remarks_5.xlsx b/calc_student_grades_005__long/f4dfeace-a9ac-57e3-9cb7-b78690026317_Student_Grades_and_Remarks_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f12f0c61ea4ce5aa5240728b1234d3f9b7c99c95 Binary files /dev/null and b/calc_student_grades_005__long/f4dfeace-a9ac-57e3-9cb7-b78690026317_Student_Grades_and_Remarks_5.xlsx differ diff --git a/csm_training_rate_005/initial_setup.py b/csm_training_rate_005/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..22c4b724e9ca6b5d318dac4014c79aba3b3ad6d6 --- /dev/null +++ b/csm_training_rate_005/initial_setup.py @@ -0,0 +1,279 @@ +""" +Initial Setup: ce_adoption_rate_b107 +Task ID: csm_training_rate_005 +Domain: mock_websites +Mocks: google_sheets_mock, salesforce_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a finance analyst. Your tools for this task are: shared spreadsheets, the Salesforce CRM, team communications. + +Environment / context (initial state + ground truth this setup establishes): +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. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "google_sheets_mock": "http://28.7.184.198:8145", + "salesforce_mock": "http://28.7.184.198:8175", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8145' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# Full initial state for every mock involved (all required top-level keys present). +STATES = { 'google_sheets_mock': { 'id': 'workbook_1', + 'title': 'Q2 Adoption Tracker', + 'activeSheetId': 'sheet_1', + 'selectedCell': 'A1', + 'selectionRange': None, + 'clipboard': None, + 'isDragging': False, + 'undoStack': [], + 'redoStack': [], + 'namedRanges': [], + 'conditionalFormats': [], + 'charts': [], + 'showGridlines': True, + 'showFormulas': False, + 'zoom': 100, + 'sheets': [ { 'id': 'sheet_1', + 'name': 'Training Attendance', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'data': { 'A1': { 'value': 'Account', + 'formula': 'Account', + 'style': {'bold': True}}, + 'B1': { 'value': 'Owner', + 'formula': 'Owner', + 'style': {'bold': True}}, + 'C1': { 'value': 'Sessions', + 'formula': 'Sessions', + 'style': {'bold': True}}, + 'D1': { 'value': 'Completed', + 'formula': 'Completed', + 'style': {'bold': True}}, + 'A2': { 'value': 'TechVentures', + 'formula': 'TechVentures'}, + 'B2': { 'value': 'John', + 'formula': 'John'}, + 'C2': {'value': '3', 'formula': '3'}, + 'D2': { 'value': 'Yes', + 'formula': 'Yes'}, + 'A3': { 'value': 'LeadCo', + 'formula': 'LeadCo'}, + 'B3': { 'value': 'Amy', + 'formula': 'Amy'}, + 'C3': {'value': '2', 'formula': '2'}, + 'D3': { 'value': 'Yes', + 'formula': 'Yes'}, + 'A4': { 'value': 'Globex', + 'formula': 'Globex'}, + 'B4': { 'value': 'John', + 'formula': 'John'}, + 'C4': {'value': '3', 'formula': '3'}, + 'D4': { 'value': 'Yes', + 'formula': 'Yes'}, + 'A5': { 'value': 'Initech', + 'formula': 'Initech'}, + 'B5': { 'value': 'Amy', + 'formula': 'Amy'}, + 'C5': {'value': '1', 'formula': '1'}, + 'D5': {'value': 'No', 'formula': 'No'}, + 'A8': { 'value': 'Completion Rate', + 'formula': 'Completion Rate', + 'style': {'bold': True}}}}]}, + 'salesforce_mock': { 'user': { 'userId': 'user-1', + 'firstName': 'John', + 'lastName': 'Smith', + 'email': 'john.smith@company.com', + 'phone': '(555) 123-4567', + 'title': 'Sales Manager', + 'department': 'Sales', + 'role': 'Manager', + 'avatar': 'https://i.pravatar.cc/150?u=user-1', + 'timezone': 'America/New_York', + 'locale': 'en-US', + 'theme': 'lightning'}, + 'users': [ { 'userId': 'user-1', + 'firstName': 'John', + 'lastName': 'Smith', + 'email': 'john.smith@company.com'}, + { 'userId': 'user-2', + 'firstName': 'Amy', + 'lastName': 'Wong', + 'email': 'amy@company.com'}], + 'leads': [], + 'accounts': [ { 'accountId': 'account-1', + 'name': 'TechVentures Inc.', + 'type': 'Customer', + 'industry': 'Technology', + 'revenue': 15000000, + 'employees': 250, + 'ownerId': 'user-1'}], + 'contacts': [ { 'contactId': 'contact-1', + 'accountId': 'account-1', + 'firstName': 'Sarah', + 'lastName': 'Johnson', + 'title': 'VP Eng', + 'department': 'Engineering', + 'email': 'sarah.j@techventures.com', + 'phone': '(555) 111-2222', + 'ownerId': 'user-1'}], + 'opportunities': [ { 'opportunityId': 'o1', + 'name': 'TechVentures Expansion', + 'accountId': 'account-1', + 'contactId': 'contact-1', + 'amount': 50000, + 'closeDate': '2026-06-30', + 'stage': 'Proposal', + 'probability': 60, + 'ownerId': 'user-1'}], + 'cases': [], + 'activities': [], + 'chatterPosts': [], + 'files': [], + 'following': [], + 'recentlyViewed': [], + 'dismissedNotifications': []}, + 'slack_mock': { 'currentUser': { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'workspace': { 'workspaceId': 'ws_1', + 'workspaceName': 'Acme Corp', + 'icon': ''}, + 'users': [ { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_2', + 'fullName': 'Sarah Johnson', + 'displayName': 'Sarah', + 'email': 'sarah.johnson@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_3', + 'fullName': 'Mike Chen', + 'displayName': 'Mike', + 'email': 'mike.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_4', + 'fullName': 'Lisa Park', + 'displayName': 'Lisa', + 'email': 'lisa.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}], + 'channels': [ { 'channelId': 'general', + 'name': 'general', + 'description': 'general channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + { 'channelId': 'random', + 'name': 'random', + 'description': 'random channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}], + 'messages': { 'general': [ { 'messageId': 'g1', + 'senderId': 'user_2', + 'content': "what's the Q2 enablement " + 'completion rate?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/csm_training_rate_005/reward.py b/csm_training_rate_005/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fb497999f52a73aec8e425aa25821a536f95c0b0 --- /dev/null +++ b/csm_training_rate_005/reward.py @@ -0,0 +1,102 @@ +""" +Reward Script: ce_adoption_rate_b107 +Task ID: csm_training_rate_005 +Domain: mock_websites +Mocks: google_sheets_mock, salesforce_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.4] completion rate computed as 75% + - [0.3] TechVentures opp -> Closed Won + - [0.1] slack_new_msg + - [0.2] reports the 75% rate +""" +import re +import sys + +import requests + +MOCK_URLS = { + "google_sheets_mock": "http://28.7.184.198:8145", + "salesforce_mock": "http://28.7.184.198:8175", + "slack_mock": "http://28.7.184.198:8178" +} +SEED = { + "slack_mock:general": [ + "g1" + ], + "slack_mock:random": [] +} + +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +STATES = {} +for _name, _url in MOCK_URLS.items(): + try: + _r = requests.get(f'{_url}/go?sid={sid}', timeout=15) + _r.raise_for_status() + STATES[_name] = _r.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {_name}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def cur(mock): + return (STATES.get(mock) or {}).get('current_state') or {} + + +def _lc(s): + return (s or '').lower() + + +total = 0.0 + +# c0: sheet cell B8 value contains '75' +c0_sheets = cur('google_sheets_mock').get('sheets') or [] +c0_data = (c0_sheets[0].get('data') if c0_sheets else {}) or {} +c0_cd = c0_data.get('B8') or {} +if '75' in str(c0_cd.get('value','')) or '75' in str(c0_cd.get('computed','')): + print('PASS: completion rate computed as 75% (0.4)') + total += 0.4 +else: + print('FAIL: completion rate computed as 75%') + +# c1: salesforce opp o1 stage == 'Closed Won' +c1_o = next((o for o in (cur('salesforce_mock').get('opportunities') or []) if o.get('opportunityId') == 'o1'), None) +if c1_o and c1_o.get('stage') == 'Closed Won': + print('PASS: TechVentures opp -> Closed Won (0.3)') + total += 0.3 +else: + print('FAIL: TechVentures opp -> Closed Won') + +# c2: new message by user_1 in #general +c2_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c2_seed = set(SEED.get('slack_mock:general', [])) +c2_new = [m for m in c2_msgs if m.get('messageId') not in c2_seed and m.get('senderId') == 'user_1'] +c2_blob = _lc(' '.join((m.get('content') or '') for m in c2_new)) +if c2_new: + print('PASS: new message by user_1 in #general (0.1)') + total += 0.1 +else: + print('FAIL: no new user_1 message in #general') + +# c3: slack #general contains (reports the 75% rate) +c3_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c3_seed = set(SEED.get('slack_mock:general', [])) +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')) +if any(t in c3_blob for t in ['75%', '75 percent', '75']): + print('PASS: reports the 75% rate (0.2)') + total += 0.2 +else: + print('FAIL: reports the 75% rate') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/csops_inbox_triage_006__long/_cua_gym_vm_bridge.sh b/csops_inbox_triage_006__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csops_inbox_triage_006__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/csops_inbox_triage_006__long/initial_setup.py b/csops_inbox_triage_006__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dccd7d2ef0017ba0c7382dd3174b38299003d8 --- /dev/null +++ b/csops_inbox_triage_006__long/initial_setup.py @@ -0,0 +1,771 @@ +""" +Initial Setup: T02_trello_triage_sla — Triage support inbox into the 'Support' Trello board +Task ID: csops_inbox_triage_006__long +Mocks: gmail_mock,trello_mock,google_calendar_mock,slack_mock + +Ground-truth embedding style: INLINE hidden field `triage` on every gmail email + triage = {"kind": "actionable|noise|resolved", + "component": "Bug|Billing|Feature Request|Account" | None, + "priority": "P1|P2|P3" | None, + "due": "T17:00:00" | None, + # P1 (urgent) tickets only — Google Calendar follow-up answer key: + "event_title": "Follow-up: ", + "event_date": "", + "guest_email": ""} +Only kind == "actionable" yields a Trello card. reward.py reads `triage` +from gmail initial_state. Priority + due are PRECOMPUTED in Python from each +email body (severity keywords) and the SLA rule, so the embedded answer key is +internally consistent with the visible email text. + +HIDDEN ACCESS POINTS the agent must DISCOVER (the whole point of this task): + - Gmail: the priority LABEL button is SELECTION-GATED — it only appears in the + toolbar after you tick an email's checkbox. The picker then lists the + P1/P2/P3 labels seeded below. (Analog of Salesforce "select row -> Change + Owner button appears".) reward grades the priority label on each genuine + email, matched by label NAME. + - Trello: a card's priority label + due date live ONLY inside the card-detail + modal you open by clicking the card. + - Calendar: guests are typed into the buried "Add guests" field in the event + editor; the requester email is NOT in the autocomplete list, so it must be + carried over from the Gmail message. + - Slack: the summary message posted to #support must be PINNED — pin lives + behind the per-message hover "..." (More actions) menu. + +Observable result kept ABSENT at injection (Rule 3): + - The four target Trello lists (Bug / Billing / Feature Request / Account) + start with ZERO cards. Only the decoy 'Done' list carries watermark cards. + - All 12 emails start in folder 'inbox' (nothing archived yet) and carry NO + labels (labels: []). + - The calendar holds NO 'Follow-up:' events at injection (only decoys). + - The Slack #support channel starts EMPTY (no messages, no pinned messages). + Only decoy channels carry watermark chatter. +""" +import datetime +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# --------------------------------------------------------------------------- +# Ground-truth derivation (PRECOMPUTED so embedded keys match the visible data) +# "Assume today is Tuesday, June 16, 2026." +# --------------------------------------------------------------------------- +TODAY = datetime.date(2026, 6, 16) +assert TODAY.strftime('%A') == 'Tuesday', 'today must be Tuesday June 16, 2026' + +# SLA: P1 = today +1d, P2 = today +3d, P3 = today +7d, all due at 17:00 local. +SLA_DAYS = {'P1': 1, 'P2': 3, 'P3': 7} + + +def sla_due(priority): + d = TODAY + datetime.timedelta(days=SLA_DAYS[priority]) + return f'{d.isoformat()}T17:00:00' + + +def classify_priority(body): + """Severity keyword rule, applied in precedence order (P1 > P2 > P3).""" + b = body.lower() + if 'urgent' in b or 'production down' in b: + return 'P1' + if 'broken' in b or 'error' in b or 'cannot' in b: + return 'P2' + return 'P3' + + +# Email specs. For actionable emails, priority/due are DERIVED from `body`; +# `expect_priority` is a sanity assertion that the authored body really yields +# the intended priority. Non-actionable emails get null component/priority/due. +EMAIL_SPECS = [ + # ---- 7 ACTIONABLE support emails (one card each) ---- + dict(eid='m1', thread='thread_m1', component='Bug', kind='actionable', + expect_priority='P1', + sender_name='Priya Nair', sender_email='priya.nair@northwind.example', + subject='Checkout page returns 500 for all users', + body='This is urgent -- production down since 8am, every customer hits a 500 at checkout. Please escalate.', + ts='2026-06-16T08:12:00Z'), + dict(eid='m2', thread='thread_m2', component='Bug', kind='actionable', + expect_priority='P2', + sender_name='Tomas Vidal', sender_email='tomas.vidal@harborlabs.example', + subject='Image upload broken on profile page', + body='The avatar upload is broken and throws an error whenever I pick a PNG. Was working last week.', + ts='2026-06-16T07:40:00Z'), + dict(eid='m3', thread='thread_m3', component='Billing', kind='actionable', + expect_priority='P2', + sender_name='Dana Whitfield', sender_email='dana@whitfield-cpa.example', + subject='Invoice shows wrong tax amount', + body='I cannot download my March invoice and the tax line looks wrong -- it doubled the VAT.', + ts='2026-06-15T16:05:00Z'), + dict(eid='m4', thread='thread_m4', component='Billing', kind='actionable', + expect_priority='P3', + sender_name='Leo Park', sender_email='leo.park@brightway.example', + subject='Request a copy of last year receipts', + body='Could you send the 2025 receipts for our accounting records when you get a chance? No rush at all.', + ts='2026-06-15T11:22:00Z'), + dict(eid='m5', thread='thread_m5', component='Feature Request', kind='actionable', + expect_priority='P3', + sender_name='Marisol Ferreira', sender_email='marisol@ferreira-design.example', + subject='Add dark mode to the dashboard', + body='It would be great to have a dark theme option in settings. Easier on the eyes for late shifts.', + ts='2026-06-15T09:48:00Z'), + dict(eid='m6', thread='thread_m6', component='Feature Request', kind='actionable', + expect_priority='P1', + sender_name='Greg Olsson', sender_email='greg.olsson@meridian.example', + subject='Need CSV export before the board meeting', + body='This is urgent: we need CSV export of the analytics dashboard by Friday for the board deck.', + ts='2026-06-16T06:30:00Z'), + dict(eid='m7', thread='thread_m7', component='Account', kind='actionable', + expect_priority='P2', + sender_name='Hana Sato', sender_email='hana.sato@kabuki.example', + subject='Cannot log in after password reset', + body='After resetting my password I cannot log in -- it shows an error saying the token expired.', + ts='2026-06-16T05:58:00Z'), + + # ---- 5 NON-ACTIONABLE emails (must be archived, no card) ---- + dict(eid='m8', thread='thread_m8', component=None, kind='noise', + expect_priority=None, + sender_name='Acme Product', sender_email='newsletter@acme-product.example', + subject='Acme Weekly: product updates and tips', + body='Here is what shipped this week, plus three tips to get more out of your dashboard. Unsubscribe anytime.', + ts='2026-06-16T04:00:00Z'), + dict(eid='m9', thread='thread_m9', component=None, kind='noise', + expect_priority=None, + sender_name='Owen Brandt', sender_email='owen.brandt@partnerco.example', + subject='Automatic reply: Out of office', + body='I am currently out of office and will return Monday June 22. For urgent matters contact my colleague.', + ts='2026-06-16T03:30:00Z'), + dict(eid='m10', thread='thread_m10', component=None, kind='noise', + expect_priority=None, + sender_name='Carla Mendez', sender_email='carla.mendez@summit.example', + subject='Thanks for the quick fix!', + body='Just wanted to say thank you -- the export works perfectly now. Really appreciate the fast turnaround.', + ts='2026-06-15T18:10:00Z'), + # Resolved THREAD: original support request + a later reply marking it done. + # Both emails are non-actionable (kind=resolved) and must be archived. + dict(eid='m11', thread='thread_resolved', component=None, kind='resolved', + expect_priority=None, + sender_name='Felix Adler', sender_email='felix.adler@coastal.example', + subject='Login button does nothing on Safari', + body='The login button appears broken on Safari and throws a console error. Can someone take a look?', + ts='2026-06-15T13:20:00Z'), + dict(eid='m12', thread='thread_resolved', component=None, kind='resolved', + expect_priority=None, + sender_name='Felix Adler', sender_email='felix.adler@coastal.example', + subject='Re: Login button does nothing on Safari', + body='Update: this is now resolved after I cleared the cache. Everything works, please close it out. Thanks!', + ts='2026-06-15T15:05:00Z'), +] + +GMAIL_USER = { + 'userId': 'u1', + 'username': 'Support Team', + 'email': 'support@acme.io', + 'avatar': 'https://picsum.photos/200/200?random=1', +} + + +def build_email(spec): + body = spec['body'] + if spec['kind'] == 'actionable': + priority = classify_priority(body) + assert priority == spec['expect_priority'], ( + f"{spec['eid']}: body classifies as {priority} but expected {spec['expect_priority']}" + ) + due = sla_due(priority) + component = spec['component'] + else: + priority = None + due = None + component = None + assert spec['component'] is None + + triage = { + 'kind': spec['kind'], + 'component': component, + 'priority': priority, + 'due': due, + } + # P1 (urgent) tickets ALSO require a Google Calendar follow-up event whose + # GUEST is the requester's email (typed into the buried guest field). The + # event date is the P1 SLA due date (today + 1). Non-P1 emails carry no event + # answer key, so they neither require nor are penalised for a calendar event. + if spec['kind'] == 'actionable' and priority == 'P1': + triage['event_title'] = f"Follow-up: {spec['subject']}" + triage['event_date'] = due[:10] # 'YYYY-MM-DD' (P1 = today+1) + triage['guest_email'] = spec['sender_email'] # cross-app: extracted from Gmail + + return { + 'id': spec['eid'], + 'threadId': spec['thread'], + 'from': {'name': spec['sender_name'], 'email': spec['sender_email'], 'avatar': ''}, + 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': spec['subject'], + 'body': body, + 'snippet': body[:120], + 'timestamp': spec['ts'], + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + # ---- inline hidden answer key (reward reads this) ---- + 'triage': triage, + } + + +EMAILS = [build_email(s) for s in EMAIL_SPECS] + +# Internal-consistency report (printed at setup time, not graded). +_actionable = [e for e in EMAILS if e['triage']['kind'] == 'actionable'] +_nonactionable = [e for e in EMAILS if e['triage']['kind'] != 'actionable'] +assert len(_actionable) == 7, f'expected 7 actionable, got {len(_actionable)}' +assert len(_nonactionable) == 5, f'expected 5 non-actionable, got {len(_nonactionable)}' +print('Ground truth (actionable -> component / priority / due):') +for e in _actionable: + t = e['triage'] + print(f" {e['id']}: {t['component']:<16} {t['priority']} due {t['due']} | {e['subject']}") + +# P1 tickets carry a calendar-event answer key; verify it is internally consistent. +_p1 = [e for e in _actionable if e['triage'].get('priority') == 'P1'] +assert all('event_title' in e['triage'] and e['triage'].get('guest_email') + for e in _p1), 'every P1 email must carry the event answer key' +print(f'P1 calendar follow-ups required: {len(_p1)} ' + f'-> {[e["triage"]["guest_email"] for e in _p1]}') + +# Gmail priority LABELS (P1/P2/P3) are seeded so the SELECTION-GATED Label button +# has something to apply. reward matches the label by NAME -> id, so the exact id +# strings here are not load-bearing (only the names P1/P2/P3 are). Work/Personal +# are decoys. Emails start with labels:[] (Rule 3) so the gradable label is absent. +GMAIL_LABELS = [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'lbl-p1', 'name': 'P1', 'color': '#eb5a46'}, # red + {'id': 'lbl-p2', 'name': 'P2', 'color': '#ff9f1a'}, # orange + {'id': 'lbl-p3', 'name': 'P3', 'color': '#f2d600'}, # yellow +] + +gmail_state = { + 'user': GMAIL_USER, + 'emails': EMAILS, + 'labels': GMAIL_LABELS, + 'drafts': [], + 'settings': { + 'density': 'default', + 'undoSend': 10, + 'categoryTabs': { + 'primary': True, + 'social': True, + 'promotions': True, + 'updates': False, + 'forums': False, + }, + }, + 'today': '2026-06-16', +} + +# --------------------------------------------------------------------------- +# Trello: 'Support' board, four empty component lists + decoy 'Done', P1/P2/P3 +# labels. Target lists start with NO cards (Rule 3). Done holds watermark cards. +# --------------------------------------------------------------------------- +SUPPORT_LABELS = [ + {'id': 'lbl-p1', 'name': 'P1', 'color': '#eb5a46'}, # red + {'id': 'lbl-p2', 'name': 'P2', 'color': '#ff9f1a'}, # orange + {'id': 'lbl-p3', 'name': 'P3', 'color': '#f2d600'}, # yellow +] + + +def trello_card(cid, title, list_id, board_id, label_ids=None, due=None, + completed=False, position=0, description=''): + return { + 'id': cid, + 'title': title, + 'description': description, + 'listId': list_id, + 'boardId': board_id, + 'labelIds': label_ids or [], + 'memberIds': ['u1'], + 'dueDate': due, + 'startDate': None, + 'completed': completed, + 'cover': None, + 'checklists': [], + 'comments': [], + 'attachments': [], + 'archived': False, + 'watching': False, + 'position': position, + 'createdAt': '2026-06-12T09:00:00.000Z', + } + + +# Two decoy cards in the (excluded-from-scoring) 'Done' list — watermark only. +decoy_done_cards = { + 'card-done-1': trello_card( + 'card-done-1', 'Rotate API signing keys (Q2)', 'list-done', 'board-support', + label_ids=['lbl-p3'], due='2026-06-10T17:00:00.000Z', completed=True, position=0, + description='Quarterly key rotation completed and verified in prod.'), + 'card-done-2': trello_card( + 'card-done-2', 'Publish status-page postmortem', 'list-done', 'board-support', + label_ids=['lbl-p2'], due='2026-06-09T17:00:00.000Z', completed=True, position=1, + description='Postmortem for the May latency incident shared with customers.'), +} + +trello_state = { + 'currentUser': 'u1', + 'users': { + 'u1': {'id': 'u1', 'name': 'Support Team', 'username': 'support', + 'initials': 'ST', 'email': 'support@acme.io', 'avatarUrl': ''}, + 'u2': {'id': 'u2', 'name': 'Maya Lindqvist', 'username': 'maya', + 'initials': 'ML', 'email': 'maya.lindqvist@acme.io', 'avatarUrl': ''}, + 'u3': {'id': 'u3', 'name': 'Hiroshi Tanabe', 'username': 'hiroshi', + 'initials': 'HT', 'email': 'hiroshi.tanabe@acme.io', 'avatarUrl': ''}, + }, + 'boards': { + 'board-support': { + 'id': 'board-support', + 'title': 'Support', + 'description': 'Customer support triage board. One card per genuine support email.', + 'background': '#0079BF', + 'listIds': ['list-bug', 'list-billing', 'list-feature', 'list-account', 'list-done'], + 'starred': True, + 'visibility': 'workspace', + 'archivedListIds': [], + 'archivedCardIds': [], + 'labels': SUPPORT_LABELS, + 'memberIds': ['u1', 'u2', 'u3'], + 'createdAt': '2026-06-01T09:00:00.000Z', + } + }, + 'lists': { + 'list-bug': {'id': 'list-bug', 'title': 'Bug', 'boardId': 'board-support', + 'cardIds': [], 'archived': False}, + 'list-billing': {'id': 'list-billing', 'title': 'Billing', 'boardId': 'board-support', + 'cardIds': [], 'archived': False}, + 'list-feature': {'id': 'list-feature', 'title': 'Feature Request', 'boardId': 'board-support', + 'cardIds': [], 'archived': False}, + 'list-account': {'id': 'list-account', 'title': 'Account', 'boardId': 'board-support', + 'cardIds': [], 'archived': False}, + 'list-done': {'id': 'list-done', 'title': 'Done', 'boardId': 'board-support', + 'cardIds': ['card-done-1', 'card-done-2'], 'archived': False}, + }, + 'cards': decoy_done_cards, + 'boardOrder': ['board-support'], + 'lastReadNotificationAt': None, +} + +# --------------------------------------------------------------------------- +# Google Calendar: operator's calendars. NO 'Follow-up:' events at injection +# (Rule 3) — only two decoy events for realism. The agent must create a +# follow-up event per P1 ticket and TYPE the requester's email into the guest +# field (the autocomplete only lists @example.com users, so the real email +# from Gmail must be carried over). +# --------------------------------------------------------------------------- +def cal_event(eid, calendar_id, title, start_iso, end_iso, location, description, guests): + return { + 'id': eid, 'calendarId': calendar_id, 'title': title, + 'start': start_iso, 'end': end_iso, + 'allDay': False, 'location': location, 'description': description, + 'guests': guests, 'color': 'bg-green-500', 'recurring': 'none', + 'reminders': [{'type': 'popup', 'minutes': 10}], + } + + +google_calendar_state = { + 'user': {'id': 'u1', 'username': 'Support Team', + 'email': 'support@acme.io', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + 'calendars': [ + {'id': 'c1', 'name': 'Personal', 'color': 'bg-blue-500', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}, + {'id': 'c2', 'name': 'Work', 'color': 'bg-green-500', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}, + ], + 'events': [ + cal_event('evt_standup', 'c2', 'Support Standup', + '2026-06-16T09:30:00.000Z', '2026-06-16T10:00:00.000Z', + 'Conference Room A', 'Daily support sync', ['support@acme.io']), + cal_event('evt_retro', 'c2', 'Sprint Retro', + '2026-06-18T15:00:00.000Z', '2026-06-18T16:00:00.000Z', + 'Zoom', 'Bi-weekly retro', []), + ], + 'view': 'week', + 'currentDate': '2026-06-16T00:00:00.000Z', + 'sidebarOpen': True, + 'settings': {'weekStart': 0, 'defaultDuration': 60}, + 'today': '2026-06-16', +} + +# --------------------------------------------------------------------------- +# Slack: the team workspace. The agent must post a one-line triage SUMMARY to +# #support stating how many tickets were triaged, then PIN that message (pin is +# hidden behind the per-message hover "..." menu). #support starts EMPTY +# (no messages, no pinned messages) per Rule 3; decoy channels carry watermark +# chatter so the agent must find the right channel. +# --------------------------------------------------------------------------- +SLACK_USERS = [ + {'userId': 'user_1', 'fullName': 'Sam Rivera', 'displayName': 'Sam', + 'email': 'support@acme.io', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Support Engineer', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya', + 'email': 'maya.lindqvist@acme.io', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Support Lead', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Hiroshi Tanabe', 'displayName': 'Hiroshi', + 'email': 'hiroshi.tanabe@acme.io', 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Engineer', 'status': 'away', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, +] + + +def slack_channel(cid, name, desc, topic, starred=False, unread=0): + return { + 'channelId': cid, 'name': name, 'description': desc, 'topic': topic, + 'isPrivate': False, 'isStarred': starred, + 'members': ['user_1', 'user_2', 'user_3'], + 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': unread, + } + + +def slack_msg(mid, sender, content, ts): + return { + 'messageId': mid, 'senderId': sender, 'content': content, + 'timestamp': ts, 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False, + } + + +slack_state = { + 'currentUser': SLACK_USERS[0], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Support', 'icon': ''}, + 'users': SLACK_USERS, + 'channels': [ + # TARGET channel — starts empty (Rule 3). + slack_channel('support', 'support', + 'Customer support triage coordination', 'Daily triage updates', + starred=True), + # Decoys (watermark chatter). + slack_channel('general', 'general', 'Company-wide announcements', 'Welcome!', + starred=True, unread=0), + slack_channel('random', 'random', 'Non-work banter', 'Watercooler', unread=2), + slack_channel('incidents', 'incidents', 'Live incident coordination', + 'Page on-call here', unread=1), + ], + 'messages': { + # #support intentionally EMPTY — the gradable post is absent at injection. + 'support': [], + 'general': [ + slack_msg('m_g_1', 'user_2', 'Morning all — support queue looks busy today.', + '2026-06-16T07:55:00Z'), + slack_msg('m_g_2', 'user_3', 'On it after standup.', + '2026-06-16T08:01:00Z'), + ], + 'random': [ + slack_msg('m_r_1', 'user_3', 'Anyone tried the new ramen place on 3rd?', + '2026-06-15T12:30:00Z'), + slack_msg('m_r_2', 'user_2', '10/10, get the spicy miso.', + '2026-06-15T12:42:00Z'), + ], + 'incidents': [ + slack_msg('m_i_1', 'user_2', 'Checkout 500s reported — investigating.', + '2026-06-16T08:15:00Z'), + ], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { + 'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False, + }, + 'invitations': [], + 'notifications': [], +} + +APP_STATES = [ + ('http://28.7.184.198:8138', gmail_state), + ('http://28.7.184.198:8182', trello_state), + ('http://28.7.184.198:8141', google_calendar_state), + ('http://28.7.184.198:8178', slack_state), +] + +for app_url, state in APP_STATES: + resp = requests.post( + f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {app_url}: {resp.text}' + ) + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}' + ) + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/csops_inbox_triage_006__long/reward.py b/csops_inbox_triage_006__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fc54baff7ef3f590cb938d57bd24f74b19386d54 --- /dev/null +++ b/csops_inbox_triage_006__long/reward.py @@ -0,0 +1,654 @@ +""" +Reward Script: T02_trello_triage_sla — Support inbox triage into Trello + Calendar + Slack +Task ID: csops_inbox_triage_006__long +Mocks: gmail_mock,trello_mock,google_calendar_mock,slack_mock +Scoring (all components are frac/F1 over absent-at-injection outputs -> do-nothing == 0): + 0.30 card placement F1 : true=(component,Subject) for actionable emails; + pred=(listName,title) over all NON-'Done' lists. + 0.15 gmail priority label: among actionable emails, frac whose CURRENT gmail + labels include the email's priority label (matched by + NAME P1/P2/P3). HIDDEN: the Label button only appears + in the Gmail toolbar after the email's checkbox is + ticked (selection-gated). + 0.12 trello label corr : among MATCHED cards, frac whose labelIds holds the + email's priority label id (by board label name P1/P2/P3). + HIDDEN: label lives inside the card-detail modal. + 0.08 due-date corr : among MATCHED cards, frac whose dueDate matches the + embedded `due` to the DAY (local-date comparison). + HIDDEN: due date lives inside the card-detail modal. + 0.10 archive rate : non-actionable emails moved to archive/all-mail/trash. + 0.08 P1 follow-up event : per P1 ticket, a calendar event titled 'Follow-up: ' + on the P1 due date exists. + 0.07 P1 event guest : that event lists the requester's email as a guest + (HIDDEN: buried guest field; email carried from Gmail). + 0.05 slack summary post : a non-empty message exists in the #support channel + (empty at injection). + 0.05 slack pin : that #support message is PINNED (HIDDEN: pin is behind + the per-message hover "..." menu). +Answer key (sole source of truth): gmail.initial_state.emails[*].triage +""" +import copy +import re +import sys + +import requests + +from datetime import datetime, timezone, timedelta + +TZ_PLUS_8 = timezone(timedelta(hours=8)) + + +def parse_as_utc(s, default_tz=TZ_PLUS_8): + """ + Parse an ISO datetime string and convert it to UTC. + + Assumption: + - If the string has Z or +00:00, it is already timezone-aware. + - If the string has no timezone, treat it as UTC+8. + """ + if not s: + return None + + s = str(s).strip() + + # Python's fromisoformat prefers +00:00 over Z + if s.endswith("Z"): + s = s[:-1] + "+00:00" + + dt = datetime.fromisoformat(s) + + # Example: "2024-03-18T09:00" has no timezone. + # Treat it as UTC+8. + if dt.tzinfo is None: + dt = dt.replace(tzinfo=default_tz) + + return dt.astimezone(timezone.utc) + + +def norm_dt(s): + dt = parse_as_utc(s) + if dt is None: + return "" + return dt.isoformat(timespec="seconds") + + +def date_key(s, local_tz=TZ_PLUS_8): + """ + Return the calendar date (YYYY-MM-DD) that an ISO datetime represents in + LOCAL (UTC+8) terms. Timezone-aware values are converted to local first so + that, e.g., a UTC '...T09:00:00Z' due-time round-trips to the same local day + as a naive '...T17:00:00'. Naive values are taken as-is (already local). + Bare 'YYYY-MM-DD' strings fall back to their first 10 chars. + """ + if not s: + return None + s = str(s).strip() + if s.endswith("Z"): + s = s[:-1] + "+00:00" + try: + dt = datetime.fromisoformat(s) + except ValueError: + return s[:10] if len(s) >= 10 else None + if dt.tzinfo is not None: + dt = dt.astimezone(local_tz) + return dt.date().isoformat() + + +# --- Read sid (set by initial_setup.py) --- +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +APP_URLS = {'gmail': 'http://28.7.184.198:8138', 'trello': 'http://28.7.184.198:8182', + 'google_calendar': 'http://28.7.184.198:8141', 'slack': 'http://28.7.184.198:8178'} +_GO_CACHE = {} + + +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def f1(true_set, pred_set): + if not true_set and not pred_set: + return 1.0 + tp = len(true_set & pred_set) + if tp == 0: + return 0.0 + prec = tp / len(pred_set) + rec = tp / len(true_set) + return 2 * prec * rec / (prec + rec) + + +def by_id(items, key='id'): + return {it.get(key): it for it in (items or []) if isinstance(it, dict)} + + +def has_text(haystack, *needles): + s = (haystack or '').lower() + return any(n.lower() in s for n in needles) + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) + target = None + for ch in channels: + if norm(ch.get('name')) == norm(channel_name): + target = ch + break + if target is None: + return [] + + ch_msgs = target.get('messages') + if isinstance(ch_msgs, list): + return ch_msgs + + msg_map = slack_state.get('messages', {}) + if isinstance(msg_map, dict): + return msg_map.get(target.get('channelId'), []) or [] + return [] + + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _parse_cell_id(cell_id): + if not isinstance(cell_id, str) or not cell_id: + return None + idx = 0 + while idx < len(cell_id) and cell_id[idx].isalpha(): + idx += 1 + if idx == 0 or idx >= len(cell_id): + return None + col = 0 + for ch in cell_id[:idx].upper(): + col = col * 26 + (ord(ch) - ord('A') + 1) + try: + row = int(cell_id[idx:]) + except ValueError: + return None + return row, col - 1 + + +def _extract_rows_from_workbook(state): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} + + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') or 'Sheet1' + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + + headers = headers_by_sheet.get(name) + if not headers: + cols = [] + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx != 1: + continue + value = '' + if isinstance(cell, dict): + value = cell.get('value', '') + elif cell is not None: + value = str(cell) + if value is not None and str(value) != '': + cols.append((col_idx, str(value))) + headers = [v for _, v in sorted(cols)] + + if not headers: + continue + + by_row = {} + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx <= 1 or col_idx >= len(headers): + continue + if isinstance(cell, dict): + value = cell.get('value', '') + else: + value = cell + by_row.setdefault(row_idx, {})[headers[col_idx]] = value + + rows = [] + for row_idx in sorted(by_row.keys()): + row = by_row[row_idx] + if not any(str(row.get(h, '')).strip() for h in headers): + continue + rows.append({h: row.get(h, '') for h in headers}) + + out[name] = {'headers': headers, 'rows': rows} + + if not out: + return None + return {'sheets': out} + + +def _sheet_rows(state, sheet_name=None): + wb = _extract_rows_from_workbook(state) or {} + sheets = wb.get('sheets', {}) if isinstance(wb, dict) else {} + if sheet_name is not None: + s = sheets.get(sheet_name) + return s.get('rows', []) if isinstance(s, dict) else [] + for s in sheets.values(): + if isinstance(s, dict): + return s.get('rows', []) + return [] + + +def _materialize_google_sheets(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + maybe_rows = _extract_rows_from_workbook(state) + if maybe_rows is not None: + state['_ui_workbook'] = { + 'sheets': copy.deepcopy(state.get('sheets', [])), + 'title': state.get('title'), + } + state['sheets'] = maybe_rows['sheets'] + + +def _materialize_slack(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, + 'messageId': mid, + 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), + 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward === +def reward(go): + gmail = go('gmail') + trello = go('trello') + + emails_i = gmail.get('initial_state', {}).get('emails', []) or [] + emails_c_list = gmail.get('current_state', {}).get('emails', []) or [] + emails_c = {e.get('id'): e for e in emails_c_list if isinstance(e, dict)} + + tcur = trello.get('current_state', {}) if isinstance(trello.get('current_state'), dict) else {} + lists_map = tcur.get('lists', {}) if isinstance(tcur.get('lists'), dict) else {} + cards_map = tcur.get('cards', {}) if isinstance(tcur.get('cards'), dict) else {} + boards_map = tcur.get('boards', {}) if isinstance(tcur.get('boards'), dict) else {} + + # Board label NAME -> label id (e.g. 'p1' -> 'lbl-p1'); union over all boards. + label_name_to_id = {} + for b in boards_map.values(): + if not isinstance(b, dict): + continue + for lab in (b.get('labels') or []): + if isinstance(lab, dict) and lab.get('name') and lab.get('id'): + label_name_to_id.setdefault(norm(lab.get('name')), lab.get('id')) + + # --- partition emails by embedded triage.kind (sole source of truth) --- + actionable = [] + nonactionable = [] + for e in emails_i: + if not isinstance(e, dict): + continue + tri = e.get('triage') or {} + if norm(tri.get('kind')) == 'actionable': + actionable.append(e) + else: + nonactionable.append(e) + + # true set = (component, Subject); lookup back to the source email. + true_set = set() + true_lookup = {} + for e in actionable: + tri = e.get('triage') or {} + key = (norm(tri.get('component')), norm(e.get('subject'))) + true_set.add(key) + true_lookup[key] = e + + # pred set + matched cards over all NON-'Done' lists (membership via cardIds). + pred_set = set() + matched = [] # (card, source_email) + for lst in lists_map.values(): + if not isinstance(lst, dict): + continue + ltitle = lst.get('title') if lst.get('title') is not None else lst.get('name') + if norm(ltitle) == 'done': + continue + for cid in (lst.get('cardIds') or []): + card = cards_map.get(cid) + if not isinstance(card, dict): + continue + key = (norm(ltitle), norm(card.get('title'))) + pred_set.add(key) + if key in true_lookup: + matched.append((card, true_lookup[key])) + + card_f1 = f1(true_set, pred_set) + + # --- Gmail priority label among ACTIONABLE emails (selection-gated control) --- + # Resolve each CURRENT gmail label id -> name so a label named P1/P2/P3 matches + # regardless of id drift; emails start with labels:[] so this is 0 at do-nothing. + gmail_labels_c = gmail.get('current_state', {}).get('labels', []) or [] + gmail_labels_i = gmail.get('initial_state', {}).get('labels', []) or [] + gmail_id_to_name = {} + for lab in list(gmail_labels_i) + list(gmail_labels_c): + if isinstance(lab, dict) and lab.get('id'): + gmail_id_to_name[lab.get('id')] = norm(lab.get('name')) + glabel_ok = 0 + for e in actionable: + tri = e.get('triage') or {} + want = norm(tri.get('priority')) + cur = emails_c.get(e.get('id'), {}) + got_names = {gmail_id_to_name.get(lid) for lid in (cur.get('labels') or [])} + if want and want in got_names: + glabel_ok += 1 + glabel_score = frac(glabel_ok, len(actionable)) if actionable else 0.0 + + # priority-label correctness among MATCHED cards (hidden: card-detail modal) + lab_ok = 0 + for card, e in matched: + tri = e.get('triage') or {} + want_id = label_name_to_id.get(norm(tri.get('priority'))) + if want_id and want_id in (card.get('labelIds') or []): + lab_ok += 1 + label_score = frac(lab_ok, len(matched)) + + # due-date correctness among MATCHED cards (compare to the day, local) + due_ok = 0 + for card, e in matched: + tri = e.get('triage') or {} + want = date_key(tri.get('due')) + got = date_key(card.get('dueDate')) + if want and got and want == got: + due_ok += 1 + due_score = frac(due_ok, len(matched)) + + # archive rate of non-actionable emails + arch = 0 + for e in nonactionable: + cur = emails_c.get(e.get('id'), {}) + if norm(cur.get('folder')) in ('archive', 'all-mail', 'trash'): + arch += 1 + archive_score = frac(arch, len(nonactionable)) if nonactionable else 0.0 + + # --- Calendar follow-up for P1 tickets (event on right date + requester guest) --- + cal = go('google_calendar') + cur_events = cal.get('current_state', {}).get('events', []) or [] + + def _event_guests(ev): + g = ev.get('guests') + if not isinstance(g, list): + g = ev.get('attendees') if isinstance(ev.get('attendees'), list) else [] + out = set() + for a in g: + if isinstance(a, dict): + a = a.get('email') or a.get('name') + if a: + out.add(norm(a)) + return out + + p1_emails = [e for e in actionable if (e.get('triage') or {}).get('priority') == 'P1' + and (e.get('triage') or {}).get('event_title')] + n_p1 = len(p1_emails) + event_ok = 0 + guest_ok = 0 + for e in p1_emails: + tri = e['triage'] + want_title = norm(tri.get('event_title')) + want_date = tri.get('event_date') # 'YYYY-MM-DD' + want_guest = norm(tri.get('guest_email')) + ev_match = None + for ev in cur_events: + if not isinstance(ev, dict): + continue + if norm(ev.get('title')) == want_title and date_key(ev.get('start')) == want_date: + ev_match = ev + break + if ev_match is not None: + event_ok += 1 + if want_guest and want_guest in _event_guests(ev_match): + guest_ok += 1 + event_score = frac(event_ok, n_p1) if n_p1 else 0.0 + guest_score = frac(guest_ok, n_p1) if n_p1 else 0.0 + + # --- Slack: summary posted to #support, then PINNED (hidden hover "..." menu) --- + slack = go('slack') + scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + support_msgs = _slack_channel_messages(scur, 'support') + _support_kw = ('triag', 'ticket') + def _is_support_summary(m): + t = (_msg_text(m) or '').lower() + return bool(t.strip()) and any(k in t for k in _support_kw) and any(c.isdigit() for c in t) + post_ok = any(_is_support_summary(m) for m in support_msgs if isinstance(m, dict)) + support_ch = None + for ch in (scur.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == 'support': + support_ch = ch + break + pinned_ids = (support_ch.get('pinnedMessages') or []) if isinstance(support_ch, dict) else [] + support_msg_ids = {(m.get('messageId') or m.get('id')) + for m in support_msgs if isinstance(m, dict)} + # Pin must reference a message that actually lives in #support (so a posted + # summary, not a phantom id), and a post must exist for a pin to count. + pin_ok = bool(post_ok and any(pid in support_msg_ids for pid in pinned_ids)) + post_score = 1.0 if post_ok else 0.0 + pin_score = 1.0 if pin_ok else 0.0 + + s_card = 0.30 * card_f1 + s_glabel = 0.15 * glabel_score + s_label = 0.12 * label_score + s_due = 0.08 * due_score + s_archive = 0.10 * archive_score + s_event = 0.08 * event_score + s_guest = 0.07 * guest_score + s_post = 0.05 * post_score + s_pin = 0.05 * pin_score + score = (s_card + s_glabel + s_label + s_due + s_archive + + s_event + s_guest + s_post + s_pin) + + print( + 'DEBUG_T02 ' + f'actionable={len(actionable)} nonactionable={len(nonactionable)} ' + f'true_cards={len(true_set)} pred_cards={len(pred_set)} card_f1={round(card_f1, 4)} ' + f'glabel_ok={glabel_ok}/{len(actionable)} glabel_score={round(glabel_score, 4)} ' + f'matched={len(matched)} label_ok={lab_ok}/{len(matched)} label_score={round(label_score, 4)} ' + f'due_ok={due_ok}/{len(matched)} due_score={round(due_score, 4)} ' + f'archived={arch}/{len(nonactionable)} archive_score={round(archive_score, 4)} ' + f'p1={n_p1} event_ok={event_ok}/{n_p1} guest_ok={guest_ok}/{n_p1} ' + f'slack_post={post_ok} slack_pin={pin_ok} ' + f'w_card={round(s_card, 4)} w_glabel={round(s_glabel, 4)} w_label={round(s_label, 4)} ' + f'w_due={round(s_due, 4)} w_archive={round(s_archive, 4)} w_event={round(s_event, 4)} ' + f'w_guest={round(s_guest, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} ' + f'total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/csops_incident_command_004__long/_cua_gym_vm_bridge.sh b/csops_incident_command_004__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csops_incident_command_004__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/csops_incident_command_004__long/initial_setup.py b/csops_incident_command_004__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..53f06f622004133b077510089e227bd3cbdac0cc --- /dev/null +++ b/csops_incident_command_004__long/initial_setup.py @@ -0,0 +1,617 @@ +""" +Initial Setup: Incident triage & on-call routing with cross-source availability & ask-before-guess +Task ID: csops_incident_command_004__long (output/0707 #12, cluster C / ITSM) +Mocks: ServiceNow_mock, microsoft_teams_mock, google_calendar_mock, gmail_mock + +The agent is an incident commander working the overnight incident queue in ServiceNow. +Assign each new incident to the on-call engineer for its service, then act by priority. + + * lever d (cross-source): the on-call rota is in a Gmail note; engineer availability + (PTO this window) is in the Calendar. Assignee = rota[service], UNLESS the primary is + on PTO -> route to their backup. No single app decides. + * read-from-history (was lever k): incident INC0007 doesn't name its service owner and the + service isn't in the rota; the answer is PRE-SEEDED in the Teams #incidents HISTORY + (a manager already replied "INC0007 = Payments, on-call Priya Patel"). The agent reads + the channel history and assigns Priya. (Review 2026-07-11: replaced the live ask/reply — + we can't preset a mid-run reply — with an already-answered exchange in history.) + * lever i (bulk + keep-group): 15 incidents. 8 New to assign (2 P1); 3 already In Progress + + 2 Resolved/Closed (keep); 2 Planning (P5) skip. Assigning a keep/skip incident, or the + wrong engineer, lowers decision-set PRECISION. Denominator = the 8. + +Assign = set assigned_to + state 2 (In Progress). P1 also gets a Teams bridge post + a +Calendar "Bridge: " event (dated the incident date). + +GROUND TRUTH: ServiceNow.incidents[*]._inc {branch, priority, service, assignee, is_p1, +actionable}; google_calendar._task_adapter holds the answer key + rota + PTO + bridge date. +Observable results ship ABSENT (Rule 3): New incidents assigned_to null / state 1, no bridge +posts, no bridge events. + +SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't assign keep/skip" is a PRECISION +denominator; the missing-owner (read from history) + PTO-reroute are positive, gated by data flow. +No negatives. No live simulator. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# --------------------------------------------------------------------------- +# Engineers + on-call rota (rota lives in the Gmail note; embedded to precompute key). +# rota: service -> {primary, backup}. PTO this window: user_diaz (primary for 'Search'). +# --------------------------------------------------------------------------- +ENGINEERS = { + 'user_wong': 'Alice Wong', 'user_lee': 'Bob Lee', 'user_diaz': 'Carol Diaz', + 'user_kim': 'David Kim', 'user_patel': 'Priya Patel', 'user_roy': 'Fiona Roy', +} +ROTA = { + 'API': {'primary': 'user_wong', 'backup': 'user_lee'}, + 'Database': {'primary': 'user_lee', 'backup': 'user_wong'}, + 'Search': {'primary': 'user_diaz', 'backup': 'user_kim'}, # diaz on PTO -> backup kim + 'Auth': {'primary': 'user_kim', 'backup': 'user_diaz'}, + 'Web': {'primary': 'user_roy', 'backup': 'user_wong'}, + 'Payments': {'primary': 'user_patel', 'backup': 'user_lee'}, # INC0007 owner (revealed via ask) +} +PTO_USERS = {'user_diaz'} # on PTO this window (from Calendar) +MISSING_OWNER_INCIDENT = 'INC0007' +MISSING_OWNER_SERVICE = 'Payments' + + +def _assignee_for(service): + r = ROTA[service] + primary = r['primary'] + return r['backup'] if primary in PTO_USERS else primary + + +# --------------------------------------------------------------------------- +# Incident spec: (number, short_desc, service, priority, state, kind) +# kind: 'assign' (New, actionable) / 'skip' (P5 Planning) / 'keep' (In Progress/Resolved/Closed) +# priority: 1 (P1) .. 5 (Planning). state: 1 New / 2 In Progress / 6 Resolved / 7 Closed. +# INC0007 (Payments) has service unknown from the ticket -> ask; here we still tag its service +# for the key, but the injected short_description won't name the owner. +# --------------------------------------------------------------------------- +_INC_SPEC = [ + # --- 8 New to assign (2 P1, 6 P2/P3) --- + ('INC0001', 'API 5xx spike', 'API', 1, 1, 'assign'), # P1 + ('INC0002', 'Checkout DB timeouts', 'Database', 1, 1, 'assign'), # P1 + ('INC0003', 'Search results stale', 'Search', 2, 1, 'assign'), # PTO reroute (diaz->kim) + ('INC0004', 'Auth token refresh slow', 'Auth', 2, 1, 'assign'), + ('INC0005', 'Web page load latency', 'Web', 3, 1, 'assign'), + ('INC0006', 'API rate-limit errors', 'API', 3, 1, 'assign'), + ('INC0007', 'Payments latency', 'Payments', 2, 1, 'assign'), # k: owner unknown -> ask + ('INC0008', 'Auth MFA delays', 'Auth', 3, 1, 'assign'), + # --- 2 Planning (P5) -> skip --- + ('INC0009', 'Tech-debt: log rotation', 'Web', 5, 1, 'skip'), + ('INC0010', 'Backlog: metrics cleanup', 'API', 5, 1, 'skip'), + # --- 3 already In Progress -> keep --- + ('INC0011', 'Ongoing DB migration', 'Database', 2, 2, 'keep'), + ('INC0012', 'Search index rebuild', 'Search', 3, 2, 'keep'), + ('INC0013', 'Auth cert renewal', 'Auth', 3, 2, 'keep'), + # --- 2 Resolved/Closed -> keep --- + ('INC0014', 'Resolved: web outage', 'Web', 2, 6, 'keep'), + ('INC0015', 'Closed: api hotfix', 'API', 2, 7, 'keep'), +] + + +def _build_incident(idx, number, desc, service, priority, state, kind): + if kind == 'assign': + branch, actionable = 'assign', True + assignee = _assignee_for(service) + elif kind == 'skip': + branch, actionable, assignee = 'skip', False, None + else: + branch, actionable, assignee = 'keep', False, None + is_p1 = (priority == 1 and kind == 'assign') + # injected: New incidents unassigned; keep incidents pre-assigned. + inj_assigned = None if kind in ('assign', 'skip') else 'user_wong' + return { + 'sys_id': f'inc{idx}', 'number': number, 'caller_id': 'user_ext', + 'category': 'Software', 'short_description': desc, 'description': desc, + 'state': state, 'impact': 2, 'urgency': 2, 'priority': priority, + 'assignment_group': 'g1', 'assigned_to': inj_assigned, + 'opened_at': '2026-04-30T02:00:00Z', 'opened_by': 'user_ext', + 'service': service, 'updated_at': '2026-04-30T02:00:00Z', + '_inc': {'branch': branch, 'priority': priority, 'service': service, + 'assignee': assignee, 'is_p1': is_p1, 'actionable': actionable}, + } + + +_INCIDENTS = [_build_incident(i, *spec) for i, spec in enumerate(_INC_SPEC, start=1)] + + +# --------------------------------------------------------------------------- +# Precompute answer key. +# --------------------------------------------------------------------------- +ASSIGN_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'assign'] +P1_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['is_p1']] +SKIP_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'skip'] +KEEP_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'keep'] +ASSIGNEE_BY_ID = {t['sys_id']: t['_inc']['assignee'] for t in _INCIDENTS if t['_inc']['branch'] == 'assign'} +NUMBER_BY_ID = {t['sys_id']: t['number'] for t in _INCIDENTS} +MISSING_ID = next(t['sys_id'] for t in _INCIDENTS if t['number'] == MISSING_OWNER_INCIDENT) +MISSING_ASSIGNEE = ASSIGNEE_BY_ID[MISSING_ID] +PTO_INCIDENT_ID = next(t['sys_id'] for t in _INCIDENTS if t['number'] == 'INC0003') # Search -> reroute +BRIDGE_EVENTS = [{'number': NUMBER_BY_ID[i], 'title': f'Bridge: {NUMBER_BY_ID[i]}', + 'date': '2026-04-30'} for i in P1_IDS] + +assert len(ASSIGN_IDS) == 8, ASSIGN_IDS +assert len(P1_IDS) == 2, P1_IDS +assert len(SKIP_IDS) == 2 and len(KEEP_IDS) == 5, (SKIP_IDS, KEEP_IDS) +assert ASSIGNEE_BY_ID[PTO_INCIDENT_ID] == 'user_kim', ASSIGNEE_BY_ID[PTO_INCIDENT_ID] # backup, not diaz +assert MISSING_ASSIGNEE == 'user_patel', MISSING_ASSIGNEE +print(f'Assign: {ASSIGN_IDS} (P1={P1_IDS}); skip: {SKIP_IDS}; keep: {KEEP_IDS}') +print(f'PTO reroute INC0003 -> {ASSIGNEE_BY_ID[PTO_INCIDENT_ID]}; INC0007 owner -> {MISSING_ASSIGNEE}') + + +# --------------------------------------------------------------------------- +# ServiceNow state. +# NOTE: ServiceNow_mock frontend (see websites/ServiceNow_mock/SCHEMA.md and +# src/pages/IncidentForm.jsx `${u.first_name} ${u.last_name}`) requires users to have +# {sys_id, user_name, first_name, last_name, email, active}. Passing only {sys_id,name,email} +# makes every Caller/Assigned-to option render as "undefined undefined". +# --------------------------------------------------------------------------- +def _split_full_name(full): + parts = full.split(' ', 1) + return parts[0], (parts[1] if len(parts) > 1 else '') + + +def _sn_user(uid, full_name, email): + first, last = _split_full_name(full_name) + return {'sys_id': uid, 'user_name': uid, 'first_name': first, 'last_name': last, + 'email': email, 'active': True} + + +_SERVICENOW_STATE = { + 'users': [_sn_user(uid, name, f'{uid}@northgate.com') for uid, name in ENGINEERS.items()] + + [_sn_user('user_ext', 'External Caller', 'ext@customer.com')], + 'groups': [{'sys_id': 'g1', 'name': 'SRE On-Call', 'description': 'On-call rotation'}], + 'incidents': _INCIDENTS, 'problems': [], 'changeRequests': [], + 'requests': [], 'requestedItems': [], 'catalogItems': [], 'knowledge': [], 'cmdb': [], + '_task_adapter': {'source_schema': 'incident_oncall', + 'task_id': 'a9b5c210-7e1f-4c3d-d92a-0707aa778800'}, +} + + +# --------------------------------------------------------------------------- +# Microsoft Teams — the incident channel + extra channels/chatter. +# Review changes: +# #2 ask-before-guess REMOVED (no live mid-run reply). Instead the INC0007 owner Q&A is +# PRE-SEEDED in the #incidents history: the manager already answered "INC0007 = Payments, +# on-call Priya Patel". The agent READS history and assigns accordingly (no asking scored). +# #5 add extra channels (general, sre-announcements) + harmless filler chatter so Teams looks +# real; every senderId resolves to a users[] entry with a displayName. +# --------------------------------------------------------------------------- +TEAMS_USERS = [ + {'userId': 'user_1', 'displayName': 'Lena Ortiz', 'email': 'lena@northgate.com'}, + {'userId': 'user_mgr', 'displayName': 'Sam Wren', 'email': 'sam@northgate.com'}, + {'userId': 'user_patel', 'displayName': 'Priya Patel', 'email': 'priya@northgate.com'}, + {'userId': 'user_kim', 'displayName': 'David Kim', 'email': 'david@northgate.com'}, + {'userId': 'user_wong', 'displayName': 'Alice Wong', 'email': 'alice@northgate.com'}, +] + + +def _tmsg(mid, ch, sender, content, ts): + return {'messageId': mid, 'containerId': ch, 'containerType': 'channel', + 'senderId': sender, 'content': content, 'contentType': 'text', + 'messageType': 'message', 'createdDateTime': ts, 'replyToId': None, + 'reactions': [], 'mentions': [], 'attachments': [], 'isBookmarked': False} + + +# #incidents history: seed the INC0007 owner Q&A (already asked & answered) + normal chatter. +_INCIDENTS_HISTORY = [ + _tmsg('msg_seed', 'ch_incidents', 'user_mgr', + 'Overnight queue is up — please triage and assign per the on-call rota.', '2026-04-30T02:00:00Z'), + _tmsg('msg_q_inc7', 'ch_incidents', 'user_1', + 'Quick one: INC0007 (payments latency) does not name a service owner and Payments is ' + 'not in the rota email — who is on-call for it?', '2026-04-30T02:05:00Z'), + _tmsg('msg_a_inc7', 'ch_incidents', 'user_mgr', + 'INC0007 is the Payments service — on-call is Priya Patel (user_patel). Assign it to her.', + '2026-04-30T02:07:00Z'), +] + +_GENERAL_HISTORY = [ + _tmsg('msg_g1', 'ch_general', 'user_mgr', 'Welcome to the SRE workspace :wave:', '2026-04-20T09:00:00Z'), + _tmsg('msg_g2', 'ch_general', 'user_kim', 'Reminder: incident retro moved to Friday 3pm.', '2026-04-28T14:00:00Z'), + _tmsg('msg_g3', 'ch_general', 'user_wong', 'Coffee machine on 4th floor is fixed 🎉', '2026-04-29T10:30:00Z'), +] + +_ANNOUNCE_HISTORY = [ + _tmsg('msg_an1', 'ch_announcements', 'user_mgr', + 'Q2 on-call rotation published — check the pinned rota email.', '2026-04-27T08:00:00Z'), + _tmsg('msg_an2', 'ch_announcements', 'user_mgr', + 'New sev-1 escalation policy takes effect May 1.', '2026-04-29T16:00:00Z'), +] + +_TEAMS_STATE = { + 'currentUser': {'userId': 'user_1', 'displayName': 'Lena Ortiz', 'email': 'lena@northgate.com'}, + 'users': TEAMS_USERS, + 'teams': [{'teamId': 'team_1', 'displayName': 'SRE', 'description': 'Site reliability', + 'avatar': '', 'channels': ['ch_general', 'ch_announcements', 'ch_incidents'], + 'members': [u['userId'] for u in TEAMS_USERS], + 'owners': ['user_mgr'], 'settings': {}}], + 'channels': [ + {'channelId': 'ch_general', 'teamId': 'team_1', 'displayName': 'general', + 'description': 'Team-wide chatter', 'isPinned': False, + 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []}, + {'channelId': 'ch_announcements', 'teamId': 'team_1', 'displayName': 'sre-announcements', + 'description': 'Announcements', 'isPinned': False, + 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []}, + {'channelId': 'ch_incidents', 'teamId': 'team_1', 'displayName': 'incidents', + 'description': 'Incident bridge', 'isPinned': False, + 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []}, + ], + 'chats': [], + 'messages': { + 'ch_general': _GENERAL_HISTORY, + 'ch_announcements': _ANNOUNCE_HISTORY, + 'ch_incidents': _INCIDENTS_HISTORY, + }, + 'meetings': [], 'calls': [], 'files': [], 'notifications': [], + 'settings': {}, 'ui': {}, +} + + +# --------------------------------------------------------------------------- +# Google Calendar — engineer PTO (Carol Diaz) + no Bridge events yet. Answer key on adapter. +# NOTE (review #1): google_calendar_mock only renders events whose calendarId is one of its +# hardcoded ids {c1,c2,c3,c4} AND whose calendar entry is visible. An injected calendar with +# id='primary' is replaced-in (wiping the c1..c4 defaults) so events (normalized to 'c1') have +# no visible calendar -> nothing shows. So we inject a calendar with id='c1', visible=True, and +# reference calendarId='c1' on every event. +# --------------------------------------------------------------------------- +CAL_ID = 'c1' + + +def cal_event(eid, title, start_iso, end_iso, guests): + return {'id': eid, 'calendarId': CAL_ID, 'title': title, 'start': start_iso, + 'end': end_iso, 'location': '', 'description': '', 'guests': guests, + 'color': 'bg-blue-500', 'recurring': 'none'} + + +_CAL_STATE = { + 'user': {'userId': 'u1', 'email': 'lena@northgate.com'}, + 'calendars': [{'id': CAL_ID, 'name': 'On-Call', 'color': 'bg-blue-500', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}], + 'events': [ + cal_event('ev_pto', 'PTO - Carol Diaz', '2026-04-29T00:00:00Z', '2026-05-02T00:00:00Z', []), + cal_event('ev_decoy', 'Weekly SRE sync', '2026-05-01T15:00:00Z', '2026-05-01T15:30:00Z', []), + ], + 'today': '2026-04-30', + '_task_adapter': { + 'source_schema': 'incident_oncall', + 'task_id': 'a9b5c210-7e1f-4c3d-d92a-0707aa778800', + 'variant': 'eval', + # ---- ANSWER KEY ---- + 'assign_ids': ASSIGN_IDS, + 'p1_ids': P1_IDS, + 'skip_ids': SKIP_IDS, + 'keep_ids': KEEP_IDS, + 'assignee_by_id': ASSIGNEE_BY_ID, + 'number_by_id': NUMBER_BY_ID, + 'bridge_events': BRIDGE_EVENTS, + 'missing_owner_id': MISSING_ID, + 'missing_owner_assignee': MISSING_ASSIGNEE, + 'pto_incident_id': PTO_INCIDENT_ID, + 'in_progress_state': 2, + # review #2: no live user-simulator anymore. INC0007's owner is revealed in the + # #incidents Teams HISTORY (msg_a_inc7); the agent reads it and assigns Priya Patel. + # review #3: bridge events must match title AND date (the incident date) on the calendar. + 'bridge_event_date': '2026-04-30', + }, +} + + +# --------------------------------------------------------------------------- +# Gmail — the on-call rota note + a decoy. +# --------------------------------------------------------------------------- +_rota_lines = '
'.join( + f"- {svc}: primary {ENGINEERS[r['primary']]}, backup {ENGINEERS[r['backup']]}" + for svc, r in ROTA.items() if svc != MISSING_OWNER_SERVICE # Payments owner not in the note (ask) +) +_GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Lena Ortiz', 'email': 'lena@northgate.com', + 'avatar': 'https://picsum.photos/200/200?random=23'}, + 'emails': [ + {'id': 'm_rota', 'threadId': 'thread_r', + 'from': {'name': 'On-Call Bot', 'email': 'oncall@northgate.com', 'avatar': ''}, + 'to': [{'name': 'Lena Ortiz', 'email': 'lena@northgate.com'}], 'cc': [], 'bcc': [], + 'subject': 'This week on-call rota', + 'body': ('Hi Lena,

On-call rota for this week:
' + _rota_lines + + '

Remember to check calendars for PTO before assigning.
— On-Call Bot'), + 'snippet': 'On-call rota for this week...', 'timestamp': '2026-04-28T08:00:00Z', + 'read': False, 'starred': False, 'important': True, 'labels': [], + 'category': 'primary', 'folder': 'inbox', 'attachments': []}, + {'id': 'm_decoy1', 'threadId': 'thread_d1', + 'from': {'name': 'IT Newsletter', 'email': 'news@northgate.com', 'avatar': ''}, + 'to': [{'name': 'Lena Ortiz', 'email': 'lena@northgate.com'}], 'cc': [], 'bcc': [], + 'subject': 'April reliability review', 'body': 'Reminders.', 'snippet': 'Reminders...', + 'timestamp': '2026-04-27T15:00:00Z', 'read': True, 'starred': False, + 'important': False, 'labels': [], 'category': 'updates', 'folder': 'inbox', + 'attachments': []}, + ], + 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}], + 'drafts': [], 'settings': {'density': 'default', 'undoSend': 10}, 'today': '2026-04-30', +} + + +# --------------------------------------------------------------------------- +# Inject. +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8105', _SERVICENOW_STATE), # ServiceNow_mock + ('http://28.7.184.198:8162', _TEAMS_STATE), # microsoft_teams_mock + ('http://28.7.184.198:8141', _CAL_STATE), # google_calendar_mock + ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock +] + + +for app_url, state in APP_STATES: + resp = requests.post(f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'State injection failed for {app_url}: {resp.text}' + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}') + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/csops_incident_command_004__long/reward.py b/csops_incident_command_004__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..e39096de20f24a3a2d7ba7ebc71a0ee9060232b0 --- /dev/null +++ b/csops_incident_command_004__long/reward.py @@ -0,0 +1,218 @@ +""" +Reward Script: Incident triage & on-call routing with cross-source availability & ask-before-guess +Task ID: csops_incident_command_004__long (output/0707 #12, cluster C / ITSM) +Mocks: ServiceNow_mock, microsoft_teams_mock, google_calendar_mock, gmail_mock + +Scoring — ALL positive. Every component in [0,1]; weights sum to 1.0. NO penalties, NO gate. + + 0.35 assignment decision-set precision: + frac(#New incidents assigned to CORRECT engineer, 8 + #wrongly_assigned) + (assigning a keep/skip incident, or the wrong engineer, = false positive) + 0.15 state correctness: frac of the 8 moved to In Progress (state 2) + 0.15 P1 bridge: frac of P1 incidents with BOTH a Teams bridge post + a Calendar bridge event + whose title is 'Bridge: ' AND whose date is the incident date + 0.25 missing-owner correctness: INC0007 assigned to the engineer named in the Teams #incidents + history (review 2026-07-11: the owner Q&A is pre-seeded in history; no live ask is scored) + 0.10 PTO-reroute correctness: the PTO-affected incident assigned to the BACKUP + +Answer key: google_calendar.initial_state._task_adapter (assign_ids, p1_ids, assignee_by_id, +bridge_events, bridge_event_date, missing_owner_*, pto_incident_id) + ServiceNow.incidents[*]._inc. +""" +import sys + +import requests + + +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +APP_URLS = { + 'servicenow': 'http://28.7.184.198:8105', + 'microsoft_teams': 'http://28.7.184.198:8162', + 'google_calendar': 'http://28.7.184.198:8141', +} +_GO_CACHE = {} + + +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _date_key(s): + if not s: + return '' + import datetime as dt + txt = str(s).replace('Z', '+00:00') + try: + d = dt.datetime.fromisoformat(txt) + dt.timedelta(hours=8) + return d.date().isoformat() + except Exception: + return str(s)[:10] + + +def _adapt_payload_for_reward(app, payload): + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +def _inc_map(state): + out = {} + for t in (state.get('incidents') or []): + if isinstance(t, dict): + out[t.get('sys_id')] = t + return out + + +def _teams_channel_messages(state, channel_id): + msgs = state.get('messages') + if isinstance(msgs, dict) and isinstance(msgs.get(channel_id), list): + return [m for m in msgs[channel_id] if isinstance(m, dict)] + return [] + + +# =========================================================================== +def reward(go): + W_ASSIGN = 0.35 + W_STATE = 0.15 + W_BRIDGE = 0.15 + W_MISS = 0.25 + W_PTO = 0.10 + + # ---- 1) answer key (on the calendar adapter) ---- + cal = go('google_calendar') + cal_init = cal.get('initial_state', {}) if isinstance(cal.get('initial_state'), dict) else {} + cal_cur = cal.get('current_state', {}) if isinstance(cal.get('current_state'), dict) else {} + adapter = cal_init.get('_task_adapter', {}) if isinstance(cal_init.get('_task_adapter'), dict) else {} + + assign_ids = set(adapter.get('assign_ids') or []) + p1_ids = list(adapter.get('p1_ids') or []) + assignee_by_id = adapter.get('assignee_by_id') if isinstance(adapter.get('assignee_by_id'), dict) else {} + bridge_events = adapter.get('bridge_events') if isinstance(adapter.get('bridge_events'), list) else [] + bridge_date = adapter.get('bridge_event_date') + missing_id = adapter.get('missing_owner_id') + missing_assignee = norm(adapter.get('missing_owner_assignee')) + pto_id = adapter.get('pto_incident_id') + in_progress_state = adapter.get('in_progress_state', 2) + n_assign = len(assign_ids) + if n_assign == 0: + print('DEBUG_SN_ONCALL fatal=no_assign_ids total=0.0') + return 0.0 + + # ---- 2) ServiceNow: assignment diff (only newly-assigned New incidents count) ---- + sn = go('servicenow') + sn_init = sn.get('initial_state', {}) if isinstance(sn.get('initial_state'), dict) else {} + sn_cur = sn.get('current_state', {}) if isinstance(sn.get('current_state'), dict) else {} + init_i = _inc_map(sn_init) + cur_i = _inc_map(sn_cur) + + correct_assign = 0 + wrongly_assign = 0 + for iid, inc in cur_i.items(): + cur_a = norm(inc.get('assigned_to')) + init_a = norm(init_i.get(iid, {}).get('assigned_to')) + if not cur_a or cur_a == init_a: + continue # no new assignment + if iid in assign_ids and cur_a == norm(assignee_by_id.get(iid)): + correct_assign += 1 + else: + wrongly_assign += 1 + assign_score = frac(correct_assign, n_assign + wrongly_assign) + s_assign = W_ASSIGN * assign_score + + # ---- 3) state correctness: the 8 -> In Progress ---- + state_ok = sum(1 for iid in assign_ids + if int(cur_i.get(iid, {}).get('state', -1)) == int(in_progress_state)) + state_score = frac(state_ok, n_assign) + s_state = W_STATE * state_score + + # ---- 4) P1 bridge: Teams post + Calendar bridge event (title AND date) ---- + # review #3: the bridge event must match its title ('Bridge: ') AND be dated the + # incident date, matching the instruction — not just any event with that title. + teams = go('microsoft_teams') + tcur = teams.get('current_state', {}) if isinstance(teams.get('current_state'), dict) else {} + tinit = teams.get('initial_state', {}) if isinstance(teams.get('initial_state'), dict) else {} + init_msg_ids = {m.get('messageId') for m in _teams_channel_messages(tinit, 'ch_incidents')} + new_msgs = [m for m in _teams_channel_messages(tcur, 'ch_incidents') + if m.get('messageId') not in init_msg_ids and norm(m.get('content'))] + cur_events = cal_cur.get('events', []) or [] + + bridge_ok = 0 + for be in bridge_events: + num = norm(be.get('number')) + title = norm(be.get('title')) + want_date = be.get('date') or bridge_date + posted = any(num in norm(m.get('content')) for m in new_msgs) + evented = any(norm(ev.get('title')) == title and _date_key(ev.get('start')) == want_date + for ev in cur_events) + if posted and evented: + bridge_ok += 1 + bridge_score = frac(bridge_ok, len(bridge_events)) if bridge_events else 0.0 + s_bridge = W_BRIDGE * bridge_score + + # ---- 5) missing-owner correctness: INC0007 assigned to the engineer named in Teams history ---- + # review #2: the answer is pre-seeded in the #incidents history (no live ask scored). + miss_ok = (norm(cur_i.get(missing_id, {}).get('assigned_to')) == missing_assignee) + s_miss = W_MISS * (1.0 if miss_ok else 0.0) + + # ---- 6) PTO-reroute correctness: PTO incident assigned to the BACKUP ---- + pto_ok = (norm(cur_i.get(pto_id, {}).get('assigned_to')) == norm(assignee_by_id.get(pto_id))) + s_pto = W_PTO * (1.0 if pto_ok else 0.0) + + score = clamp01(s_assign + s_state + s_bridge + s_miss + s_pto) + + print( + 'DEBUG_SN_ONCALL ' + f'n_assign={n_assign} correct={correct_assign} wrongly={wrongly_assign} ' + f'assign={round(assign_score, 4)} state_ok={state_ok}/{n_assign} ' + f'bridge_ok={bridge_ok}/{len(bridge_events)} miss_ok={miss_ok} pto_ok={pto_ok} ' + f'w_assign={round(s_assign, 4)} w_state={round(s_state, 4)} w_bridge={round(s_bridge, 4)} ' + f'w_miss={round(s_miss, 4)} w_pto={round(s_pto, 4)} ' + f'total={round(score, 4)}' + ) + return score + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/hr_payroll_approval_006__long/_cua_gym_vm_bridge.sh b/hr_payroll_approval_006__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/hr_payroll_approval_006__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/hr_payroll_approval_006__long/initial_setup.py b/hr_payroll_approval_006__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4203719ca5551d7f39b3e0456ae5395c37a0f533 --- /dev/null +++ b/hr_payroll_approval_006__long/initial_setup.py @@ -0,0 +1,782 @@ +""" +Initial Setup: W06 — Payroll specialist batch approval + chase dispatch +Task ID: hr_payroll_approval_006__long +Persona: Payroll Specialist Niko +Mocks: workday_mock (L2 anchor) , asana_mock (L1) , microsoft_teams_mock , gmail_mock + +Ground-truth embedding (read by reward.py from initial_state): + - Workday tasks[*]._expected_approve on every Pending inbox task + (True -> agent should approve it via the bulk-approve bar; + False -> agent must LEAVE it pending and open a follow-up instead). + - On every _expected_approve==False task: tasks[*]._chase_title (the Asana + follow-up task title the agent should create) and tasks[*]._expected_priority + ('High' for over-cap timesheets, 'Medium' for non-compliant leave). +Observable outputs kept ABSENT at injection (Rule 3): + - all 10 pending inbox tasks still have status=='Pending' (none decided) + - Asana has NO 'Follow up: ' task — agent must create each one and set + its Priority custom field + - microsoft_teams 'Payroll' channel has zero messages + - gmail has no SENT notification email +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# =========================================================================== +# WORKDAY (L2 anchor: Inbox bulk-approve bar — renders only when >=1 pending +# task is checked; handleBulkApprove COMPLETE_TASKs the selected subset). +# +# Approval rule (documented in instruction; encoded here only via the +# _expected_approve answer key, NOT re-derived in reward): +# APPROVE a pending request if it is in-policy: +# - a weekly timesheet of 40 hours or fewer, OR +# - a leave request that is within the employee's balance AND does not +# overlap the month-end payroll blackout. +# DO NOT APPROVE (leave pending + open a follow-up) if it breaks policy: +# - a timesheet logging more than 40 hours (unauthorised overtime), OR +# - leave that exceeds the remaining balance or overlaps the blackout. +# =========================================================================== +def wd_employee(eid, name, title, dept, dept_id, mgr='emp_niko'): + first = name.split()[0] + return { + 'id': eid, 'name': name, + 'email': f'{name.lower().replace(" ", ".")}@acmecorp.com', + 'phone': '+1 (415) 555-0100', 'role': 'Employee', 'department': dept, + 'departmentId': dept_id, + 'avatar': f'https://ui-avatars.com/api/?name={first}&background=0875E1&color=fff&size=128', + 'managerId': mgr, 'title': title, 'location': 'San Francisco, CA', + 'joinDate': '2021-05-01', 'employeeType': 'Full-Time', + 'birthday': '1990-01-01', 'workAnniversary': '2021-05-01', + } + + +def wd_task(task_id, sub_type, description, initiator, business_process, + due_date, priority, expected_approve, + chase_title=None, expected_priority=None): + """A Pending inbox approval. Carries the hidden answer key.""" + rec = { + 'taskId': task_id, 'employeeId': 'emp_niko', 'type': 'Approval', + 'subType': sub_type, 'description': description, 'status': 'Pending', + 'dueDate': due_date, 'createdDate': '2026-06-26', + 'relatedId': None, 'initiator': initiator, + 'businessProcess': business_process, 'priority': priority, + 'comments': [], + '_expected_approve': expected_approve, # hidden answer key + } + if chase_title is not None: + rec['_chase_title'] = chase_title + if expected_priority is not None: + rec['_expected_priority'] = expected_priority + return rec + + +NIKO = { + 'id': 'emp_niko', 'name': 'Niko Bellic', + 'email': 'niko.bellic@acmecorp.com', 'phone': '+1 (415) 555-0188', + 'role': 'Manager', 'department': 'Finance', 'departmentId': 'dept004', + 'avatar': 'https://ui-avatars.com/api/?name=Niko+Bellic&background=0875E1&color=fff&size=128', + 'managerId': 'emp_dir', 'title': 'Payroll Specialist', + 'location': 'San Francisco, CA', 'joinDate': '2019-02-11', + 'employeeType': 'Full-Time', 'skills': ['Payroll', 'Compliance'], + 'birthday': '1986-09-12', 'workAnniversary': '2019-02-11', +} +WD_DIRECTOR = { + 'id': 'emp_dir', 'name': 'Sandra Voss', 'email': 'sandra.voss@acmecorp.com', + 'phone': '+1 (415) 555-0101', 'role': 'Director', 'department': 'Finance', + 'departmentId': 'dept004', + 'avatar': 'https://ui-avatars.com/api/?name=Sandra+Voss&background=7C3AED&color=fff&size=128', + 'managerId': None, 'title': 'Director of Finance', + 'location': 'San Francisco, CA', 'joinDate': '2016-01-04', + 'employeeType': 'Full-Time', 'birthday': '1980-03-03', + 'workAnniversary': '2016-01-04', +} + +WD_EMPLOYEES = [ + NIKO, WD_DIRECTOR, + # Tom Reed — payroll analyst on Niko's team; the exception-handoff email + # recipient. Present in the Workday Directory so his address is discoverable + # (the instruction names him but does not give his email). + wd_employee('emp110', 'Tom Reed', 'Payroll Analyst', 'Finance', 'dept004'), + wd_employee('emp101', 'Marcus Johnson', 'Backend Engineer', 'Engineering', 'dept001'), + wd_employee('emp102', 'Rachel Green', 'Data Analyst', 'Engineering', 'dept001'), + wd_employee('emp103', 'David Kim', 'Network Engineer', 'Engineering', 'dept001'), + wd_employee('emp104', 'Nina Patel', 'QA Engineer', 'Engineering', 'dept001'), + wd_employee('emp105', 'John Smith', 'Frontend Engineer', 'Engineering', 'dept001'), + wd_employee('emp106', 'Emily Chen', 'Product Designer', 'Design', 'dept002'), + wd_employee('emp107', 'Lisa Park', 'Marketing Lead', 'Marketing', 'dept003'), + wd_employee('emp108', 'James Wilson', 'Sales Rep', 'Marketing', 'dept003'), + wd_employee('emp109', 'Priya Nair', 'Recruiter', 'Human Resources', 'dept005'), +] + +WD_DEPARTMENTS = [ + {'id': 'dept001', 'name': 'Engineering', 'headcount': 5, 'managerId': 'emp_dir'}, + {'id': 'dept002', 'name': 'Design', 'headcount': 1, 'managerId': 'emp_dir'}, + {'id': 'dept003', 'name': 'Marketing', 'headcount': 2, 'managerId': 'emp_dir'}, + {'id': 'dept004', 'name': 'Finance', 'headcount': 3, 'managerId': 'emp_dir'}, + {'id': 'dept005', 'name': 'Human Resources', 'headcount': 1, 'managerId': 'emp_dir'}, +] + +# --- 12 PENDING approval tasks (the batch to triage) ----------------------- +# 7 in-policy -> approve; 5 out-of-policy -> leave pending + chase. +# +# DESIGN (v2): descriptions give ONLY the raw facts — never the verdict. The +# agent must APPLY the policy itself: +# - timesheets list per-day hours; the agent sums them and compares to 40. +# - leave requests give only the raw date range; the agent must read the +# blackout window (Jun 29 - Jul 3) from the Workday announcement / the HR +# email — it is NOT repeated in the task — and compute the overlap. +# - over-balance leave states the request hours AND the employee's remaining +# balance for that leave type; the agent compares the two. +# Boundary traps: a timesheet of EXACTLY 40.0h is in-policy; 40.5h is not. A +# leave ending the day BEFORE the blackout is fine; one ending on its first day +# is not. So a "looks like a lot" heuristic fails — real arithmetic is required. +WD_PENDING = [ + # ---- APPROVE: standard timesheets (sum <= 40h) ---- + wd_task('wd_t1', 'Timesheet Approval', + '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.', + 'John Smith', 'Submit Timesheet', '2026-07-01', 'Normal', + expected_approve=True), + wd_task('wd_t2', 'Timesheet Approval', + '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.', + 'Emily Chen', 'Submit Timesheet', '2026-07-01', 'Normal', + expected_approve=True), + # boundary: exactly 40.0h across 6 days -> still in policy (approve) + wd_task('wd_t3', 'Timesheet Approval', + '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.', + 'Lisa Park', 'Submit Timesheet', '2026-07-01', 'Normal', + expected_approve=True), + # ---- APPROVE: in-policy leave (no blackout overlap, within balance) ---- + wd_task('wd_t4', 'Time Off Request', + 'Vacation request — James Wilson, Jul 13-15 (24 hours requested). Remaining vacation balance: 80 hours.', + 'James Wilson', 'Request Time Off', '2026-07-08', 'Normal', + expected_approve=True), + wd_task('wd_t5', 'Time Off Request', + 'Sick leave — Sandra Voss, Jul 6 (8 hours requested). Remaining sick balance: 40 hours.', + 'Sandra Voss', 'Request Time Off', '2026-07-06', 'Normal', + expected_approve=True), + wd_task('wd_t6', 'Time Off Request', + 'Personal day — Priya Nair, Jul 8 (8 hours requested). Remaining personal balance: 16 hours.', + 'Priya Nair', 'Request Time Off', '2026-07-07', 'Low', + expected_approve=True), + # boundary: leave ending the day BEFORE the blackout starts -> approve + wd_task('wd_t11', 'Time Off Request', + 'Vacation request — Emily Chen, Jun 26-28 (24 hours requested). Remaining vacation balance: 64 hours.', + 'Emily Chen', 'Request Time Off', '2026-06-25', 'Normal', + expected_approve=True), + # ---- DO NOT APPROVE: over-cap timesheets (sum > 40h) -> chase High ---- + wd_task('wd_t7', 'Timesheet Approval', + '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.', + 'Marcus Johnson', 'Submit Timesheet', '2026-07-01', 'High', + expected_approve=False, + chase_title='Follow up: Marcus Johnson', expected_priority='High'), + # boundary: 40.5h (just over) -> NOT in policy, chase High + wd_task('wd_t8', 'Timesheet Approval', + '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.', + 'Rachel Green', 'Submit Timesheet', '2026-07-01', 'High', + expected_approve=False, + chase_title='Follow up: Rachel Green', expected_priority='High'), + # ---- DO NOT APPROVE: non-compliant leave -> chase Medium ---- + # overlaps blackout (Jun 29 - Jul 3): agent must read blackout elsewhere + wd_task('wd_t9', 'Time Off Request', + 'Vacation request — David Kim, Jun 29 - Jul 2 (32 hours requested). Remaining vacation balance: 96 hours.', + 'David Kim', 'Request Time Off', '2026-06-26', 'High', + expected_approve=False, + chase_title='Follow up: David Kim', expected_priority='Medium'), + # boundary: ends ON the blackout's first day -> overlaps -> chase Medium + wd_task('wd_t12', 'Time Off Request', + 'Vacation request — John Smith, Jun 27-29 (24 hours requested). Remaining vacation balance: 72 hours.', + 'John Smith', 'Request Time Off', '2026-06-26', 'Normal', + expected_approve=False, + chase_title='Follow up: John Smith', expected_priority='Medium'), + # over balance: 48h requested vs 16h remaining -> chase Medium + wd_task('wd_t10', 'Time Off Request', + 'Vacation request — Nina Patel, Jul 6-13 (48 hours requested). Remaining vacation balance: 16 hours.', + 'Nina Patel', 'Request Time Off', '2026-07-02', 'High', + expected_approve=False, + chase_title='Follow up: Nina Patel', expected_priority='Medium'), +] + +# --- NOISE: already-processed tasks (Archive tab, no checkbox, not scored) -- +WD_NOISE = [ + {'taskId': 'wd_n1', 'employeeId': 'emp_niko', 'type': 'Approval', + 'subType': 'Timesheet Approval', + 'description': 'Approve weekly timesheet — John Smith, week of Jun 15. Already approved.', + 'status': 'Completed', 'dueDate': '2026-06-22', 'createdDate': '2026-06-19', + 'relatedId': None, 'initiator': 'John Smith', 'businessProcess': 'Submit Timesheet', + 'priority': 'Normal', 'comments': []}, + {'taskId': 'wd_n2', 'employeeId': 'emp_niko', 'type': 'Approval', + 'subType': 'Time Off Request', + 'description': 'Approve vacation — Marcus Johnson, May 5-7. Previously denied (blackout).', + 'status': 'Denied', 'dueDate': '2026-05-04', 'createdDate': '2026-05-01', + 'relatedId': None, 'initiator': 'Marcus Johnson', 'businessProcess': 'Request Time Off', + 'priority': 'Normal', 'comments': []}, +] + +WD_TASKS = WD_PENDING + WD_NOISE + +WORKDAY_STATE = { + 'currentUser': NIKO, + 'employees': WD_EMPLOYEES, + 'departments': WD_DEPARTMENTS, + 'timeEntries': [ + {'entryId': 'te1', 'employeeId': 'emp_niko', 'date': '2026-06-24', 'hours': 8, + 'project': 'General', 'status': 'Approved', 'notes': ''}, + ], + 'timeOffRequests': [ + {'requestId': 'tr1', 'employeeId': 'emp108', 'type': 'Vacation', + 'startDate': '2026-07-13', 'endDate': '2026-07-15', 'status': 'Pending', + 'reason': 'Family trip', 'totalHours': 24, 'reviewedBy': None, 'reviewedDate': None}, + ], + 'timeOffBalance': {'vacation': 120, 'sick': 40, 'personal': 16}, + 'payroll': [ + {'paystubId': 'ps1', 'employeeId': 'emp_niko', 'period': 'Jun 1 - Jun 15, 2026', + 'payDate': '2026-06-15', 'date': '2026-06-15', 'grossPay': 5576.92, + 'federalTax': 892.31, 'stateTax': 445.35, 'socialSecurity': 345.77, + 'medicare': 80.87, 'healthInsurance': 120.00, 'retirement401k': 278.85, + 'otherDeductions': 15.00, 'totalDeductions': 2178.15, 'netPay': 3398.77, + 'deductions': 2178.15}, + ], + 'benefits': { + 'employeeId': 'emp_niko', 'enrollmentStatus': 'Complete', + 'plans': [ + {'id': 'b1', 'type': 'Medical', 'name': 'Medical - PPO Plus', + 'provider': 'BlueCross BlueShield', 'coverageLevel': 'Employee Only', + 'employeeCost': 180.00, 'employerCost': 600.00, 'cost': 180.00, + 'status': 'Active', 'effectiveDate': '2024-01-01', + 'details': {'deductible': 1500, 'outOfPocketMax': 5000, 'copay': 25, 'coinsurance': 20}}, + ], + 'dependents': [], + }, + 'reviews': [], + 'goals': [], + 'tasks': WD_TASKS, + 'announcements': [ + {'id': 'a1', 'title': 'Month-End Payroll Blackout', 'date': '2026-06-25', + 'content': 'Payroll blackout runs Jun 29 - Jul 3. No leave should be approved that overlaps these dates.', + 'category': 'HR', 'priority': 'High'}, + ], + 'notifications': [ + {'id': 'n1', 'type': 'task', 'title': 'Approvals waiting', + 'message': 'You have timesheet and leave approvals waiting in your inbox.', + 'timestamp': '2026-06-26T09:00:00.000Z', 'read': False, 'link': '/inbox'}, + ], + 'clockStatus': {'isClockedIn': False, 'startTime': None}, +} + + +# =========================================================================== +# ASANA (L1: per chase item, create a 'Follow up: ' task and set its +# Priority custom field — customFieldValues['field-1']). No follow-up task is +# pre-seeded; only unrelated noise tasks exist. +# =========================================================================== +def asana_user(uid, name, title, dept): + return { + 'userId': uid, 'name': name, + 'email': f'{name.lower().replace(" ", ".")}@company.com', + 'avatar': f'https://i.pravatar.cc/150?u={uid}', 'title': title, + 'department': dept, 'location': 'San Francisco, CA', + 'timezone': 'PST', 'theme': 'light', + } + + +ASANA_NIKO = asana_user('user-0', 'Niko Bellic', 'Payroll Specialist', 'Finance') +ASANA_USERS = [ + ASANA_NIKO, + asana_user('user-1', 'Sandra Voss', 'Director of Finance', 'Finance'), + asana_user('user-2', 'Tom Reed', 'Payroll Analyst', 'Finance'), +] + +ASANA_PROJECT = { + 'projectId': 'project-payroll', 'name': 'Payroll Operations', 'teamId': 'team-1', + 'description': 'Payroll cycle tasks, exceptions, and follow-ups.', + 'color': '#4186E0', 'icon': 'https://i.pravatar.cc/40?u=payroll', + 'ownerId': 'user-0', 'memberIds': ['user-0', 'user-1', 'user-2'], + 'sections': [ + {'sectionId': 'section-p-1', 'name': 'Follow-ups', 'collapsed': False}, + {'sectionId': 'section-p-2', 'name': 'In Progress', 'collapsed': False}, + {'sectionId': 'section-p-3', 'name': 'Done', 'collapsed': False}, + ], + 'customFields': [ + {'id': 'field-1', 'name': 'Priority', 'type': 'dropdown', + 'options': ['High', 'Medium', 'Low']}, + ], + 'privacy': 'public', 'startDate': '2026-06-01', 'dueDate': '2026-07-31', + 'archived': False, 'starred': True, + 'createdDate': '2026-06-01T00:00:00Z', 'modifiedDate': '2026-06-25T00:00:00Z', +} + + +def asana_task(task_id, name, section_id, priority=None): + rec = { + 'taskId': task_id, 'name': name, 'projectId': 'project-payroll', + 'sectionId': section_id, 'description': '', 'assigneeId': 'user-0', + 'creatorId': 'user-0', 'completed': False, 'dependencies': [], + 'tags': [], 'attachmentIds': [], 'customFieldValues': {}, + 'likeCount': 0, 'createdDate': '2026-06-20T00:00:00Z', + 'modifiedDate': '2026-06-20T00:00:00Z', + } + if priority is not None: + rec['customFieldValues']['field-1'] = priority + return rec + + +# Noise tasks only — NOT the 'Follow up: ' chase tasks. +ASANA_TASKS = [ + asana_task('task-noise-1', 'Reconcile June payroll register', 'section-p-2', 'Medium'), + asana_task('task-noise-2', 'File Q2 941 tax deposit', 'section-p-1', 'High'), + asana_task('task-noise-3', 'Update direct-deposit forms batch', 'section-p-3'), +] + +ASANA_STATE = { + 'currentUser': ASANA_NIKO, + 'users': ASANA_USERS, + 'teams': [ + {'teamId': 'team-1', 'name': 'Finance', 'description': 'Finance & payroll', + 'memberIds': ['user-0', 'user-1', 'user-2'], 'ownerId': 'user-1', + 'privacy': 'public', 'createdDate': '2026-01-01T00:00:00Z'}, + ], + 'projects': [ASANA_PROJECT], + 'tasks': ASANA_TASKS, + 'comments': [], + 'portfolios': [], + 'goals': [], + 'notifications': [], + 'attachments': [], +} + + +# =========================================================================== +# MICROSOFT TEAMS (post a summary to the 'Payroll' channel — Posts only; +# Calendar/Files untouched to avoid the known crash). Channel starts empty. +# =========================================================================== +def teams_user(uid, name, title, dept): + first, last = (name.split() + [''])[:2] + return { + 'userId': uid, 'displayName': name, 'firstName': first, 'lastName': last, + 'email': f'{name.lower().replace(" ", ".")}@contoso.com', + 'avatar': f'https://i.pravatar.cc/150?u={uid}', 'jobTitle': title, + 'department': dept, 'location': 'Seattle, WA', 'phone': '+1 (206) 555-0110', + 'presence': 'available', 'statusMessage': '', 'statusEmoji': '', + 'outOfOffice': False, 'timezone': 'America/Los_Angeles', + } + + +TEAMS_NIKO = teams_user('user_1', 'Niko Bellic', 'Payroll Specialist', 'Finance') +TEAMS_USERS = [ + TEAMS_NIKO, + teams_user('user_2', 'Sandra Voss', 'Director of Finance', 'Finance'), + teams_user('user_3', 'Tom Reed', 'Payroll Analyst', 'Finance'), +] + +TEAMS_STATE = { + 'currentUser': TEAMS_NIKO, + 'users': TEAMS_USERS, + 'teams': [ + {'teamId': 'team_fin', 'displayName': 'Finance Ops', 'description': 'Finance & payroll collaboration', + 'avatar': '', 'avatarColor': '#4A90D9', 'avatarInitials': 'FO', + 'visibility': 'private', 'isArchived': False, 'isFavorite': True, + 'createdDateTime': '2024-06-15T10:00:00Z', + 'members': ['user_1', 'user_2', 'user_3'], 'owners': ['user_2'], + 'channels': ['ch_general', 'ch_payroll'], + 'settings': {'allowMemberCreateChannels': True, 'allowMemberDeleteMessages': True, + 'allowGiphy': True, 'allowStickers': True, 'allowMemes': True}}, + ], + 'channels': [ + {'channelId': 'ch_general', 'teamId': 'team_fin', 'displayName': 'General', + 'description': 'General finance discussion', 'membershipType': 'standard', + 'isFavoriteByDefault': True, 'isPinned': False, 'isMuted': False, 'unreadCount': 0, + 'lastMessagePreview': 'Reminder: month-end blackout starts Jun 29.', + 'lastMessageTimestamp': '2026-06-25T15:00:00.000Z', + 'createdDateTime': '2024-06-15T10:00:00Z', 'members': [], + 'tabs': [{'tabId': 'tab_posts_g', 'displayName': 'Posts', 'type': 'posts', 'isDefault': True}], + 'pinnedMessages': []}, + {'channelId': 'ch_payroll', 'teamId': 'team_fin', 'displayName': 'Payroll', + 'description': 'Payroll approvals and exceptions', 'membershipType': 'standard', + 'isFavoriteByDefault': False, 'isPinned': False, 'isMuted': False, 'unreadCount': 0, + 'lastMessagePreview': '', 'lastMessageTimestamp': '2026-06-25T09:00:00.000Z', + 'createdDateTime': '2026-06-01T10:00:00Z', 'members': [], + 'tabs': [{'tabId': 'tab_posts_p', 'displayName': 'Posts', 'type': 'posts', 'isDefault': True}], + 'pinnedMessages': []}, + ], + 'chats': [], + 'messages': { + 'ch_general': [ + {'messageId': 'msg_g1', 'containerId': 'ch_general', 'containerType': 'channel', + 'senderId': 'user_2', 'content': 'Reminder: month-end blackout starts Jun 29.', + 'contentType': 'text', 'messageType': 'message', + 'createdDateTime': '2026-06-25T15:00:00.000Z', 'lastEditedDateTime': None, + 'deletedDateTime': None, 'importance': 'normal', 'subject': '', + 'replyToId': None, 'reactions': [], 'mentions': [], 'attachments': [], + 'isBookmarked': False}, + ], + 'ch_payroll': [], + }, + 'meetings': [], + 'calls': [], + 'files': [], + 'notifications': [], + 'settings': { + 'theme': 'light', 'language': 'en-US', + 'notifications': {'showMessagePreviews': True, 'playSound': True, 'showBadgeCount': True, + 'muteAll': False, 'quietHoursEnabled': False, + 'quietHoursStart': '22:00', 'quietHoursEnd': '07:00'}, + 'privacy': {'readReceipts': True, 'showPresence': True}, + 'display': {'density': 'comfortable', 'showChannelPreview': True}, + }, + 'ui': {'activeView': 'chat', 'activeTeamId': None, 'activeChannelId': None, + 'activeChatId': None, 'activeThreadMessageId': None, 'isThreadPanelOpen': False, + 'isDetailsPanelOpen': False, 'searchQuery': '', 'searchResults': None}, +} + + +# =========================================================================== +# GMAIL (record hub: send a notification email; no SENT email pre-seeded). +# =========================================================================== +GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Niko Bellic', 'email': 'niko.bellic@acmecorp.com', + 'avatar': 'https://i.pravatar.cc/150?u=niko'}, + 'emails': [ + {'id': 'email_1', 'threadId': 'thread_1', + 'from': {'name': 'Sandra Voss', 'email': 'sandra.voss@acmecorp.com'}, + 'to': [{'name': 'Niko Bellic', 'email': 'niko.bellic@acmecorp.com'}], + 'cc': [], 'bcc': [], + 'subject': 'This week’s timesheet & leave approvals', + 'body': '

Niko, please clear the approval queue in Workday today and flag anything that breaks policy. Thanks!

', + 'snippet': 'Please clear the approval queue in Workday today.', + 'timestamp': '2026-06-26T08:30:00Z', 'read': False, 'starred': False, + 'important': True, 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox', + 'attachments': []}, + {'id': 'email_2', 'threadId': 'thread_2', + 'from': {'name': 'Acme HR', 'email': 'hr@acmecorp.com'}, + 'to': [{'name': 'Niko Bellic', 'email': 'niko.bellic@acmecorp.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Payroll blackout: Jun 29 – Jul 3', + 'body': '

The month-end payroll blackout runs Jun 29 through Jul 3. Do not approve leave overlapping these dates.

', + 'snippet': 'The month-end payroll blackout runs Jun 29 through Jul 3.', + 'timestamp': '2026-06-25T12:00:00Z', 'read': True, 'starred': False, + 'important': False, 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox', + 'attachments': []}, + ], + 'labels': [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'l3', 'name': 'Travel', 'color': '#22c55e'}, + {'id': 'l4', 'name': 'Finance', 'color': '#eab308'}, + ], + 'drafts': [], +} + + +# =========================================================================== +# Inject (each mock gets its FULL top-level schema; missing keys -> blank page) +# =========================================================================== +APP_STATES = [ + ('http://28.7.184.198:8192', WORKDAY_STATE), # workday_mock (L2 anchor) + ('http://28.7.184.198:8114', ASANA_STATE), # asana_mock (L1) + ('http://28.7.184.198:8162', TEAMS_STATE), # microsoft_teams_mock + ('http://28.7.184.198:8138', GMAIL_STATE), # gmail_mock +] + +for placeholder, state in APP_STATES: + resp = requests.post( + f'{placeholder}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {placeholder}: {resp.text}' + ) + print(f'State injected: {placeholder} sid={sid}') + +for placeholder, _ in APP_STATES: + go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state') is not None, ( + f'initial_state is None after injection for {placeholder}' + ) + print(f'Verified initial_state set: {placeholder}') + + +def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8): + """Pure-HTTP readiness: wait for every mock to serve its injected state. + No CDP / 9222 probing (that hangs on local review boxes).""" + import urllib.request as _urlreq + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + deadline = time.time() + timeout + todo = list(urls) + while todo and time.time() < deadline: + rest = [] + for _u in todo: + try: + _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5) + if _r.status == 200: + print(f" {_u}: ready") + continue + except Exception: + pass + rest.append(_u) + todo = rest + if todo: + time.sleep(2) + print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}" + + (f" (pending: {todo})" if todo else "")) + time.sleep(render_buffer) + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/hr_payroll_approval_006__long/reward.py b/hr_payroll_approval_006__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..586f56c685924fbb612e8602defed58d7f12e76c --- /dev/null +++ b/hr_payroll_approval_006__long/reward.py @@ -0,0 +1,341 @@ +""" +Reward Script: W06 — Payroll specialist batch approval + chase dispatch +Task ID: hr_payroll_approval_006__long +Persona: Payroll Specialist Niko +Mocks: workday_mock (L2 anchor) , asana_mock (L1) , microsoft_teams_mock , gmail_mock + +Answer key (embedded in initial_state): + - workday tasks[*]._expected_approve on every Pending task (True/False). + - on each _expected_approve==False task: _chase_title (Asana follow-up title) + and _expected_priority ('High' over-cap timesheet | 'Medium' bad leave). + +Scoring (sub-weights sum to 1.0): + 0.45 Workday bulk approval (L2 anchor): penalty-based recall over the + should-approve set. +1 for each in-policy task the agent actively + Completed; -1 for each out-of-policy (chase) task the agent wrongly + Completed; score = max(0, +sum) / n_approve. Untouched state scores 0 + (so "approve nothing" earns nothing) and "approve everything" is + penalised (W04 lesson). Reachable only via the gated bulk-approve bar + (renders only when >=1 task is checked). NOTE (v2): task descriptions + give only raw facts (per-day hours / raw leave dates / balance); the + agent must APPLY the policy — sum hours vs 40, read the blackout window + from the announcement/email and compute date overlap, compare requested + hours vs balance — rather than read a pre-computed verdict. + 0.25 Asana follow-ups (recall, no penalty for extras): per chase item, an + Asana task titled 'Follow up: ' exists (half) with its Priority + custom field == _expected_priority (other half). + 0.15 Teams 'Payroll' channel (TWO posts, strict): 0.075 a summary post with + the EXACT approved/follow-up counts + 0.075 an exception-list post + naming every flagged employee (partial = fraction of names). No + non-empty fallback. + 0.15 Gmail (TWO sent emails, strict): 0.075 a summary to Sandra Voss + (sandra.voss@acmecorp.com) with the EXACT counts + 0.075 an exception + handoff to Tom Reed (tom.reed@acmecorp.com) naming every flagged + employee (partial = fraction of names). No "any sent email" fallback. +""" +import re +import sys + +import requests + +# --- Read sid (fatal if missing) --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +APP_URLS = { + 'workday': 'http://28.7.184.198:8192', + 'asana': 'http://28.7.184.198:8114', + 'teams': 'http://28.7.184.198:8162', + 'gmail': 'http://28.7.184.198:8138', +} +_GO_CACHE = {} + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)') + print('REWARD: 0.0') + sys.exit(0) + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + _GO_CACHE[app_name] = payload + return payload + + +# --- Shared utils --- +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _collapse_ws(s): + return re.sub(r'\s+', ' ', norm(s)) + + +def _by_id(records, key): + out = {} + for r in records or []: + if isinstance(r, dict) and r.get(key) is not None: + out[r[key]] = r + return out + + +def _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +def _teams_channel_messages(teams_state, channel_name): + channels = teams_state.get('channels', []) or [] + target = None + for ch in channels: + if norm(ch.get('displayName')) == norm(channel_name) or norm(ch.get('name')) == norm(channel_name): + target = ch + break + if target is None: + return [] + msg_map = teams_state.get('messages', {}) or {} + if isinstance(msg_map, dict): + return msg_map.get(target.get('channelId'), []) or [] + return [] + + +def _asana_priority(task): + cfv = task.get('customFieldValues', {}) or {} + return norm(cfv.get('field-1')) + + +def _names_present(text, names): + """How many of `names` appear in `text` (full name, case-insensitive).""" + t = norm(text) + return sum(1 for nm in names if norm(nm) in t) + + +def _counts_match(text, n_approve, n_chase): + """True iff the text states BOTH the approved count and the follow-up count + correctly, accepting either word order ('7 approved' or 'approved 7', etc.). + Strict on the numbers, lenient on phrasing.""" + low = norm(text) + approve_kw = r'(?:approv\w*)' + chase_kw = r'(?:follow[- ]?ups?|flagged|exceptions?|pending|on hold|held)' + + def _has(n, kw): + return bool( + re.search(rf'\b{n}\b[^.\n]{{0,30}}?{kw}', low) or + re.search(rf'{kw}[^.\n0-9]{{0,30}}?\b{n}\b', low) + ) + return _has(n_approve, approve_kw) and _has(n_chase, chase_kw) + + +# ============================================================================= +# Task-specific reward +# ============================================================================= +def reward(go): + wd_i = go('workday').get('initial_state', {}) or {} + wd_c = go('workday').get('current_state', {}) or {} + asana_c = go('asana').get('current_state', {}) or {} + teams_c = go('teams').get('current_state', {}) or {} + gmail_c = go('gmail').get('current_state', {}) or {} + + tasks_i = wd_i.get('tasks', []) or [] + tasks_c_by_id = _by_id(wd_c.get('tasks', []), 'taskId') + + # ---- Answer key: pending tasks carrying _expected_approve ---- + pendings = [t for t in tasks_i + if norm(t.get('status')) == 'pending' and '_expected_approve' in t] + n = len(pendings) + if n == 0: + print('DEBUG_W06 no pending tasks with embedded answer key; nothing to score') + return 0.0 + + should_approve = [t for t in pendings if t.get('_expected_approve') is True] + should_chase = [t for t in pendings if t.get('_expected_approve') is False] + n_approve = len(should_approve) + n_chase = len(should_chase) + + # Flagged employee names (from the chase answer key) — the exception list / + # handoff must name every one of these. Derive from _chase_title + # ('Follow up: ') so it stays correct across variants. + flagged_names = [] + for t in should_chase: + ct = t.get('_chase_title') or '' + nm = ct.split(':', 1)[1].strip() if ':' in ct else ct.strip() + if nm: + flagged_names.append(nm) + + # ---- 1) Workday bulk approval (L2 anchor) — 0.45 ---- + # Penalty-based recall: reward actively approving the in-policy set, punish + # approving any out-of-policy (chase) task. Untouched inbox -> 0 (no free + # credit); blanket "approve all" -> heavily penalised (W04 lesson). + wd_correct = 0 # in-policy tasks correctly Completed + wd_wrong = 0 # out-of-policy tasks wrongly Completed + try: + for t in pendings: + cur = tasks_c_by_id.get(t['taskId'], {}) + completed = norm(cur.get('status')) == 'completed' + if t.get('_expected_approve') is True and completed: + wd_correct += 1 + elif t.get('_expected_approve') is False and completed: + wd_wrong += 1 + except Exception as e: + print(f'DEBUG_W06 workday component error: {e!r}') + wd_score = clamp01(frac(wd_correct - wd_wrong, n_approve)) + + # ---- 2) Asana follow-ups (recall, no penalty for extras) — 0.25 ---- + # Per chase item: title 'Follow up: ' exists (0.5) + Priority custom + # field == _expected_priority (0.5). Extra/wrong tasks never penalised. + asana_points = 0.0 + try: + asana_tasks = asana_c.get('tasks', []) or [] + for t in should_chase: + title = norm(t.get('_chase_title')) + exp_pri = norm(t.get('_expected_priority')) + if not title: + continue + hit = None + for at in asana_tasks: + if _collapse_ws(at.get('name')) == _collapse_ws(title): + hit = at + break + if hit is None: + # looser: any task whose name contains the chase title + for at in asana_tasks: + if title in _collapse_ws(at.get('name')): + hit = at + break + if hit is not None: + asana_points += 0.5 + if exp_pri and _asana_priority(hit) == exp_pri: + asana_points += 0.5 + except Exception as e: + print(f'DEBUG_W06 asana component error: {e!r}') + asana_score = frac(asana_points, n_chase) if n_chase else 1.0 + + # ---- 3) Teams 'Payroll' channel — 0.15 (two posts, strict) ---- + # Requires TWO separate posts: + # 0.075 a summary post with the EXACT approved (n_approve) and follow-up + # (n_chase) counts. + # 0.075 an exception-list post naming EVERY flagged employee (all + # n_chase names present). Partial credit = fraction of names found. + # No non-empty-message fallback (v2: strict). + teams_summary_ok = 0.0 + teams_list_frac = 0.0 + try: + msgs = _teams_channel_messages(teams_c, 'Payroll') + texts = [(_msg_text(m) or '') for m in msgs if (_msg_text(m) or '').strip()] + for txt in texts: + if _counts_match(txt, n_approve, n_chase): + teams_summary_ok = 1.0 + break + # exception-list post: the message naming the most flagged employees + if flagged_names: + best = max((_names_present(txt, flagged_names) for txt in texts), default=0) + teams_list_frac = frac(best, len(flagged_names)) + else: + teams_list_frac = 1.0 + except Exception as e: + print(f'DEBUG_W06 teams component error: {e!r}') + teams_ok = 0.5 * teams_summary_ok + 0.5 * teams_list_frac + + # ---- 4) Gmail — 0.15 (two emails, strict) ---- + # Requires TWO sent emails: + # 0.075 summary to Sandra Voss (sandra.voss@acmecorp.com) whose body + # carries the EXACT approved + follow-up counts. + # 0.075 exception handoff to Tom Reed (tom.reed@acmecorp.com) naming + # EVERY flagged employee (partial = fraction of names found). + # No "any sent email" fallback (v2: strict). + SANDRA = 'sandra.voss@acmecorp.com' + TOM = 'tom.reed@acmecorp.com' + gmail_summary_ok = 0.0 + gmail_handoff_frac = 0.0 + try: + emails = gmail_c.get('emails', []) or [] + sent = [e for e in emails if norm(e.get('folder')) == 'sent'] + + def _recips(e): + out = [] + for fld in ('to', 'cc', 'bcc'): + v = e.get(fld) + if isinstance(v, list): + for r in v: + if isinstance(r, dict): + out.append(norm(r.get('email'))) + else: + out.append(norm(r)) + elif v: + out.append(norm(v)) + return out + + def _blob(e): + return (norm(e.get('subject')) + ' ' + norm(e.get('snippet')) + ' ' + + norm(e.get('body'))) + + for e in sent: + if SANDRA in _recips(e): + if _counts_match(_blob(e), n_approve, n_chase): + gmail_summary_ok = 1.0 + break + if flagged_names: + best = 0 + for e in sent: + if TOM in _recips(e): + best = max(best, _names_present(_blob(e), flagged_names)) + gmail_handoff_frac = frac(best, len(flagged_names)) + else: + gmail_handoff_frac = 1.0 + except Exception as e: + print(f'DEBUG_W06 gmail component error: {e!r}') + gmail_ok = 0.5 * gmail_summary_ok + 0.5 * gmail_handoff_frac + + # ---- Combine ---- + s_wd = 0.45 * wd_score + s_asana = 0.25 * asana_score + s_teams = 0.15 * teams_ok + s_gmail = 0.15 * gmail_ok + score = s_wd + s_asana + s_teams + s_gmail + + print( + 'DEBUG_W06 ' + f'n_pending={n} n_approve={n_approve} n_chase={n_chase} ' + f'wd_correct={wd_correct}/{n_approve} wd_wrong={wd_wrong} wd_score={round(wd_score, 4)} ' + f'asana_points={round(asana_points, 4)}/{n_chase} asana_score={round(asana_score, 4)} ' + f'teams_summary={teams_summary_ok} teams_list={round(teams_list_frac, 3)} teams_ok={round(teams_ok, 3)} ' + f'gmail_summary={gmail_summary_ok} gmail_handoff={round(gmail_handoff_frac, 3)} gmail_ok={round(gmail_ok, 3)} ' + f'w_wd={round(s_wd, 4)} w_asana={round(s_asana, 4)} ' + f'w_teams={round(s_teams, 4)} w_gmail={round(s_gmail, 4)} ' + f'total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/hr_policy_ack_002/_cua_gym_vm_bridge.sh b/hr_policy_ack_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/hr_policy_ack_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/hr_policy_ack_002/initial_setup.py b/hr_policy_ack_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8a524183392c80dd7b6c0e154cd012363a4213f8 --- /dev/null +++ b/hr_policy_ack_002/initial_setup.py @@ -0,0 +1,369 @@ +""" +Initial Setup: Carlos Mendez completed signing the Remote Work Policy in DocuSign +Task ID: hr_policy_ack_002 +Domain: mock_websites +Mocks: docusign_mock, workday_mock, slack_mock +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +TASK_ID = "hr_policy_ack_002" + +# Generate and persist sid for golden_patch.py and reward.py +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + +print(f"Session ID generated: {sid}") + +# Mock URLs (using public URLs from skill documentation) +MOCKS = { + "docusign_mock": "http://28.7.184.198:8130", + "workday_mock": "http://28.7.184.198:8192", + "slack_mock": "http://28.7.184.198:8178" +} + +# --- Build DocuSign initial state --- +# Carlos Mendez's Remote Work Policy envelope is in "Completed" state (signed) +docusign_state = { + "user": { + "id": "user_hr_admin", + "name": "HR Administrator", + "email": "hr.admin@company.com", + "title": "HR Administrator", + "company": "TechCorp Inc", + "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 30, "timezone": "America/New_York"} + }, + "envelopes": [ + { + "id": "env_remote_work_policy_carlos", + "subject": "Remote Work Policy 2026", + "message": "Please review and sign the updated Remote Work Policy for 2026.", + "status": "completed", # Already signed/completed as per task context + "createdAt": "2026-06-20T10:00:00Z", + "sentAt": "2026-06-20T10:15:00Z", + "completedAt": "2026-06-24T09:30:00Z", # Recently completed + "voidedAt": None, + "declinedAt": None, + "lastActivityAt": "2026-06-24T09:30:00Z", + "expiresAt": None, + "senderId": "user_hr_admin", + "folderId": None, + "templateId": None, + "reminderEnabled": False, + "reminderDays": 3, + "reminderFrequency": 2, + "documents": [ + { + "id": "doc_remote_policy", + "name": "Remote Work Policy 2026.pdf", + "pageCount": 8, + "order": 1, + "fileUrl": "https://picsum.photos/seed/remote_policy/800/1100", + "fileType": "pdf" + } + ], + "recipients": [ + { + "id": "rec_carlos_mendez", + "name": "Carlos Mendez", + "email": "carlos.mendez@company.com", + "role": "signer", + "routingOrder": 1, + "status": "signed", # Signed status + "signedAt": "2026-06-24T09:30:00Z", + "viewedAt": "2026-06-24T09:25:00Z", + "deliveredAt": "2026-06-20T10:20:00Z", + "declinedAt": None, + "declineReason": None + } + ], + "fields": [], + "history": [ + { + "id": "evt_created", + "timestamp": "2026-06-20T10:00:00Z", + "action": "created", + "actorName": "HR Administrator", + "actorEmail": "hr.admin@company.com", + "details": "Envelope created" + }, + { + "id": "evt_sent", + "timestamp": "2026-06-20T10:15:00Z", + "action": "sent", + "actorName": "HR Administrator", + "actorEmail": "hr.admin@company.com", + "details": "Envelope sent to Carlos Mendez" + }, + { + "id": "evt_completed", + "timestamp": "2026-06-24T09:30:00Z", + "action": "completed", + "actorName": "Carlos Mendez", + "actorEmail": "carlos.mendez@company.com", + "details": "Envelope completed and signed" + } + ] + } + ], + "templates": [], + "folders": [], + "contacts": [], + "auditLog": [] +} + +# --- Build Workday initial state --- +# Carlos's onboarding checklist has "Policy Acknowledgement" item marked "Not Started" +workday_state = { + "currentUser": { + "id": "emp_hr_admin", + "name": "HR Administrator", + "email": "hr.admin@company.com", + "phone": "+1 (555) 123-4567", + "role": "Manager", + "department": "Human Resources", + "departmentId": "dept_hr", + "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128", + "managerId": None, + "title": "HR Administrator", + "location": "New York, NY", + "joinDate": "2022-01-15", + "employeeType": "Full-Time", + "skills": ["HR Management", "Employee Relations", "Compliance"], + "birthday": "1985-03-20", + "workAnniversary": "2022-01-15" + }, + "employees": [ + { + "id": "emp_hr_admin", + "name": "HR Administrator", + "email": "hr.admin@company.com", + "role": "Manager", + "department": "Human Resources", + "departmentId": "dept_hr", + "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128", + "managerId": None, + "title": "HR Administrator", + "location": "New York, NY", + "joinDate": "2022-01-15", + "employeeType": "Full-Time", + "birthday": "1985-03-20", + "workAnniversary": "2022-01-15" + }, + { + "id": "emp_carlos_mendez", + "name": "Carlos Mendez", + "email": "carlos.mendez@company.com", + "role": "Employee", + "department": "Engineering", + "departmentId": "dept_eng", + "avatar": "https://ui-avatars.com/api/?name=Carlos+Mendez&background=7C3AED&color=fff&size=128", + "managerId": "emp_eng_manager", + "title": "Software Engineer", + "location": "San Francisco, CA", + "joinDate": "2026-06-01", + "employeeType": "Full-Time", + "birthday": "1992-08-15", + "workAnniversary": "2026-06-01" + }, + { + "id": "emp_eng_manager", + "name": "Sarah Chen", + "email": "sarah.chen@company.com", + "role": "Manager", + "department": "Engineering", + "departmentId": "dept_eng", + "avatar": "https://ui-avatars.com/api/?name=Sarah+Chen&background=DC2626&color=fff&size=128", + "managerId": None, + "title": "Engineering Manager", + "location": "San Francisco, CA", + "joinDate": "2020-03-10", + "employeeType": "Full-Time", + "birthday": "1988-11-30", + "workAnniversary": "2020-03-10" + } + ], + "departments": [ + {"id": "dept_hr", "name": "Human Resources", "headcount": 1, "managerId": "emp_hr_admin"}, + {"id": "dept_eng", "name": "Engineering", "headcount": 2, "managerId": "emp_eng_manager"} + ], + "timeEntries": [], + "timeOffRequests": [], + "timeOffBalance": {"vacation": 120, "sick": 40, "personal": 16}, + "payroll": [], + "benefits": { + "employeeId": "emp_hr_admin", + "enrollmentStatus": "Complete", + "plans": [], + "dependents": [] + }, + "reviews": [], + "goals": [], + "tasks": [ + { + "taskId": "task_policy_ack", + "employeeId": "emp_hr_admin", + "type": "To-Do", + "subType": "Onboarding", + "description": "Policy Acknowledgement for Carlos Mendez", + "status": "Pending", # Not Started - will be marked Completed during the task + "dueDate": "2026-06-30", + "createdDate": "2026-06-20", + "relatedId": "emp_carlos_mendez", + "initiator": "System", + "businessProcess": "Employee Onboarding", + "priority": "Normal", + "comments": [] + } + ], + "announcements": [], + "notifications": [], + "clockStatus": {"isClockedIn": False, "startTime": None} +} + +# --- Build Slack initial state --- +# #hr-ops channel has existing message announcing policy was sent to Carlos for signing +slack_state = { + "currentUser": { + "userId": "user_hr_admin", + "fullName": "HR Administrator", + "displayName": "HR Admin", + "email": "hr.admin@company.com", + "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128", + "status": "online", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York" + }, + "workspace": {"workspaceId": "ws_techcorp", "workspaceName": "TechCorp", "icon": ""}, + "users": [ + { + "userId": "user_hr_admin", + "fullName": "HR Administrator", + "displayName": "HR Admin", + "email": "hr.admin@company.com", + "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128", + "status": "online" + }, + { + "userId": "user_sarah_chen", + "fullName": "Sarah Chen", + "displayName": "Sarah", + "email": "sarah.chen@company.com", + "avatar": "https://ui-avatars.com/api/?name=Sarah+Chen&background=DC2626&color=fff&size=128", + "status": "online" + } + ], + "channels": [ + { + "channelId": "hr-ops", + "name": "hr-ops", + "description": "HR Operations and Announcements", + "topic": "Employee onboarding and policy management", + "isPrivate": False, + "isStarred": False, + "members": ["user_hr_admin", "user_sarah_chen"], + "createdBy": "user_hr_admin", + "createdAt": "2024-01-01T10:00:00Z", + "pinnedMessages": [], + "unreadCount": 0 + } + ], + "messages": { + "hr-ops": [ + { + "messageId": "msg_policy_sent", + "senderId": "user_hr_admin", + "content": "Sent Remote Work Policy 2026 to Carlos Mendez (carlos.mendez@company.com) for signature via DocuSign.", + "timestamp": "2026-06-20T10:30:00Z", + "threadId": None, # This will be the parent message for the threaded reply + "reactions": [], + "attachments": [], + "isEdited": False + } + ] + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": { + "theme": "light", + "notifications": "all", + "displayDensity": "comfortable", + "showAvatars": True, + "use24Hour": False + }, + "invitations": [], + "notifications": [] +} + +# --- Inject state into all mocks --- +print("Injecting initial state into all mocks...") + +for mock_name, base_url in MOCKS.items(): + print(f" Injecting into {mock_name} at {base_url}") + + if mock_name == "docusign_mock": + state = docusign_state + elif mock_name == "workday_mock": + state = workday_state + elif mock_name == "slack_mock": + state = slack_state + + try: + resp = requests.post( + f'{base_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30 + ) + assert resp.status_code == 200, f'State injection failed for {mock_name}: {resp.text}' + print(f" ✓ State injected successfully") + + # Verify state was set + go = requests.get(f'{base_url}/go?sid={sid}', timeout=10).json() + assert go['initial_state'] is not None, f'initial_state is None after injection for {mock_name}' + print(f" ✓ State verified") + + except Exception as e: + print(f" ✗ Error injecting state into {mock_name}: {e}") + raise + +print("All states injected successfully!") + +# --- Launch browser with primary mock (DocuSign as per task_config) --- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + +# Launch browser with DocuSign (primary mock) +primary_url = f"{MOCKS['docusign_mock']}/?sid={sid}" +launch_gui(f'google-chrome "{primary_url}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {primary_url}') + +# Also launch Workday and Slack in separate tabs after a delay +time.sleep(1.0) +workday_url = f"{MOCKS['workday_mock']}/?sid={sid}" +launch_gui(f'google-chrome "{workday_url}"', delay_sec=0.5) + +time.sleep(0.5) +slack_url = f"{MOCKS['slack_mock']}/?sid={sid}" +launch_gui(f'google-chrome "{slack_url}"', delay_sec=0.5) + +print("All browsers launched successfully!") \ No newline at end of file diff --git a/hr_policy_ack_002/reward.py b/hr_policy_ack_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..08bdee0404d1d25d3b941e1ffbe90604d529ab5b --- /dev/null +++ b/hr_policy_ack_002/reward.py @@ -0,0 +1,134 @@ +""" +Reward Script: Carlos Mendez Remote Work Policy Acknowledgement +Task ID: hr_policy_ack_002 +Domain: mock_websites +Mocks: docusign_mock, workday_mock, slack_mock +Scoring: + - DocuSign envelope completed (0.3 pts) + - Workday checklist item completed (0.4 pts) + - Slack threaded reply confirming completion (0.3 pts) +""" + +import json +import sys +import requests + +# Mock URLs based on the schema documentation +MOCKS = { + 'docusign_mock': 'http://28.7.184.198:8130', + 'workday_mock': 'http://28.7.184.198:8192', + 'slack_mock': 'http://28.7.184.198:8178' +} + +def verify_task(): + total_score = 0.0 + + # Read session ID + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') + except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + return 0.0 + + # Fetch state from all mocks + states = {} + for name, url in MOCKS.items(): + try: + resp = requests.get(f'{url}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + states[name] = data + except Exception as e: + print(f'ERROR: Cannot fetch state from {name}: {e}') + print('REWARD: 0.0') + return 0.0 + + # Component 1: DocuSign envelope status is 'completed' (0.3 points) + try: + docusign_current = states['docusign_mock'].get('current_state', {}) + envelopes = docusign_current.get('envelopes', []) + + # Find Carlos Mendez's Remote Work Policy envelope + carlos_envelope_found = False + for envelope in envelopes: + # Check if this is the Remote Work Policy for Carlos Mendez + recipients = envelope.get('recipients', []) + carlos_recipient = None + for recipient in recipients: + if recipient.get('email') == 'carlos.mendez@company.com': + carlos_recipient = recipient + break + + if carlos_recipient and envelope.get('subject', '').lower().find('remote work policy') != -1: + carlos_envelope_found = True + if envelope.get('status') == 'completed' and carlos_recipient.get('status') == 'signed': + print(f'PASS: DocuSign envelope for Carlos Mendez is completed (0.3 pts)') + total_score += 0.3 + else: + print(f'FAIL: DocuSign envelope status: {envelope.get("status")}, recipient status: {carlos_recipient.get("status")}') + break + + if not carlos_envelope_found: + print('FAIL: Could not find Carlos Mendez Remote Work Policy envelope in DocuSign') + except Exception as e: + print(f'ERROR: Component 1 — {e}') + + # Component 2: Workday onboarding checklist item marked 'Completed' (0.4 points) + try: + workday_current = states['workday_mock'].get('current_state', {}) + tasks = workday_current.get('tasks', []) + + # Find the Policy Acknowledgement task for Carlos Mendez + policy_task_found = False + for task in tasks: + if (task.get('description', '').lower().find('policy acknowledgement') != -1 and + task.get('subType', '').lower().find('onboarding') != -1): + policy_task_found = True + if task.get('status') == 'Completed': + print(f'PASS: Workday Policy Acknowledgement task is completed (0.4 pts)') + total_score += 0.4 + else: + print(f'FAIL: Workday task status: {task.get("status")}') + break + + if not policy_task_found: + print('FAIL: Could not find Policy Acknowledgement onboarding task in Workday') + except Exception as e: + print(f'ERROR: Component 2 — {e}') + + # Component 3: Slack threaded reply confirms policy signed and recorded (0.3 points) + try: + slack_current = states['slack_mock'].get('current_state', {}) + messages = slack_current.get('messages', {}) + hr_ops_messages = messages.get('hr-ops', []) + + # Check for threaded replies that mention policy completion + policy_reply_found = False + for message in hr_ops_messages: + thread_id = message.get('threadId') + if thread_id: + # This is a threaded reply, check content + content = message.get('content', '').lower() + if ('signed' in content and 'recorded' in content and + ('policy' in content or 'remote work' in content)): + policy_reply_found = True + print(f'PASS: Slack threaded reply confirms policy signed and recorded (0.3 pts)') + total_score += 0.3 + break + + if not policy_reply_found: + print('FAIL: No threaded reply confirming policy signed and recorded found in Slack #hr-ops') + except Exception as e: + print(f'ERROR: Component 3 — {e}') + + final_score = min(total_score, 1.0) + print(f'\nScore: {total_score}/1.0') + print(f'REWARD: {final_score}') + return final_score + +if __name__ == '__main__': + verify_task() \ No newline at end of file diff --git a/hr_policy_ack_002/reward_label.json b/hr_policy_ack_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..dcac7688c85aad2abd0582e4cfe2c2424637b3a7 --- /dev/null +++ b/hr_policy_ack_002/reward_label.json @@ -0,0 +1,57 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/hr_policy_ack_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:27:05", + "label": { + "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 + }, + "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。 {\"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}" +} diff --git a/itops_access_log_003/_cua_gym_vm_bridge.sh b/itops_access_log_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/itops_access_log_003/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/itops_access_log_003/initial_setup.py b/itops_access_log_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2e40bb09350ffc6b40aacdfd5c9304cef1a35bc6 --- /dev/null +++ b/itops_access_log_003/initial_setup.py @@ -0,0 +1,238 @@ +""" +Initial Setup: Access-Request-To-Log pipeline (Slack -> Google Sheets) +Task ID: itops_access_log_003 +Domain: mock_websites +Mocks: slack_mock (http://28.7.184.198:8178), google_sheets_mock (http://28.7.184.198:8145) +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config (task-config URLs) --- +SLACK_URL = 'http://28.7.184.198:8178' +SHEETS_URL = 'http://28.7.184.198:8145' + +# Use a deterministic sid derived from task_id so initial_env, golden_env, and +# reward.py all agree on the same session. The mock apps are remote HTTP servers +# (state keyed by sid), so a stable sid lets golden_patch.py (running on a separate +# VM with its own filesystem) locate the shared state without a local file dependency. +# We still persist it to /tmp/task_web_sid for reward.py's convenience. +sid = 'prof34_access_log_001' +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + +# --------------------------------------------------------------------------- +# Slack initial state +# --------------------------------------------------------------------------- +slack_state = { + "currentUser": { + "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" + }, + "workspace": {"workspaceId": "ws_nw", "workspaceName": "Northwind Corp", "icon": ""}, + "users": [ + {"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"}, + {"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"}, + {"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"} + ], + "channels": [ + {"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} + ], + "messages": { + "it-access-requests": [ + {"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} + ] + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [] +} + +# --------------------------------------------------------------------------- +# Google Sheets initial state +# --------------------------------------------------------------------------- +def header_cell(value): + return {"value": value, "formula": value, "style": {"bold": True, "bg": "#E8EAED"}} + +def data_cell(value): + return {"value": value, "formula": value} + +access_log_data = { + "A1": header_cell("Request ID"), + "B1": header_cell("Date"), + "C1": header_cell("Requester"), + "D1": header_cell("Email"), + "E1": header_cell("App"), + "F1": header_cell("Access Level"), + "G1": header_cell("Manager"), + "H1": header_cell("Approval"), + "I1": header_cell("Status"), + "A2": data_cell("ACC-2026-0628-001"), + "B2": data_cell("2026-06-28"), + "C2": data_cell("Liam Wong"), + "D2": data_cell("liam.wong@northwind.io"), + "E2": data_cell("Asana"), + "F2": data_cell("Read-only"), + "G2": data_cell("Sara Kim"), + "H2": data_cell("Approved"), + "I2": data_cell("Provisioned"), + "A3": data_cell("ACC-2026-0629-002"), + "B3": data_cell("2026-06-29"), + "C3": data_cell("Nina Patel"), + "D3": data_cell("nina.patel@northwind.io"), + "E3": data_cell("Google Sheets"), + "F3": data_cell("Edit"), + "G3": data_cell("Daniel Okafor"), + "H3": data_cell("Approved"), + "I3": data_cell("Provisioned"), + "A4": data_cell("ACC-2026-0630-003"), + "B4": data_cell("2026-06-30"), + "C4": data_cell("Omar Said"), + "D4": data_cell("omar.said@northwind.io"), + "E4": data_cell("GitHub"), + "F4": data_cell("Read-only"), + "G4": data_cell("Sara Kim"), + "H4": data_cell("Pending"), + "I4": data_cell("Awaiting"), +} + +sheets_state = { + "id": "wb_acc_01", + "title": "Access Audit Log", + "activeSheetId": "sh_acc_01", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [ + { + "id": "sh_acc_01", + "name": "Access Log", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": None, + "isHidden": False, + "columnWidths": {}, + "rowHeights": {}, + "filterRange": None, + "filterCriteria": {}, + "sortColumn": None, + "sortDirection": None, + "data": access_log_data + } + ] +} + +# --------------------------------------------------------------------------- +# Inject state into BOTH mocks with the same sid +# --------------------------------------------------------------------------- +resp = requests.post(f'{SLACK_URL}/post?sid={sid}', json={'action': 'set', 'state': slack_state}, timeout=30) +assert resp.status_code == 200, f'Slack state injection failed: {resp.text}' +print('Slack initial state injected') + +resp = requests.post(f'{SHEETS_URL}/post?sid={sid}', json={'action': 'set', 'state': sheets_state}, timeout=30) +assert resp.status_code == 200, f'Sheets state injection failed: {resp.text}' +print('Google Sheets initial state injected') + +# Verify +go_slack = requests.get(f'{SLACK_URL}/go?sid={sid}', timeout=10).json() +go_sheets = requests.get(f'{SHEETS_URL}/go?sid={sid}', timeout=10).json() +assert go_slack['initial_state'] is not None, 'Slack initial_state is None' +assert go_sheets['initial_state'] is not None, 'Sheets initial_state is None' +print('Verified: both mocks have initial_state + current_state set') + +# --------------------------------------------------------------------------- +# Launch a Chrome window for EACH mock +# --------------------------------------------------------------------------- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.0) +launch_gui(f'google-chrome "{SHEETS_URL}/?sid={sid}"', delay_sec=1.0) + +# --------------------------------------------------------------------------- +# Wait until both mocks serve injected state AND fully render +# --------------------------------------------------------------------------- +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + raise RuntimeError(f'Mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 5s') + _t.sleep(5.0) + return + with sync_playwright() as p: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', + timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 100", + timeout=int(render_timeout * 1000)) + html = page.content() + if len(html) < 2000: + raise RuntimeError( + f'[{name}] rendered DOM too small ({len(html)} bytes) — blank/stuck loading') + print(f'[{name}] rendered OK ({len(html)} bytes)') + finally: + page.close() + finally: + browser.close() + +mocks = {'slack_mock': SLACK_URL, 'google_sheets_mock': SHEETS_URL} +wait_for_mocks_loaded(mocks, sid) +print(f'GUI_READY: all {len(mocks)} mocks launched and verified (sid={sid})') diff --git a/itops_access_log_003/reward.py b/itops_access_log_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..35e7d64800a4f52a7b180d591c557377feff4007 --- /dev/null +++ b/itops_access_log_003/reward.py @@ -0,0 +1,182 @@ +""" +Reward Script: Add a new access-log row to the Google Sheets 'Access Log' sheet +Task ID: itops_access_log_003 +Domain: mock_websites +Mocks: slack_mock (read request), google_sheets_mock (write row) +Scoring: + Component 1 (0.6): Row 5 in 'Access Log' sheet contains the exact 9 required + values A5='ACC-2026-0701-001' ... I5='Logged'. + Component 2 (0.4): Rows 2-4 (existing records) are byte-for-byte unchanged AND + no duplicate of Request ID 'ACC-2026-0701-001' exists. + reward(initial_env) == 0.0 (row 5 empty -> both components fail) + reward(golden_env) == 1.0 (row 5 filled correctly, rows 2-4 intact) +""" +import json +import sys + +import requests + +# --- Read sid from the VM (written by initial_setup.py) --- +try: + with open('/tmp/task_web_sid') as f: + SID = f.read().strip() + if not SID: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +# --- Google Sheets mock base URL (from task_config.json) --- +BASE_URL = 'http://28.7.184.198:8145' + +# --- Fetch current state (the agent / golden_patch result) --- +try: + resp = requests.get(f'{BASE_URL}/go?sid={SID}', timeout=15) + resp.raise_for_status() + data = resp.json() +except Exception as e: + print(f'CRITICAL: Cannot fetch state from {BASE_URL}/go?sid={SID}: {e}') + print('REWARD: 0.0') + sys.exit(0) + +CURRENT = data.get('current_state') or {} +if not CURRENT: + print('CRITICAL: current_state is empty/None') + print('REWARD: 0.0') + sys.exit(0) + + +# --- Expected ground-truth values (from task_config.json context) --- +EXPECTED_ROW5 = { + 'A5': 'ACC-2026-0701-001', + 'B5': '2026-07-01', + 'C5': 'Maya Chen', + 'D5': 'maya.chen@northwind.io', + 'E5': 'Salesforce', + 'F5': 'Read-only', + 'G5': 'Daniel Okafor', + 'H5': 'Approved', + 'I5': 'Logged', +} +# Baseline records that must remain unchanged (rows 2-4). +BASELINE_ROWS = { + 'A2': 'ACC-2026-0628-001', 'B2': '2026-06-28', 'C2': 'Liam Wong', + 'D2': 'liam.wong@northwind.io', 'E2': 'Asana', 'F2': 'Read-only', + 'G2': 'Sara Kim', 'H2': 'Approved', 'I2': 'Provisioned', + 'A3': 'ACC-2026-0629-002', 'B3': '2026-06-29', 'C3': 'Nina Patel', + 'D3': 'nina.patel@northwind.io', 'E3': 'Google Sheets', 'F3': 'Edit', + 'G3': 'Daniel Okafor', 'H3': 'Approved', 'I3': 'Provisioned', + 'A4': 'ACC-2026-0630-003', 'B4': '2026-06-30', 'C4': 'Omar Said', + 'D4': 'omar.said@northwind.io', 'E4': 'GitHub', 'F4': 'Read-only', + 'G4': 'Sara Kim', 'H4': 'Pending', 'I4': 'Awaiting', +} + + +def _get_sheet(current, sheet_name='Access Log'): + """Return the target sheet dict, or None if not found.""" + for s in current.get('sheets', []): + if s.get('name') == sheet_name or s.get('id') == 'sh_acc_01': + return s + return None + + +def _cell_value(sheet, cell_id): + """Return the value of a cell, or None if missing.""" + cell = sheet.get('data', {}).get(cell_id) + if cell is None: + return None + return cell.get('value') + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# --- Per-component checks --- + +def check_component_1(current): + """Row 5 has exactly the 9 required values A5..I5. + Pass condition: every cell in EXPECTED_ROW5 matches current_state exactly.""" + sheet = _get_sheet(current) + if sheet is None: + return False, 0.0, "sheet 'Access Log' not found in current_state" + mismatches = [] + for cell_id, expected in EXPECTED_ROW5.items(): + actual = _cell_value(sheet, cell_id) + if actual != expected: + mismatches.append(f'{cell_id}: expected {expected!r}, got {actual!r}') + if mismatches: + return False, 0.0, '; '.join(mismatches) + return True, 0.6, 'Row 5 matches all 9 required values exactly' + + +def check_component_2(current): + """Rows 2-4 unchanged AND no duplicate Request ID. + Pass condition: all 27 baseline cells unchanged AND Request ID + ACC-2026-0701-001 appears exactly once in column A (at A5).""" + sheet = _get_sheet(current) + if sheet is None: + return False, 0.0, "sheet 'Access Log' not found in current_state" + + # 1) baseline rows 2-4 must be intact + changed = [] + for cell_id, expected in BASELINE_ROWS.items(): + actual = _cell_value(sheet, cell_id) + if actual != expected: + changed.append(f'{cell_id}: expected {expected!r}, got {actual!r}') + if changed: + return False, 0.0, 'baseline rows 2-4 changed: ' + '; '.join(changed) + + # 2) no duplicate Request ID 'ACC-2026-0701-001' + req_id = EXPECTED_ROW5['A5'] + occurrences = 0 + for cell_id, cell in sheet.get('data', {}).items(): + col = ''.join(ch for ch in cell_id if ch.isalpha()) + if col == 'A': + if cell.get('value') == req_id: + occurrences += 1 + if occurrences != 1: + return False, 0.0, f"Request ID {req_id!r} appears {occurrences} time(s), expected exactly 1" + + return True, 0.4, 'Rows 2-4 intact and no duplicate Request ID' + + +def verify_task(): + """Verify task completion with progressive scoring. Returns float 0.0-1.0.""" + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'Row 5 populated with exact required values', 0.6, + check_component_1, (CURRENT,)), + (2, 'Rows 2-4 unchanged and no duplicate Request ID', 0.4, + check_component_2, (CURRENT,)), + ]: + _, score, _ = _run_component(idx, name, weight, fn, args) + total_score += score + + final_score = round(min(total_score, 1.0), 4) + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +verify_task() diff --git a/itops_access_log_003/reward_label.json b/itops_access_log_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..f87dd5a841087e6e42990c0dffaeccd709bf62bd --- /dev/null +++ b/itops_access_log_003/reward_label.json @@ -0,0 +1,47 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof34_access_log_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:31:11", + "label": { + "task_id": "itops_access_log_003", + "domain": "mock_websites", + "summary": "验证代理是否在 Google Sheets 的 'Access Log' 工作表第 5 行正确添加了包含 9 个精确字段的新访问日志记录,同时保持第 2-4 行现有记录完全不变且未产生重复 Request ID。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_sheets_mock (http://28.7.186.212:8165)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.6, + "description": "检查 'Access Log' 工作表第 5 行的 9 个单元格是否精确匹配预期值", + "check_logic": "通过 _get_sheet 获取工作表后,遍历 EXPECTED_ROW5 中的 9 个单元格(A5..I5),使用 _cell_value 逐一比对实际值与预期值;若全部相等则通过,否则返回失败并列出所有不匹配的单元格。", + "pass_condition": "A5='ACC-2026-0701-001'、B5='2026-07-01'、C5='Maya Chen'、D5='maya.chen@northwind.io'、E5='Salesforce'、F5='Read-only'、G5='Daniel Okafor'、H5='Approved'、I5='Logged' 全部精确匹配" + }, + { + "name": "Component 2", + "weight": 0.4, + "description": "检查第 2-4 行基线记录未被修改,且 Request ID 在 A 列恰好出现一次", + "check_logic": "先比对 BASELINE_ROWS 中 27 个单元格(A2..I4)是否全部保持原值;再遍历工作表 data 中所有单元格,筛选列名为 'A' 的单元格,统计其值等于 'ACC-2026-0701-001' 的出现次数,要求恰好为 1。", + "pass_condition": "Rows 2-4 的 27 个基线单元格全部未改动,且 A 列中 Request ID 'ACC-2026-0701-001' 恰好出现 1 次(无重复)" + } + ], + "total_max_score": 1.0, + "score_aggregation": "两组件得分直接相加得到 total_score,再用 min(total_score, 1.0) 钳制到上限 1.0,最后 round(..., 4) 四舍五入到 4 位小数作为最终 REWARD。", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并 REWARD: 0.0 后 sys.exit(0)", + "向 google_sheets_mock 发送 GET 请求失败或超时:打印 CRITICAL 并 REWARD: 0.0 后 sys.exit(0)", + "返回的 current_state 为空/None:打印 CRITICAL 并 REWARD: 0.0 后 sys.exit(0)", + "未找到 'Access Log' 工作表:对应组件得 0 分", + "Component 1 中 A5-I5 任一单元格与预期不符:该组件得 0 分", + "Component 2 中基线行 A2-I4 任一单元格被修改:该组件得 0 分", + "Component 2 中 A 列 Request ID 出现次数不等于 1(重复或缺失):该组件得 0 分" + ], + "scoring_logic_explanation": "脚本首先按顺序执行:1) 从 /tmp/task_web_sid 读取会话 ID;2) 向 google_sheets_mock (BASE_URL/go?sid={SID}) 发送 GET 请求获取当前状态 JSON;3) 提取 current_state。若任何一步失败或状态为空,立即输出 0.0 并退出。随后 verify_task() 顺序运行两个组件:Component 1 检查 'Access Log' 工作表第 5 行 A5-I5 的 9 个单元格是否完全等于 EXPECTED_ROW5 中的预定值,通过得 0.6 分;Component 2 先检查第 2-4 行共 27 个基线单元格是否与 BASELINE_ROWS 完全一致,再遍历 A 列统计 Request ID 'ACC-2026-0701-001' 出现次数是否恰好为 1,两项均满足得 0.4 分。两个组件的得分相加后,用 min(..., 1.0) 钳制上限,并四舍五入到小数点后 4 位作为最终分数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. 任务 ID: prof34_access_log_001 (从 docstring 中提取)\n2. Domain: mock_websites (从 docstring 中提取)\n3. 数据源: \n - /tmp/task_web_sid (读取 sid)\n - http://28.7.186.212:8165/go?sid={SID} (google_sheets_mock,虽然 docstring 说 Mocks 包含 slack_mock 和 google_sheets_mock,但代码中实际只调用了 google_sheets_mock 的接口)\n - 实际上代码中 BASE_URL 指向的是 Google Sheets mock\n\n4. 评分组件:\n - Component 1 (0.6): 检查 Row 5 (A5-I5) 是否包含预期的 9 个精确值\n - Component 2 (0.4): 检查 Rows 2-4 是否未改变(27个单元格),并且 Request ID 'ACC-2026-0701-001' 在 A 列只出现一次(无重复)\n\n5. 分数聚合: 两个组件分数相加,然后 min(total_score, 1.0),再 round 到 4 位小数\n\n6. 失败模式:\n - 读取 /tmp/task_web_sid 失败 -> 0.0\n - 从 BASE_URL 获取状态失败 -> 0.0\n - current_state 为空 -> 0.0\n - 组件检查失败会得 0 分但不会提前退出(除了上面的 critical 错误)\n\n7. is_placeholder: false,因为脚本确实做了详细检查\n\n8. confidence: 1.0,因为代码逻辑清晰完整\n\n让我构建 JSON:\n\n- task_id: \"prof34_access_log_001\"\n- domain: \"mock_websites\"\n- summary: \"验证代理是否在 Google Sheets 的 'Access Log' 工作表第 5 行正确添加了包含 9 个精确字段的新访问日志记录,且未修改第 2-4 行的现有记录、未产生重复 Request ID。\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"google_sheets_mock (http://28.7.186.212:8165)\"]\n- scoring_components:\n - Component 1: weight 0.6, 检查 A5-I5 是否精确匹配预期值\n - Component 2: weight 0.4, 检查 BASELINE_ROWS (A2-I4) 是否完全未变,且 A 列中 Request ID 只出现一次\n- total_max_score: 1.0\n- score_aggregation: 两组件得分相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\n- failure_modes: 读取 sid 失败、拉取 mock 状态失败、current_state 为空、sheet 未找到、单元格值不匹配、基线行被修改、Request ID 重复或缺失\n- scoring_logic_explanation: 详细按执行顺序说明\n- confidence: 1.0\n\n注意:docstring 中提到了 slack_mock (read request),但代码中实际上没有直接调用 slack_mock 的 API,只是通过 google_sheets_mock 读取状态。不过 data_sources 应该包含代码中实际使用的数据源。docstring 说 Mocks: slack_mock (read request), google_sheets_mock (write row),但评分脚本只读取 google_sheets_mock 的状态。我应该如实填写代码中实际使用的数据源。\n\n代码中实际使用的数据源:\n- /tmp/task_web_sid\n- http://28.7.186.212:8165 (google_sheets_mock)\n\n让我再检查一下 BASELINE_ROWS 的数量:A2-I2 是 9 个,A3-I3 是 9 个,A4-I4 是 9 个,总共 27 个。对的。\n\n检查 Component 2 的逻辑:\n1. 检查 BASELINE_ROWS 中 27 个单元格是否完全匹配\n2. 遍历 sheet.data 中所有单元格,找出 A 列(通过判断 cell_id 中的字母部分是否为 'A'),统计值为 'ACC-2026-0701-001' 的出现次数,必须恰好为 1\n\n注意:Component 2 中统计 A 列时,会包括 A5 吗?会的,因为 A5 也在 sheet.data 中。但 A5 的值就是 'ACC-2026-0701-001',所以 occurrences 至少为 1。如果其他地方还有,就会 >1。如果 A5 不是这个值(比如 Component 1 失败了),那么 occurrences 可能为 0,也会导致 Component 2 失败。这是合理的。\n\n现在组织 JSON 输出。确保:\n- 只输出 JSON 对象\n- 第一个字符是 {,最后一个字符是 }\n- 没有 Markdown 代码块\n- 没有额外解释\n- 字符串 value 使用中文,但代码标识符保留原样\n\n让我再仔细看看 scoring_logic_explanation 的要求:\"对整体评分逻辑的详细中文解释,按执行顺序说明脚本如何读取状态、逐项检查、汇总得分\"\n\n执行顺序:\n1. 从 /tmp/task_web_sid 读取会话 ID\n2. 向 google_sheets_mock (BASE_URL/go?sid={SID}) 发送 GET 请求获取 current_state\n3. 解析 JSON 得到 CURRENT\n4. 调用 verify_task()\n5. Component 1: 查找 'Access Log' 工作表,检查 A5-I5 共 9 个单元格是否精确等于 EXPECTED_ROW5,通过得 0.6 分\n6. Component 2: 查找同一工作表,检查 A2-I4 共 27 个基线单元格是否与 BASELINE_ROWS 完全一致;再遍历 A 列所有单元格,确认 Request ID 'ACC-2026-0701-001' 恰好出现 1 次。两项都满足得 0.4 分\n7. 汇总:total_score = 各组件得分之和,final_score = round(min(total_score, 1.0), 4)\n8. 任何关键步骤(读 sid、拉状态、空状态)失败直接打印 REWARD: 0.0 并 sys.exit(0)\n\nfailure_modes:\n- 读取 /tmp/task_web_sid 失败或为空:CRITICAL,输出 0.0 并退出\n- 请求 google_sheets_mock 失败:CRITICAL,输出 0.0 并退出\n- current_state 为空/None:CRITICAL,输出 0.0 并退出\n- 'Access Log' 工作表未找到:组件失败,该组件得 0 分\n- Component 1: 任意 A5-I5 单元格值不匹配预期:得 0 分\n- Component 2: 基线行 A2-I4 任一单元格被修改:得 0 分\n- Component 2: Request ID 在 A 列出现次数不为 1(重复或缺失):得 0 分\n\n注意:虽然 Component 1 和 Component 2 是顺序执行的,但 Component 2 失败不会导致提前退出,只是不得分。\n\n现在确认 JSON 格式正确,没有语法错误。 {\"task_id\":\"prof34_access_log_001\",\"domain\":\"mock_websites\",\"summary\":\"验证代理是否在 Google Sheets 的 'Access Log' 工作表第 5 行正确添加了包含 9 个精确字段的新访问日志记录,同时保持第 2-4 行现有记录完全不变且未产生重复 Request ID。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock (http://28.7.186.212:8165)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.6,\"description\":\"检查 'Access Log' 工作表第 5 行的 9 个单元格是否精确匹配预期值\",\"check_logic\":\"通过 _get_sheet 获取工作表后,遍历 EXPECTED_ROW5 中的 9 个单元格(A5..I5),使用 _cell_value 逐一比对实际值与预期值;若全部相等则通过,否则返回失败并列出所有不匹配的单元格。\",\"pass_condition\":\"A5='ACC-2026-0701-001'、B5='2026-07-01'、C5='Maya Chen'、D5='maya.chen@northwind.io'、E5='Salesforce'、F5='Read-only'、G5='Daniel Okafor'、H5='Approved'、I5='Logged' 全部精确匹配\"},{\"name\":\"Component 2\",\"weight\":0.4,\"description\":\"检查第 2-4 行基线记录未被修改,且 Request ID 在 A 列恰好出现一次\",\"check_logic\":\"先比对 BASELINE_ROWS 中 27 个单元格(A2..I4)是否全部保持原值;再遍历工作表 data 中所有单元格,筛选列名为 'A' 的单元格,统计其值等于 'ACC-2026-0701-001' 的出现次数,要求恰好为 1。\",\"pass_condition\":\"Rows 2-4 的 27 个基线单元格全部未改动,且 A 列中 Request ID 'ACC-2026-0701-001' 恰好出现 1 次(无重复)\"}],\"total_max_score\":1.0,\"score_aggregation\":\"两组件得分直接相加得到 total_score,再用 min(total_score, 1.0) 钳制到上限 1.0,最后 round(..., 4) 四舍五入到 4 位小数作为最终 REWARD。\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并 REWARD: 0.0 后 sys.exit(0)\",\"向 google_sheets_mock 发送 GET 请求失败或超时:打印 CRITICAL 并 REWARD: 0.0 后 sys.exit(0)\",\"返回的 current_state 为空/None:打印 CRITICAL 并 REWARD: 0.0 后 sys.exit(0)\",\"未找到 'Access Log' 工作表:对应组件得 0 分\",\"Component 1 中 A5-I5 任一单元格与预期不符:该组件得 0 分\",\"Component 2 中基线行 A2-I4 任一单元格被修改:该组件得 0 分\",\"Component 2 中 A 列 Request ID 出现次数不等于 1(重复或缺失):该组件得 0 分\"],\"scoring_logic_explanation\":\"脚本首先按顺序执行:1) 从 /tmp/task_web_sid 读取会话 ID;2) 向 google_sheets_mock (BASE_URL/go?sid={SID}) 发送 GET 请求获取当前状态 JSON;3) 提取 current_state。若任何一步失败或状态为空,立即输出 0.0 并退出。随后 verify_task() 顺序运行两个组件:Component 1 检查 'Access Log' 工作表第 5 行 A5-I5 的 9 个单元格是否完全等于 EXPECTED_ROW5 中的预定值,通过得 0.6 分;Component 2 先检查第 2-4 行共 27 个基线单元格是否与 BASELINE_ROWS 完全一致,再遍历 A 列统计 Request ID 'ACC-2026-0701-001' 出现次数是否恰好为 1,两项均满足得 0.4 分。两个组件的得分相加后,用 min(..., 1.0) 钳制上限,并四舍五入到小数点后 4 位作为最终分数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/_cua_gym_vm_bridge.sh b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/initial_setup.py b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b91030d5345ddac2f6033ed3240d796506a93954 --- /dev/null +++ b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/initial_setup.py @@ -0,0 +1,1611 @@ +""" +Initial Setup: se_linear_github_triage_b91 +Task ID: a91f29df-e380-5d54-b965-27aecef4d2b3 +Domain: mock_websites +Mocks: linear_mock, github_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as an engineering lead. Your tools for this task are: the Linear issue tracker, the GitHub repositories, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Linear workspace (32 issues across Engineering/Design teams); GitHub repo with 1 issue(s) and 0 PR(s); Slack workspace with channels #general, #engineering, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: ENG-15 (memory leak) moved to In Progress (+0.3); ENG-15 assigned to Sam Patel (+0.2); GitHub issue opened for the leak (+0.2); slack_new_msg (+0.1); Slack names ENG-15 exactly (+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. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "linear_mock": "http://28.7.186.212:8176", + "github_mock": "http://28.7.186.212:8156", + "slack_mock": "http://28.7.186.212:8198" +} +PRIMARY_URL = 'http://28.7.186.212:8176' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# Full initial state for every mock involved (all required top-level keys present). +STATES = { 'linear_mock': { 'currentUserId': 'u1', + 'workspace': {'id': 'w1', 'name': 'Acme Corp', 'urlKey': 'acme'}, + 'users': [ { 'id': 'u1', + 'name': 'Alex Morgan', + 'email': 'alex@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u1', + 'displayName': 'Alex', + 'role': 'Admin', + 'active': True}, + { 'id': 'u2', + 'name': 'Jamie Chen', + 'email': 'jamie@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u2', + 'displayName': 'Jamie', + 'role': 'Member', + 'active': True}, + { 'id': 'u3', + 'name': 'Sam Patel', + 'email': 'sam@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u3', + 'displayName': 'Sam', + 'role': 'Member', + 'active': True}, + { 'id': 'u4', + 'name': 'Taylor Kim', + 'email': 'taylor@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u4', + 'displayName': 'Taylor', + 'role': 'Member', + 'active': True}, + { 'id': 'u5', + 'name': 'Jordan Lee', + 'email': 'jordan@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u5', + 'displayName': 'Jordan', + 'role': 'Member', + 'active': True}, + { 'id': 'u6', + 'name': 'Riley Zhang', + 'email': 'riley@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u6', + 'displayName': 'Riley', + 'role': 'Guest', + 'active': True}], + 'teams': [ { 'id': 't1', + 'name': 'Engineering', + 'key': 'ENG', + 'icon': '⚙️', + 'color': '#5e6ad2', + 'memberIds': ['u1', 'u2', 'u3', 'u4'], + 'workflowStates': [ { 'id': 'ws_eng_triage', + 'name': 'Triage', + 'category': 'triage', + 'color': '#8a8f98', + 'position': 0, + 'teamId': 't1'}, + { 'id': 'ws_eng_backlog', + 'name': 'Backlog', + 'category': 'backlog', + 'color': '#8a8f98', + 'position': 1, + 'teamId': 't1'}, + { 'id': 'ws_eng_todo', + 'name': 'Todo', + 'category': 'unstarted', + 'color': '#e2e2e3', + 'position': 2, + 'teamId': 't1'}, + { 'id': 'ws_eng_in_progress', + 'name': 'In Progress', + 'category': 'started', + 'color': '#f2c94c', + 'position': 3, + 'teamId': 't1'}, + { 'id': 'ws_eng_in_review', + 'name': 'In Review', + 'category': 'started', + 'color': '#5e6ad2', + 'position': 4, + 'teamId': 't1'}, + { 'id': 'ws_eng_done', + 'name': 'Done', + 'category': 'completed', + 'color': '#27a644', + 'position': 5, + 'teamId': 't1'}, + { 'id': 'ws_eng_canceled', + 'name': 'Canceled', + 'category': 'canceled', + 'color': '#8a8f98', + 'position': 6, + 'teamId': 't1'}], + 'triageEnabled': True, + 'cycleEnabled': True, + 'cycleDuration': 2, + 'activeCycleId': 'c1'}, + { 'id': 't2', + 'name': 'Design', + 'key': 'DES', + 'icon': '🎨', + 'color': '#e5484d', + 'memberIds': ['u1', 'u4', 'u5'], + 'workflowStates': [ { 'id': 'ws_des_triage', + 'name': 'Triage', + 'category': 'triage', + 'color': '#8a8f98', + 'position': 0, + 'teamId': 't2'}, + { 'id': 'ws_des_backlog', + 'name': 'Backlog', + 'category': 'backlog', + 'color': '#8a8f98', + 'position': 1, + 'teamId': 't2'}, + { 'id': 'ws_des_todo', + 'name': 'Todo', + 'category': 'unstarted', + 'color': '#e2e2e3', + 'position': 2, + 'teamId': 't2'}, + { 'id': 'ws_des_in_progress', + 'name': 'In Progress', + 'category': 'started', + 'color': '#f2c94c', + 'position': 3, + 'teamId': 't2'}, + { 'id': 'ws_des_in_review', + 'name': 'In Review', + 'category': 'started', + 'color': '#5e6ad2', + 'position': 4, + 'teamId': 't2'}, + { 'id': 'ws_des_done', + 'name': 'Done', + 'category': 'completed', + 'color': '#27a644', + 'position': 5, + 'teamId': 't2'}, + { 'id': 'ws_des_canceled', + 'name': 'Canceled', + 'category': 'canceled', + 'color': '#8a8f98', + 'position': 6, + 'teamId': 't2'}], + 'triageEnabled': False, + 'cycleEnabled': True, + 'cycleDuration': 1, + 'activeCycleId': 'c4'}], + 'issues': [ { 'id': 'i1', + 'identifier': 'ENG-1', + 'number': 1, + 'title': 'Set up CI/CD pipeline for staging environment', + 'description': 'Configure GitHub Actions to deploy to ' + 'staging on merge to develop branch.\n' + '\n' + '**Acceptance Criteria:**\n' + '- Pipeline triggers on push to develop\n' + '- Runs tests before deploy\n' + '- Sends Slack notification on failure', + 'stateId': 'ws_eng_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u3', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l8'], + 'parentId': None, + 'dueDate': '2026-04-18', + 'subscriberIds': ['u1', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-28T10:00:00Z', + 'updatedAt': '2026-04-09T14:30:00Z', + 'completedAt': None, + 'sortOrder': 100}, + { 'id': 'i2', + 'identifier': 'ENG-2', + 'number': 2, + 'title': 'Fix authentication token refresh race condition', + 'description': 'There is a race condition when multiple ' + 'requests try to refresh the auth token ' + 'simultaneously, causing some requests to ' + 'fail with 401.\n' + '\n' + '**Steps to reproduce:**\n' + '1. Open multiple tabs\n' + '2. Let token expire\n' + '3. Perform simultaneous actions', + 'stateId': 'ws_eng_in_progress', + 'priority': 1, + 'estimate': 3, + 'assigneeId': 'u1', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l1', 'l7'], + 'parentId': None, + 'dueDate': '2026-04-12', + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-29T09:00:00Z', + 'updatedAt': '2026-04-10T09:00:00Z', + 'completedAt': None, + 'sortOrder': 110}, + { 'id': 'i3', + 'identifier': 'ENG-3', + 'number': 3, + 'title': 'Implement user avatar upload endpoint', + 'description': 'Add a POST /api/users/avatar endpoint ' + 'that accepts image files and stores them ' + 'in S3.', + 'stateId': 'ws_eng_todo', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u2', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l2'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-30T11:00:00Z', + 'updatedAt': '2026-04-07T10:00:00Z', + 'completedAt': None, + 'sortOrder': 120}, + { 'id': 'i4', + 'identifier': 'ENG-4', + 'number': 4, + 'title': 'Update API error response format to RFC 7807', + 'description': 'Standardize all API error responses to ' + 'use Problem Details format as defined in ' + 'RFC 7807.', + 'stateId': 'ws_eng_todo', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l3'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-31T08:00:00Z', + 'updatedAt': '2026-04-06T15:00:00Z', + 'completedAt': None, + 'sortOrder': 130}, + { 'id': 'i5', + 'identifier': 'ENG-5', + 'number': 5, + 'title': 'Add rate limiting to public API endpoints', + 'description': 'Implement rate limiting using Redis to ' + 'prevent API abuse. Limits: 100 req/min ' + 'per IP for unauthenticated, 1000 req/min ' + 'for authenticated.', + 'stateId': 'ws_eng_todo', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u3', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l7', 'l8'], + 'parentId': None, + 'dueDate': '2026-04-15', + 'subscriberIds': ['u1', 'u3'], + 'relationIds': [], + 'createdAt': '2026-04-01T09:00:00Z', + 'updatedAt': '2026-04-08T11:00:00Z', + 'completedAt': None, + 'sortOrder': 140}, + { 'id': 'i6', + 'identifier': 'ENG-6', + 'number': 6, + 'title': 'Refactor database connection pooling', + 'description': 'Current connection pool configuration is ' + 'causing connection exhaustion under load. ' + 'Need to tune pool size and implement ' + 'proper connection lifecycle management.', + 'stateId': 'ws_eng_in_review', + 'priority': 2, + 'estimate': 8, + 'assigneeId': 'u1', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l6', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-25T14:00:00Z', + 'updatedAt': '2026-04-10T08:00:00Z', + 'completedAt': None, + 'sortOrder': 150}, + { 'id': 'i7', + 'identifier': 'ENG-7', + 'number': 7, + 'title': 'Write integration tests for payment flow', + 'description': 'Create comprehensive integration tests ' + 'covering the complete payment flow from ' + 'cart to confirmation.', + 'stateId': 'ws_eng_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u2', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l5'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-04-02T10:00:00Z', + 'updatedAt': '2026-04-09T16:00:00Z', + 'completedAt': None, + 'sortOrder': 160}, + { 'id': 'i8', + 'identifier': 'ENG-8', + 'number': 8, + 'title': 'Fix mobile viewport breakpoint inconsistencies', + 'description': 'Several UI components render incorrectly ' + 'on mobile screen sizes. Fixed breakpoints ' + 'to use consistent values.', + 'stateId': 'ws_eng_done', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l1'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-03T09:00:00Z', + 'updatedAt': '2026-04-08T17:00:00Z', + 'completedAt': '2026-04-08T17:00:00Z', + 'sortOrder': 170}, + { 'id': 'i9', + 'identifier': 'ENG-9', + 'number': 9, + 'title': 'Add dark mode support to settings page', + 'description': 'Settings page is missing dark mode ' + 'styles. Should use the same color system ' + 'as the rest of the app.', + 'stateId': 'ws_eng_done', + 'priority': 4, + 'estimate': 3, + 'assigneeId': 'u1', + 'creatorId': 'u4', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l2', 'l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-04T11:00:00Z', + 'updatedAt': '2026-04-09T10:00:00Z', + 'completedAt': '2026-04-09T10:00:00Z', + 'sortOrder': 180}, + { 'id': 'i10', + 'identifier': 'ENG-10', + 'number': 10, + 'title': 'Optimize image lazy loading performance', + 'description': 'Implement Intersection Observer-based ' + 'lazy loading for all product images to ' + 'improve initial page load time.', + 'stateId': 'ws_eng_in_progress', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u3', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l6'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u2', 'u3'], + 'relationIds': [], + 'createdAt': '2026-04-05T09:00:00Z', + 'updatedAt': '2026-04-10T10:00:00Z', + 'completedAt': None, + 'sortOrder': 190}, + { 'id': 'i11', + 'identifier': 'ENG-11', + 'number': 11, + 'title': 'Implement WebSocket reconnection logic', + 'description': 'WebSocket connections drop silently when ' + 'network is interrupted. Need exponential ' + 'backoff reconnect logic.', + 'stateId': 'ws_eng_backlog', + 'priority': 2, + 'estimate': 5, + 'assigneeId': None, + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l2', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-20T10:00:00Z', + 'updatedAt': '2026-03-20T10:00:00Z', + 'completedAt': None, + 'sortOrder': 200}, + { 'id': 'i12', + 'identifier': 'ENG-12', + 'number': 12, + 'title': 'Add CSV export for analytics dashboard', + 'description': 'Users need ability to export analytics ' + 'data as CSV for external reporting.', + 'stateId': 'ws_eng_backlog', + 'priority': 4, + 'estimate': 3, + 'assigneeId': None, + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l2'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3'], + 'relationIds': [], + 'createdAt': '2026-03-22T14:00:00Z', + 'updatedAt': '2026-03-22T14:00:00Z', + 'completedAt': None, + 'sortOrder': 210}, + { 'id': 'i13', + 'identifier': 'ENG-13', + 'number': 13, + 'title': 'Migrate user preferences to new schema', + 'description': 'User preference storage needs to be ' + 'migrated from legacy JSON blob to ' + 'properly normalized schema.', + 'stateId': 'ws_eng_backlog', + 'priority': 3, + 'estimate': 5, + 'assigneeId': 'u2', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l3'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-23T09:00:00Z', + 'updatedAt': '2026-03-23T09:00:00Z', + 'completedAt': None, + 'sortOrder': 220}, + { 'id': 'i14', + 'identifier': 'ENG-14', + 'number': 14, + 'title': 'Create API documentation with OpenAPI spec', + 'description': 'Write comprehensive OpenAPI 3.0 spec for ' + 'all public API endpoints, including ' + 'request/response schemas and examples.', + 'stateId': 'ws_eng_backlog', + 'priority': 3, + 'estimate': 8, + 'assigneeId': None, + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l5'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u2'], + 'relationIds': [], + 'createdAt': '2026-03-24T11:00:00Z', + 'updatedAt': '2026-03-24T11:00:00Z', + 'completedAt': None, + 'sortOrder': 230}, + { 'id': 'i15', + 'identifier': 'ENG-15', + 'number': 15, + 'title': 'Fix memory leak in real-time notification ' + 'service', + 'description': 'Notification service has a memory leak ' + 'causing server restarts every ~48 hours. ' + 'Profiling shows event listeners are not ' + 'being cleaned up.', + 'stateId': 'ws_eng_backlog', + 'priority': 1, + 'estimate': 5, + 'assigneeId': None, + 'creatorId': 'u4', + 'teamId': 't1', + 'projectId': None, + 'cycleId': None, + 'labelIds': ['l1', 'l6'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3', 'u4'], + 'relationIds': [], + 'createdAt': '2026-03-26T15:00:00Z', + 'updatedAt': '2026-03-26T15:00:00Z', + 'completedAt': None, + 'sortOrder': 240}, + { 'id': 'i16', + 'identifier': 'ENG-16', + 'number': 16, + 'title': 'Add end-to-end encryption for file uploads', + 'description': 'Implement client-side encryption before ' + 'upload and decryption on download for ' + 'sensitive file attachments.', + 'stateId': 'ws_eng_backlog', + 'priority': 2, + 'estimate': 13, + 'assigneeId': None, + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': None, + 'cycleId': None, + 'labelIds': ['l7'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-27T09:00:00Z', + 'updatedAt': '2026-03-27T09:00:00Z', + 'completedAt': None, + 'sortOrder': 250}, + { 'id': 'i17', + 'identifier': 'ENG-17', + 'number': 17, + 'title': 'Set up error monitoring with Sentry integration', + 'description': 'Integrate Sentry for error tracking and ' + 'performance monitoring in both frontend ' + 'and backend services.', + 'stateId': 'ws_eng_backlog', + 'priority': 3, + 'estimate': 3, + 'assigneeId': None, + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3'], + 'relationIds': [], + 'createdAt': '2026-03-28T10:00:00Z', + 'updatedAt': '2026-03-28T10:00:00Z', + 'completedAt': None, + 'sortOrder': 260}, + { 'id': 'i18', + 'identifier': 'ENG-18', + 'number': 18, + 'title': 'Design new landing page layout', + 'description': 'Create the new homepage design with ' + 'improved hero section, feature ' + 'highlights, and social proof.', + 'stateId': 'ws_eng_done', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u4', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c2', + 'labelIds': ['l2', 'l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u4'], + 'relationIds': [], + 'createdAt': '2026-03-10T09:00:00Z', + 'updatedAt': '2026-03-28T16:00:00Z', + 'completedAt': '2026-03-28T16:00:00Z', + 'sortOrder': 270}, + { 'id': 'i19', + 'identifier': 'ENG-19', + 'number': 19, + 'title': 'Implement search indexing service', + 'description': 'Set up Elasticsearch to index all issue ' + 'content for full-text search ' + 'capabilities.', + 'stateId': 'ws_eng_done', + 'priority': 1, + 'estimate': 8, + 'assigneeId': 'u1', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': ['l2', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-12T10:00:00Z', + 'updatedAt': '2026-03-29T14:00:00Z', + 'completedAt': '2026-03-29T14:00:00Z', + 'sortOrder': 280}, + { 'id': 'i20', + 'identifier': 'ENG-20', + 'number': 20, + 'title': 'Fix pagination cursor bug in API', + 'description': 'Cursor-based pagination returns incorrect ' + 'results when sorting by non-unique ' + 'fields.', + 'stateId': 'ws_eng_done', + 'priority': 2, + 'estimate': 3, + 'assigneeId': 'u2', + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': ['l1'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u2', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-14T11:00:00Z', + 'updatedAt': '2026-03-27T15:00:00Z', + 'completedAt': '2026-03-27T15:00:00Z', + 'sortOrder': 290}, + { 'id': 'i21', + 'identifier': 'ENG-21', + 'number': 21, + 'title': 'Add request logging middleware', + 'description': 'Implement structured logging middleware ' + 'that captures request/response details, ' + 'timing, and error information.', + 'stateId': 'ws_eng_done', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u3', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': ['l5', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-16T09:00:00Z', + 'updatedAt': '2026-03-26T12:00:00Z', + 'completedAt': '2026-03-26T12:00:00Z', + 'sortOrder': 300}, + { 'id': 'i22', + 'identifier': 'ENG-22', + 'number': 22, + 'title': 'Remove deprecated v1 API routes', + 'description': 'Clean up legacy v1 API routes that are no ' + 'longer used. Migration guide has been ' + 'published.', + 'stateId': 'ws_eng_canceled', + 'priority': 4, + 'estimate': None, + 'assigneeId': 'u1', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': [], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-18T10:00:00Z', + 'updatedAt': '2026-03-25T09:00:00Z', + 'completedAt': '2026-03-25T09:00:00Z', + 'sortOrder': 310}, + { 'id': 'i23', + 'identifier': 'DES-1', + 'number': 1, + 'title': 'Design onboarding flow mockups', + 'description': 'Create high-fidelity mockups for the new ' + 'user onboarding experience, covering ' + 'account setup, team invitation, and first ' + 'issue creation.', + 'stateId': 'ws_des_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u5', + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u4', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-07T09:00:00Z', + 'updatedAt': '2026-04-10T11:00:00Z', + 'completedAt': None, + 'sortOrder': 100}, + { 'id': 'i24', + 'identifier': 'DES-2', + 'number': 2, + 'title': 'Create component library documentation', + 'description': 'Document all UI components in Storybook ' + 'with usage examples, prop descriptions, ' + 'and accessibility notes.', + 'stateId': 'ws_des_todo', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u4', + 'creatorId': 'u5', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l5'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-07T10:00:00Z', + 'updatedAt': '2026-04-07T10:00:00Z', + 'completedAt': None, + 'sortOrder': 110}, + { 'id': 'i25', + 'identifier': 'DES-3', + 'number': 3, + 'title': 'Redesign notification center UI', + 'description': 'The current notification center is ' + 'cluttered and hard to scan. Design a ' + 'cleaner, more focused inbox experience.', + 'stateId': 'ws_des_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u5', + 'creatorId': 'u1', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l2', 'l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-08T09:00:00Z', + 'updatedAt': '2026-04-10T14:00:00Z', + 'completedAt': None, + 'sortOrder': 120}, + { 'id': 'i26', + 'identifier': 'DES-4', + 'number': 4, + 'title': 'Audit accessibility compliance (WCAG 2.1)', + 'description': 'Conduct full accessibility audit of the ' + 'application against WCAG 2.1 AA ' + 'standards. Document all failures and ' + 'create remediation plan.', + 'stateId': 'ws_des_todo', + 'priority': 1, + 'estimate': 8, + 'assigneeId': 'u1', + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l3'], + 'parentId': None, + 'dueDate': '2026-04-13', + 'subscriberIds': ['u1', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-08T11:00:00Z', + 'updatedAt': '2026-04-08T11:00:00Z', + 'completedAt': None, + 'sortOrder': 130}, + { 'id': 'i27', + 'identifier': 'DES-5', + 'number': 5, + 'title': 'Design mobile app icon and splash screen', + 'description': 'Create app icon following Apple and ' + 'Google guidelines, plus splash screen ' + 'animations.', + 'stateId': 'ws_des_done', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u5', + 'teamId': 't2', + 'projectId': 'p3', + 'cycleId': 'c4', + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-07T14:00:00Z', + 'updatedAt': '2026-04-09T17:00:00Z', + 'completedAt': '2026-04-09T17:00:00Z', + 'sortOrder': 140}, + { 'id': 'i28', + 'identifier': 'DES-6', + 'number': 6, + 'title': 'Create illustration set for empty states', + 'description': 'Design a cohesive set of illustrations ' + 'for all empty state screens in the ' + 'application.', + 'stateId': 'ws_des_backlog', + 'priority': 4, + 'estimate': None, + 'assigneeId': None, + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4'], + 'relationIds': [], + 'createdAt': '2026-03-25T10:00:00Z', + 'updatedAt': '2026-03-25T10:00:00Z', + 'completedAt': None, + 'sortOrder': 200}, + { 'id': 'i29', + 'identifier': 'DES-7', + 'number': 7, + 'title': 'Design dark mode color palette variants', + 'description': 'Expand the design system to include dark ' + 'mode variants for all semantic colors.', + 'stateId': 'ws_des_backlog', + 'priority': 3, + 'estimate': None, + 'assigneeId': 'u5', + 'creatorId': 'u1', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u5'], + 'relationIds': [], + 'createdAt': '2026-03-26T09:00:00Z', + 'updatedAt': '2026-03-26T09:00:00Z', + 'completedAt': None, + 'sortOrder': 210}, + { 'id': 'i30', + 'identifier': 'DES-8', + 'number': 8, + 'title': 'Prototype interactive data visualization', + 'description': 'Build an interactive prototype of the new ' + 'analytics dashboard with filterable ' + 'charts.', + 'stateId': 'ws_des_backlog', + 'priority': 3, + 'estimate': None, + 'assigneeId': None, + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p3', + 'cycleId': None, + 'labelIds': ['l2'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4'], + 'relationIds': [], + 'createdAt': '2026-03-28T11:00:00Z', + 'updatedAt': '2026-03-28T11:00:00Z', + 'completedAt': None, + 'sortOrder': 220}, + { 'id': 'i31', + 'identifier': 'ENG-23', + 'number': 23, + 'title': 'Design avatar upload UI component', + 'description': 'Create the modal dialog and drag-and-drop ' + 'area for avatar uploads.', + 'stateId': 'ws_eng_todo', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l4'], + 'parentId': 'i3', + 'dueDate': None, + 'subscriberIds': ['u2', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-05T10:00:00Z', + 'updatedAt': '2026-04-05T10:00:00Z', + 'completedAt': None, + 'sortOrder': 320}, + { 'id': 'i32', + 'identifier': 'ENG-24', + 'number': 24, + 'title': 'Implement S3 upload service', + 'description': 'Build the backend service for handling ' + 'multipart uploads to S3 with presigned ' + 'URLs.', + 'stateId': 'ws_eng_in_progress', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u2', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l8'], + 'parentId': 'i3', + 'dueDate': None, + 'subscriberIds': ['u2'], + 'relationIds': [], + 'createdAt': '2026-04-05T10:30:00Z', + 'updatedAt': '2026-04-09T11:00:00Z', + 'completedAt': None, + 'sortOrder': 330}], + 'labels': [ { 'id': 'l1', + 'name': 'Bug', + 'color': '#eb5757', + 'teamId': None}, + { 'id': 'l2', + 'name': 'Feature', + 'color': '#5e6ad2', + 'teamId': None}, + { 'id': 'l3', + 'name': 'Improvement', + 'color': '#27a644', + 'teamId': None}, + { 'id': 'l4', + 'name': 'Design', + 'color': '#f2994a', + 'teamId': None}, + { 'id': 'l5', + 'name': 'Documentation', + 'color': '#8a8f98', + 'teamId': None}, + { 'id': 'l6', + 'name': 'Performance', + 'color': '#bb6bd9', + 'teamId': None}, + { 'id': 'l7', + 'name': 'Security', + 'color': '#e5484d', + 'teamId': None}, + { 'id': 'l8', + 'name': 'Infrastructure', + 'color': '#56b4be', + 'teamId': None}], + 'projects': [ { 'id': 'p1', + 'name': 'Website Redesign', + 'description': 'Complete overhaul of the marketing ' + 'website with new brand identity and ' + 'improved performance.', + 'icon': '🌐', + 'color': '#5e6ad2', + 'status': 'started', + 'health': 'onTrack', + 'leadId': 'u1', + 'memberIds': ['u1', 'u2', 'u4', 'u5'], + 'teamIds': ['t1', 't2'], + 'targetDate': '2026-05-31', + 'startDate': '2026-03-01', + 'progress': 65, + 'createdAt': '2026-03-01T09:00:00Z', + 'updatedAt': '2026-04-09T14:00:00Z'}, + { 'id': 'p2', + 'name': 'API v2 Migration', + 'description': 'Migrate all public API endpoints to v2 ' + 'with improved authentication and error ' + 'handling.', + 'icon': '🔌', + 'color': '#f2994a', + 'status': 'started', + 'health': 'atRisk', + 'leadId': 'u2', + 'memberIds': ['u1', 'u2', 'u3'], + 'teamIds': ['t1'], + 'targetDate': '2026-04-30', + 'startDate': '2026-02-15', + 'progress': 30, + 'createdAt': '2026-02-15T09:00:00Z', + 'updatedAt': '2026-04-08T11:00:00Z'}, + { 'id': 'p3', + 'name': 'Mobile App Launch', + 'description': 'Design and development of the companion ' + 'mobile app for iOS and Android.', + 'icon': '📱', + 'color': '#27a644', + 'status': 'planned', + 'health': None, + 'leadId': 'u4', + 'memberIds': ['u4', 'u5'], + 'teamIds': ['t2'], + 'targetDate': '2026-07-31', + 'startDate': '2026-05-01', + 'progress': 0, + 'createdAt': '2026-04-01T09:00:00Z', + 'updatedAt': '2026-04-01T09:00:00Z'}], + 'cycles': [ { 'id': 'c1', + 'number': 5, + 'name': 'Cycle 5', + 'teamId': 't1', + 'startsAt': '2026-03-31', + 'endsAt': '2026-04-13', + 'isActive': True, + 'isCompleted': False, + 'progress': 20}, + { 'id': 'c2', + 'number': 4, + 'name': 'Cycle 4', + 'teamId': 't1', + 'startsAt': '2026-03-17', + 'endsAt': '2026-03-30', + 'isActive': False, + 'isCompleted': True, + 'progress': 100}, + { 'id': 'c3', + 'number': 6, + 'name': 'Cycle 6', + 'teamId': 't1', + 'startsAt': '2026-04-14', + 'endsAt': '2026-04-27', + 'isActive': False, + 'isCompleted': False, + 'progress': 0}, + { 'id': 'c4', + 'number': 3, + 'name': 'Cycle 3', + 'teamId': 't2', + 'startsAt': '2026-04-07', + 'endsAt': '2026-04-13', + 'isActive': True, + 'isCompleted': False, + 'progress': 20}], + 'comments': [ { 'id': 'cm1', + 'body': "I've started working on this. The GitHub " + 'Actions workflow is configured and should be ' + 'ready for review by EOD.', + 'issueId': 'i1', + 'userId': 'u3', + 'createdAt': '2026-04-08T10:00:00Z', + 'updatedAt': '2026-04-08T10:00:00Z', + 'parentId': None}, + { 'id': 'cm2', + 'body': 'Looks good! Make sure to add the Slack webhook ' + 'secret to the environment variables.', + 'issueId': 'i1', + 'userId': 'u1', + 'createdAt': '2026-04-08T11:30:00Z', + 'updatedAt': '2026-04-08T11:30:00Z', + 'parentId': None}, + { 'id': 'cm3', + 'body': 'Done, added it to the secrets manager. The ' + 'pipeline is green now.', + 'issueId': 'i1', + 'userId': 'u3', + 'createdAt': '2026-04-08T14:00:00Z', + 'updatedAt': '2026-04-08T14:00:00Z', + 'parentId': 'cm2'}, + { 'id': 'cm4', + 'body': 'I reproduced the race condition. It happens ' + 'when the token expires within the same 100ms ' + 'window as multiple fetch calls. We need to ' + 'implement a mutex or queue mechanism.', + 'issueId': 'i2', + 'userId': 'u1', + 'createdAt': '2026-04-09T09:30:00Z', + 'updatedAt': '2026-04-09T09:30:00Z', + 'parentId': None}, + { 'id': 'cm5', + 'body': 'Could we use a refresh promise singleton ' + 'pattern? That way concurrent refreshes share ' + 'the same promise.', + 'issueId': 'i2', + 'userId': 'u2', + 'createdAt': '2026-04-09T10:15:00Z', + 'updatedAt': '2026-04-09T10:15:00Z', + 'parentId': None}, + { 'id': 'cm6', + 'body': "Yes, that's the plan. I'll implement that " + 'approach.', + 'issueId': 'i2', + 'userId': 'u1', + 'createdAt': '2026-04-09T10:45:00Z', + 'updatedAt': '2026-04-09T10:45:00Z', + 'parentId': 'cm5'}, + { 'id': 'cm7', + 'body': 'Code review complete. The PR looks solid ' + 'overall. A few minor comments:\n' + '1. The pool size should be configurable via ' + 'env var\n' + '2. Add connection timeout handling\n' + '3. The error logging format could be more ' + 'structured', + 'issueId': 'i6', + 'userId': 'u2', + 'createdAt': '2026-04-09T14:00:00Z', + 'updatedAt': '2026-04-09T14:00:00Z', + 'parentId': None}, + { 'id': 'cm8', + 'body': 'All feedback addressed. Pool size is now ' + 'configurable with `DB_POOL_SIZE` env var.', + 'issueId': 'i6', + 'userId': 'u1', + 'createdAt': '2026-04-10T08:30:00Z', + 'updatedAt': '2026-04-10T08:30:00Z', + 'parentId': None}, + { 'id': 'cm9', + 'body': 'Payment flow tests are at 85% coverage. ' + 'Remaining 15% is edge cases around declined ' + 'cards and network timeouts.', + 'issueId': 'i7', + 'userId': 'u2', + 'createdAt': '2026-04-09T16:00:00Z', + 'updatedAt': '2026-04-09T16:00:00Z', + 'parentId': None}, + { 'id': 'cm10', + 'body': 'Great progress! Make sure to include a test ' + 'for the 3D Secure redirect flow.', + 'issueId': 'i7', + 'userId': 'u1', + 'createdAt': '2026-04-09T16:45:00Z', + 'updatedAt': '2026-04-09T16:45:00Z', + 'parentId': None}, + { 'id': 'cm11', + 'body': 'This is blocking the launch of the mobile ' + 'responsive design. Can we prioritize it?', + 'issueId': 'i5', + 'userId': 'u3', + 'createdAt': '2026-04-08T09:00:00Z', + 'updatedAt': '2026-04-08T09:00:00Z', + 'parentId': None}, + { 'id': 'cm12', + 'body': 'Agreed, adding to the current cycle. @u3 can ' + 'you pair with @u4 on this?', + 'issueId': 'i5', + 'userId': 'u1', + 'createdAt': '2026-04-08T09:30:00Z', + 'updatedAt': '2026-04-08T09:30:00Z', + 'parentId': None}, + { 'id': 'cm13', + 'body': 'The onboarding mockups are taking shape! ' + 'Initial screens are in Figma. Would love ' + 'feedback from the eng team on feasibility.', + 'issueId': 'i23', + 'userId': 'u5', + 'createdAt': '2026-04-09T11:00:00Z', + 'updatedAt': '2026-04-09T11:00:00Z', + 'parentId': None}, + { 'id': 'cm14', + 'body': 'The animation on the welcome screen might be ' + "tricky with our current setup. Let's discuss " + "in tomorrow's sync.", + 'issueId': 'i23', + 'userId': 'u1', + 'createdAt': '2026-04-09T14:30:00Z', + 'updatedAt': '2026-04-09T14:30:00Z', + 'parentId': None}, + { 'id': 'cm15', + 'body': 'The notification redesign looks great! Much ' + 'cleaner than the current version. One ' + 'suggestion: add a "Mark all as read" button at ' + 'the top.', + 'issueId': 'i25', + 'userId': 'u1', + 'createdAt': '2026-04-10T09:00:00Z', + 'updatedAt': '2026-04-10T09:00:00Z', + 'parentId': None}, + { 'id': 'cm16', + 'body': 'Good call! Added that to the designs. Also ' + 'thinking about adding swipe gestures for ' + 'mobile.', + 'issueId': 'i25', + 'userId': 'u5', + 'createdAt': '2026-04-10T10:30:00Z', + 'updatedAt': '2026-04-10T10:30:00Z', + 'parentId': None}, + { 'id': 'cm17', + 'body': 'The performance numbers are looking promising. ' + 'Initial LCP improved by 35% with lazy loading.', + 'issueId': 'i10', + 'userId': 'u3', + 'createdAt': '2026-04-10T10:00:00Z', + 'updatedAt': '2026-04-10T10:00:00Z', + 'parentId': None}], + 'notifications': [ { 'id': 'n1', + 'type': 'issue_assigned', + 'actorId': 'u2', + 'issueId': 'i2', + 'projectId': None, + 'title': 'Jamie Chen assigned you to ENG-2', + 'body': 'Fix authentication token refresh race ' + 'condition', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-10T09:00:00Z'}, + { 'id': 'n2', + 'type': 'comment', + 'actorId': 'u3', + 'issueId': 'i1', + 'projectId': None, + 'title': 'Sam Patel commented on ENG-1', + 'body': 'Done, added it to the secrets manager. ' + 'The pipeline is green now.', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T14:00:00Z'}, + { 'id': 'n3', + 'type': 'issue_mention', + 'actorId': 'u1', + 'issueId': 'i5', + 'projectId': None, + 'title': 'Alex Morgan mentioned you in ENG-5', + 'body': 'can you pair with @u3 on this?', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T09:30:00Z'}, + { 'id': 'n4', + 'type': 'issue_status_changed', + 'actorId': 'u4', + 'issueId': 'i8', + 'projectId': None, + 'title': 'ENG-8 moved to Done', + 'body': 'Taylor Kim moved Fix mobile viewport ' + 'breakpoint inconsistencies to Done', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T17:00:00Z'}, + { 'id': 'n5', + 'type': 'comment', + 'actorId': 'u2', + 'issueId': 'i6', + 'projectId': None, + 'title': 'Jamie Chen commented on ENG-6', + 'body': 'Code review complete. The PR looks solid ' + 'overall.', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-09T14:00:00Z'}, + { 'id': 'n6', + 'type': 'issue_assigned', + 'actorId': 'u4', + 'issueId': 'i26', + 'projectId': None, + 'title': 'Taylor Kim assigned you to DES-4', + 'body': 'Audit accessibility compliance (WCAG 2.1)', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T11:00:00Z'}, + { 'id': 'n7', + 'type': 'issue_status_changed', + 'actorId': 'u3', + 'issueId': 'i1', + 'projectId': None, + 'title': 'ENG-1 moved to In Progress', + 'body': 'Sam Patel moved Set up CI/CD pipeline to ' + 'In Progress', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T10:00:00Z'}, + { 'id': 'n8', + 'type': 'project_update', + 'actorId': 'u2', + 'issueId': None, + 'projectId': 'p2', + 'title': 'API v2 Migration health changed to At ' + 'Risk', + 'body': 'Jamie Chen updated project health. ' + 'Timeline may need adjustment due to scope ' + 'changes.', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-09T11:00:00Z'}, + { 'id': 'n9', + 'type': 'issue_mention', + 'actorId': 'u5', + 'issueId': 'i23', + 'projectId': None, + 'title': 'Jordan Lee mentioned you in DES-1', + 'body': 'Would love feedback from the eng team on ' + 'feasibility.', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-09T11:00:00Z'}, + { 'id': 'n10', + 'type': 'issue_assigned', + 'actorId': 'u1', + 'issueId': 'i9', + 'projectId': None, + 'title': 'You were assigned ENG-9', + 'body': 'Add dark mode support to settings page', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-04T11:00:00Z'}], + 'views': [ { 'id': 'v1', + 'name': 'High Priority Bugs', + 'icon': '🐛', + 'filters': {'priority': [1, 2], 'labelIds': ['l1']}, + 'groupBy': 'status', + 'sortBy': 'priority', + 'layout': 'list', + 'teamId': None, + 'creatorId': 'u1'}, + { 'id': 'v2', + 'name': 'My In Progress', + 'icon': '🔥', + 'filters': {'assigneeId': 'u1', 'stateCategory': 'started'}, + 'groupBy': None, + 'sortBy': 'updated', + 'layout': 'list', + 'teamId': None, + 'creatorId': 'u1'}], + 'favorites': [ { 'id': 'f1', + 'type': 'project', + 'targetId': 'p1', + 'userId': 'u1', + 'sortOrder': 0}, + { 'id': 'f2', + 'type': 'view', + 'targetId': 'v1', + 'userId': 'u1', + 'sortOrder': 1}, + { 'id': 'f3', + 'type': 'cycle', + 'targetId': 'c1', + 'userId': 'u1', + 'sortOrder': 2}], + 'issueRelations': [ { 'id': 'r1', + 'issueId': 'i2', + 'relatedIssueId': 'i5', + 'type': 'blocks'}, + { 'id': 'r2', + 'issueId': 'i5', + 'relatedIssueId': 'i2', + 'type': 'blocked_by'}, + { 'id': 'r3', + 'issueId': 'i6', + 'relatedIssueId': 'i1', + 'type': 'relates_to'}, + { 'id': 'r4', + 'issueId': 'i25', + 'relatedIssueId': 'i9', + 'type': 'relates_to'}], + 'issueCounters': {'t1': 24, 't2': 8}, + 'sidebarCollapsed': False, + 'teamSectionsExpanded': {'t1': True, 't2': True}}, + 'github_mock': { 'currentUser': { 'id': 'u1', + 'username': 'octocat', + 'name': 'The Octocat', + 'email': 'octocat@github.com', + 'avatar': ''}, + 'users': [ { 'id': 'u1', + 'username': 'octocat', + 'name': 'The Octocat', + 'email': 'octocat@github.com', + 'avatar': ''}, + { 'id': 'u2', + 'username': 'hubot', + 'name': 'Hubot', + 'email': 'hubot@github.com', + 'avatar': ''}], + 'repos': [ { 'id': 'r1', + 'ownerId': 'u1', + 'name': 'hello-world', + 'description': 'Sample repo', + 'language': 'Python', + 'stars': 12, + 'forks': 3, + 'watchers': 5, + 'isPrivate': False, + 'defaultBranch': 'main', + 'topics': [], + 'hasWiki': True, + 'hasIssues': True, + 'updatedAt': '2026-06-01T00:00:00Z', + 'createdAt': '2026-01-01T00:00:00Z'}], + 'branches': [ { 'id': 'b1', + 'repoId': 'r1', + 'name': 'main', + 'lastCommitId': 'abc123'}], + 'files': [], + 'commits': [], + 'issues': [ { 'id': 'gi1', + 'repoId': 'r1', + 'number': 1, + 'title': 'Update README badges', + 'description': '', + 'status': 'open', + 'authorId': 'u1', + 'assignees': [], + 'labels': [], + 'milestone': None, + 'column': 'todo', + 'isPinned': False, + 'reactions': {}, + 'createdAt': '2026-06-01T00:00:00Z', + 'closedAt': None, + 'comments': []}], + 'pullRequests': [], + 'wiki': [], + 'actions': [], + 'notifications': [], + 'labels': [], + 'milestones': [], + 'discussions': [], + 'releases': []}, + 'slack_mock': { 'currentUser': { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'workspace': { 'workspaceId': 'ws_1', + 'workspaceName': 'Acme Corp', + 'icon': ''}, + 'users': [ { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_2', + 'fullName': 'Sarah Johnson', + 'displayName': 'Sarah', + 'email': 'sarah.johnson@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_3', + 'fullName': 'Mike Chen', + 'displayName': 'Mike', + 'email': 'mike.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_4', + 'fullName': 'Lisa Park', + 'displayName': 'Lisa', + 'email': 'lisa.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}], + 'channels': [ { 'channelId': 'general', + 'name': 'general', + 'description': 'general channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + { 'channelId': 'engineering', + 'name': 'engineering', + 'description': 'engineering channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + { 'channelId': 'random', + 'name': 'random', + 'description': 'random channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}], + 'messages': { 'general': [], + 'engineering': [ { 'messageId': 'e1', + 'senderId': 'user_2', + 'content': 'pagerduty is going off — ' + 'notifications service is ' + 'OOMing in prod', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}, + { 'messageId': 'e2', + 'senderId': 'user_3', + 'content': 'which backlog item covers ' + 'that?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward_label.json b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..ab110e4983c8aee59c5b81194d80cb1ea7f3be39 --- /dev/null +++ b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward_label.json @@ -0,0 +1,70 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/a91f29df-e380-5d54-b965-27aecef4d2b3/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:20:23", + "label": { + "task_id": "a91f29df-e380-5d54-b965-27aecef4d2b3", + "domain": "mock_websites", + "summary": "验证 Linear 工单 ENG-15 的状态变更与人员分配、GitHub 创建相关 Issue、以及在 Slack engineering 频道发送提及 ENG-15 的新消息", + "is_placeholder": false, + "data_sources": [ + "linear_mock", + "github_mock", + "slack_mock", + "/tmp/task_web_sid" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.3, + "description": "Linear 中 ENG-15 工单被移动到 In Progress", + "check_logic": "从 linear_mock 的 current_state.issues 中查找 id 为 'i15' 的 issue,检查其 stateId 是否等于 'ws_eng_in_progress'", + "pass_condition": "linear_mock 中存在 id='i15' 的 issue 且其 stateId == 'ws_eng_in_progress'" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "Linear 中 ENG-15 工单分配给 Sam Patel", + "check_logic": "从 linear_mock 的 current_state.issues 中查找 id 为 'i15' 的 issue,检查其 assigneeId 是否等于 'u3'", + "pass_condition": "linear_mock 中存在 id='i15' 的 issue 且其 assigneeId == 'u3'" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "GitHub 中新建了关于 memory leak 的 issue", + "check_logic": "对比 github_mock 的 initial_state.issues 与 current_state.issues,找出 id 不在初始集合中的新 issue,并检查其 title(转小写后)是否包含 'memory leak in real-time notifications' 或 'memory leak'", + "pass_condition": "github_mock current_state 中存在新 issue(id 不在 initial_state 中)且标题包含指定 memory leak 关键词" + }, + { + "name": "Component 4", + "weight": 0.1, + "description": "Slack engineering 频道有 user_1 发送的新消息", + "check_logic": "检查 slack_mock current_state.messages.engineering 中是否存在 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId == 'user_1' 的消息", + "pass_condition": "slack_mock engineering 频道存在至少一条由 user_1 发送且不在初始 SEED 中的新消息" + }, + { + "name": "Component 5", + "weight": 0.2, + "description": "Slack engineering 频道的新消息中准确提及 ENG-15", + "check_logic": "将 slack_mock engineering 频道中所有 senderId='user_1' 且不在 SEED 中的消息内容合并并转小写,检查其中是否包含 'eng-15'", + "pass_condition": "由 user_1 发送的新消息内容(小写合并后)包含 'eng-15'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限 1.0,再四舍五入保留 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,输出 REWARD: 0.0 并退出", + "任一 mock 服务(linear_mock、github_mock、slack_mock)状态拉取失败:打印 CRITICAL,输出 REWARD: 0.0 并退出", + "ENG-15 未移动到 In Progress:FAIL,不得 0.3 分", + "ENG-15 未分配给 Sam Patel (u3):FAIL,不得 0.2 分", + "GitHub 未创建关于 memory leak 的新 issue:FAIL,不得 0.2 分", + "Slack #engineering 无 user_1 的新消息:FAIL,不得 0.1 分", + "Slack #engineering 新消息未包含 ENG-15:FAIL,不得 0.2 分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 linear_mock、github_mock、slack_mock 发送请求获取当前状态。若读取 sid 或任一 mock 状态失败则直接返回 0.0。随后按顺序检查五个评分组件:1) Linear 中 id 为 i15 的 issue 状态是否为 ws_eng_in_progress;2) 同一 issue 的 assigneeId 是否为 u3;3) GitHub 中是否存在标题包含 memory leak 相关关键词且不在初始状态中的新 issue;4) Slack engineering 频道是否有 senderId 为 user_1 的新消息;5) 这些新消息内容(小写合并后)是否包含 eng-15。各组件通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不包含任何额外文本、Markdown 代码块标记或思考过程。\n\n让我仔细阅读源码:\n\n1. **Task ID**: 从 docstring 看是 `se_linear_github_triage_b91`,但文件路径中的 UUID 是 `a91f29df-e380-5d54-b965-27aecef4d2b3`。docstring 中明确写了 \"Task ID: a91f29df-e380-5d54-b965-27aecef4d2b3\",所以 task_id 应该是这个 UUID。\n\n2. **Domain**: docstring 中明确写了 `Domain: mock_websites`。\n\n3. **Summary**: 一句话概括。这个脚本验证 Linear 工单状态变更、分配、GitHub issue 创建、Slack 消息发送等行为。\n\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n\n5. **data_sources**: `linear_mock`, `github_mock`, `slack_mock`, `/tmp/task_web_sid`。\n\n6. **scoring_components**:\n - Component 1 (c0): weight 0.3, 检查 linear_mock 中 id 为 i15 的 issue 的 stateId 是否为 'ws_eng_in_progress'。\n - Component 2 (c1): weight 0.2, 检查 linear_mock 中 id 为 i15 的 issue 的 assigneeId 是否为 'u3'。\n - Component 3 (c2): weight 0.2, 检查 github_mock 中是否有新创建的 issue(不在 initial_state 中),且标题包含 'memory leak in real-time notifications' 或 'memory leak'。\n - Component 4 (c3): weight 0.1, 检查 slack_mock 的 engineering 频道中是否有 senderId 为 'user_1' 的新消息(排除 SEED 中的消息)。\n - Component 5 (c4): weight 0.2, 检查 slack_mock 的 engineering 频道中 senderId 为 'user_1' 的新消息内容(小写后)是否包含 'eng-15'。\n\n7. **total_max_score**: 1.0\n\n8. **score_aggregation**: 各组件分数相加,最后用 `min(total, 1.0)` 钳制到上限 1.0,再四舍五入到 4 位小数。\n\n9. **failure_modes**:\n - 读取 `/tmp/task_web_sid` 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)。\n - 从任一 mock 服务获取状态失败:打印 CRITICAL,REWARD: 0.0,sys.exit(0)。\n - 各组件检查失败:仅打印 FAIL,不加分,不提前退出。\n\n10. **scoring_logic_explanation**: 按执行顺序详细说明。\n\n11. **confidence**: 1.0,因为源码完整清晰。\n\n让我再仔细检查一下细节:\n\n- c3 和 c4 都检查 slack_mock:engineering 中 senderId 为 user_1 且不在 SEED 中的消息。c3 只要有新消息就加 0.1。c4 要求这些新消息的内容(小写合并后)包含 'eng-15'。\n- c4 的代码:`c4_msgs = ...`, `c4_seed = ...`, `c4_blob = _lc(' '.join(...))`, `if all(t in c4_blob for t in ['eng-15']):`。这里 `all(t in c4_blob for t in ['eng-15'])` 实际上就是检查 'eng-15' 是否在 c4_blob 中。\n- c2 的代码:`c2_new = [i for i in (cur('github_mock').get('issues') or []) if i.get('id') not in c2_init and any(t in _lc(i.get('title','')) for t in ['memory leak in real-time notifications', 'memory leak'])]`。检查新 issue 标题是否包含指定关键词。\n\n注意:task_id 从 docstring 中提取。docstring 第一行是 `Reward Script: se_linear_github_triage_b91`,但后面明确写了 `Task ID: a91f29df-e380-5d54-b965-27aecef4d2b3`。根据要求\"从文件 docstring 中提取的任务 ID\",应该取 `a91f29df-e380-5d54-b965-27aecef4d2b3`。\n\ndomain 是 `mock_websites`。\n\n现在构建 JSON。确保:\n- 只输出 JSON 对象\n- 第一个字符是 `{`,最后一个字符是 `}`\n- 没有 Markdown 代码块\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- weight 填写代码中显式给出的分值\n\n让我确认每个组件的 pass_condition:\n\nc0: linear_mock 中 id='i15' 的 issue 存在且 stateId == 'ws_eng_in_progress'\nc1: linear_mock 中 id='i15' 的 issue 存在且 assigneeId == 'u3'\nc2: github_mock current_state issues 中存在 id 不在 initial_state issues 中的新 issue,且其 title(小写)包含 'memory leak in real-time notifications' 或 'memory leak'\nc3: slack_mock current_state messages.engineering 中存在 messageId 不在 SEED[\"slack_mock:engineering\"] 中且 senderId == 'user_1' 的新消息\nc4: slack_mock current_state messages.engineering 中,由 senderId='user_1' 发送且不在 SEED 中的新消息,其内容合并后小写包含 'eng-15'\n\nfailure_modes:\n- /tmp/task_web_sid 读取失败或为空:CRITICAL,REWARD 0.0,退出\n- linear_mock/github_mock/slack_mock 任一状态拉取失败:CRITICAL,REWARD 0.0,退出\n- ENG-15 未移动到 In Progress:FAIL,不得 0.3 分\n- ENG-15 未分配给 Sam Patel (u3):FAIL,不得 0.2 分\n- GitHub 未创建关于 memory leak 的新 issue:FAIL,不得 0.2 分\n- Slack #engineering 无 user_1 的新消息:FAIL,不得 0.1 分\n- Slack #engineering 新消息未包含 ENG-15:FAIL,不得 0.2 分\n\nscore_aggregation: 各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,再四舍五入保留 4 位小数。\n\nsummary: 验证 Linear 工单 ENG-15 的状态变更与人员分配、GitHub 创建相关 Issue、以及在 Slack engineering 频道发送提及 ENG-15 的新消息。\n\nscoring_logic_explanation: 脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 linear_mock、github_mock、slack_mock 发送请求获取当前状态。若读取 sid 或任一 mock 状态失败则直接返回 0.0。随后按顺序检查五个评分组件:1) Linear 中 id 为 i15 的 issue 状态是否为 ws_eng_in_progress;2) 同一 issue 的 assigneeId 是否为 u3;3) GitHub 中是否存在标题包含 memory leak 相关关键词且不在初始状态中的新 issue;4) Slack engineering 频道是否有 senderId 为 user_1 的新消息;5) 这些新消息内容(小写合并后)是否包含 eng-15。各组件通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后输出。\n\nconfidence: 1.0\n\n检查 JSON 格式,确保没有 trailing comma。\n\n让我再仔细看看 c4 的代码逻辑:\n```python\nc4_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or []\nc4_seed = set(SEED.get('slack_mock:engineering', []))\nc4_blob = _lc(' '.join((m.get('content') or '') for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1'))\nif all(t in c4_blob for t in ['eng-15']):\n```\n这里 `all(t in c4_blob for t in ['eng-15'])` 就是检查 'eng-15' 是否在字符串中。注意 c4_blob 包含的是所有不在 seed 中且 senderId 为 user_1 的消息,不仅仅是新消息(虽然相对于 seed 来说都是新的)。c3 检查的是 `c3_new` 是否非空,c4 检查的是 `c4_blob` 是否包含 'eng-15'。\n\nc3 和 c4 的 seed 检查是一致的。\n\n好的,准备输出。 {\"task_id\":\"a91f29df-e380-5d54-b965-27aecef4d2b3\",\"domain\":\"mock_websites\",\"summary\":\"验证 Linear 工单 ENG-15 的状态变更与人员分配、GitHub 创建相关 Issue、以及在 Slack engineering 频道发送提及 ENG-15 的新消息\",\"is_placeholder\":false,\"data_sources\":[\"linear_mock\",\"github_mock\",\"slack_mock\",\"/tmp/task_web_sid\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.3,\"description\":\"Linear 中 ENG-15 工单被移动到 In Progress\",\"check_logic\":\"从 linear_mock 的 current_state.issues 中查找 id 为 'i15' 的 issue,检查其 stateId 是否等于 'ws_eng_in_progress'\",\"pass_condition\":\"linear_mock 中存在 id='i15' 的 issue 且其 stateId == 'ws_eng_in_progress'\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"Linear 中 ENG-15 工单分配给 Sam Patel\",\"check_logic\":\"从 linear_mock 的 current_state.issues 中查找 id 为 'i15' 的 issue,检查其 assigneeId 是否等于 'u3'\",\"pass_condition\":\"linear_mock 中存在 id='i15' 的 issue 且其 assigneeId == 'u3'\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"GitHub 中新建了关于 memory leak 的 issue\",\"check_logic\":\"对比 github_mock 的 initial_state.issues 与 current_state.issues,找出 id 不在初始集合中的新 issue,并检查其 title(转小写后)是否包含 'memory leak in real-time notifications' 或 'memory leak'\",\"pass_condition\":\"github_mock current_state 中存在新 issue(id 不在 initial_state 中)且标题包含指定 memory leak 关键词\"},{\"name\":\"Component 4\",\"weight\":0.1,\"description\":\"Slack engineering 频道有 user_1 发送的新消息\",\"check_logic\":\"检查 slack_mock current_state.messages.engineering 中是否存在 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId == 'user_1' 的消息\",\"pass_condition\":\"slack_mock engineering 频道存在至少一条由 user_1 发送且不在初始 SEED 中的新消息\"},{\"name\":\"Component 5\",\"weight\":0.2,\"description\":\"Slack engineering 频道的新消息中准确提及 ENG-15\",\"check_logic\":\"将 slack_mock engineering 频道中所有 senderId='user_1' 且不在 SEED 中的消息内容合并并转小写,检查其中是否包含 'eng-15'\",\"pass_condition\":\"由 user_1 发送的新消息内容(小写合并后)包含 'eng-15'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限 1.0,再四舍五入保留 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,输出 REWARD: 0.0 并退出\",\"任一 mock 服务(linear_mock、github_mock、slack_mock)状态拉取失败:打印 CRITICAL,输出 REWARD: 0.0 并退出\",\"ENG-15 未移动到 In Progress:FAIL,不得 0.3 分\",\"ENG-15 未分配给 Sam Patel (u3):FAIL,不得 0.2 分\",\"GitHub 未创建关于 memory leak 的新 issue:FAIL,不得 0.2 分\",\"Slack #engineering 无 user_1 的新消息:FAIL,不得 0.1 分\",\"Slack #engineering 新消息未包含 ENG-15:FAIL,不得 0.2 分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 linear_mock、github_mock、slack_mock 发送请求获取当前状态。若读取 sid 或任一 mock 状态失败则直接返回 0.0。随后按顺序检查五个评分组件:1) Linear 中 id 为 i15 的 issue 状态是否为 ws_eng_in_progress;2) 同一 issue 的 assigneeId 是否为 u3;3) GitHub 中是否存在标题包含 memory leak 相关关键词且不在初始状态中的新 issue;4) Slack engineering 频道是否有 senderId 为 user_1 的新消息;5) 这些新消息内容(小写合并后)是否包含 eng-15。各组件通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后输出。\",\"confidence\":1.0}" +} diff --git a/legacy/prof19_hygiene_report_001/_cua_gym_vm_bridge.sh b/legacy/prof19_hygiene_report_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/prof19_hygiene_report_001/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/prof19_hygiene_report_001/initial_setup.py b/legacy/prof19_hygiene_report_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb7fa91d5c7b05a7bfbfb2e2713babfe049f427 --- /dev/null +++ b/legacy/prof19_hygiene_report_001/initial_setup.py @@ -0,0 +1,146 @@ +""" +Initial Setup: CRM Hygiene Report (Stale Open Opps) +Task ID: prof19_hygiene_report_001 +Domain: libreoffice_calc + +Builds the PRE-TASK state on the initial VM: + 1. /home/user/salesforce_opportunities.csv + - The Salesforce "Opportunities" list view filtered to Stage = 'Open'. + - 14 open opportunities. Exactly 3 have a past Close Date (stale): + OPP-4821, OPP-4833, OPP-4840. + - 1 future distractor (OPP-4855, Close Date 2026-09-15) must be excluded. + - The 4 already-flagged opps (OPP-4801..4804) are NOT in this list. + 2. /home/user/prof19_hygiene_report_001.xlsx + - The Google Sheets 'CRM Hygiene Report' tab 'Stale Open Opps'. + - Header row + 4 existing rows (OPP-4801..4804). NO stale opps added yet. + +The agent must read the Salesforce CSV, find the 3 stale opps, and append +them to the report. +""" + +import csv +import os +import shlex +import subprocess +import time + +WORKDIR = '/home/user' # VM path -- all scripts run on the VM +TASK_ID = 'prof19_hygiene_report_001' + +SALESFORCE_CSV = f'{WORKDIR}/salesforce_opportunities.csv' +REPORT_XLSX = f'{WORKDIR}/{TASK_ID}.xlsx' + +# Salesforce "Opportunities" list view -- Stage = 'Open' (14 rows). +# Columns: Opportunity ID, Account Name, Stage, Close Date, Amount +SALESFORCE_ROWS = [ + # Stale (Close Date in the past, still open) -- the 3 to flag + ['OPP-4821', 'Northwind Logistics — Platform Seat Expansion', 'Prospecting', '2026-05-19', 48000], + ['OPP-4833', 'Helios Health — Analytics Add-on', 'Qualification', '2026-06-08', 27500], + ['OPP-4840', 'Cobalt Retail — Multi-region Rollout', 'Negotiation', '2026-04-30', 61000], + # Distractor (future close date, must NOT be flagged) + ['OPP-4855', 'Vertex Media — Renewal', 'Proposal', '2026-09-15', 39000], + # Remaining open opps (future close dates, not stale) + ['OPP-4805', 'Acme Robotics — Seat Expansion', 'Qualification', '2026-08-12', 52000], + ['OPP-4806', 'BrightWave Logistics — Analytics', 'Prospecting', '2026-10-03', 33000], + ['OPP-4807', 'Summit Health — Platform', 'Negotiation', '2026-11-20', 71000], + ['OPP-4808', 'Pinecrest Foods — Add-on', 'Proposal', '2026-12-01', 24000], + ['OPP-4809', 'Lumen Media — Expansion', 'Qualification', '2026-08-25', 46000], + ['OPP-4810', 'TerraNova Energy — Pilot', 'Prospecting', '2026-09-30', 18000], + ['OPP-4811', 'Orion Financial — Platform', 'Negotiation', '2026-10-18', 88000], + ['OPP-4812', 'Cedarline Retail — Add-on', 'Proposal', '2026-11-05', 29000], + ['OPP-4813', 'Aquila Pharma — Expansion', 'Qualification', '2026-12-15', 64000], + ['OPP-4814', 'Meridian Travel — Pilot', 'Prospecting', '2026-08-08', 21000], +] + +REPORT_HEADERS = ['Opportunity ID', 'Account Name', 'Close Date', 'Amount', + 'Flagged By', 'Date Flagged'] + +# Four pre-existing rows in the report (must remain UNCHANGED). +REPORT_EXISTING = [ + ['OPP-4801', 'Aurora Systems — Renewal', '2026-03-12', 42000, 'RevOps', '2026-06-28'], + ['OPP-4802', 'Delphi Manufacturing — Expansion', '2026-02-20', 55000, 'RevOps', '2026-06-28'], + ['OPP-4803', 'Nimbus Cloud — Add-on', '2026-03-01', 31000, 'RevOps', '2026-06-28'], + ['OPP-4804', 'Vantage Logistics — Pilot', '2026-02-15', 26000, 'RevOps', '2026-06-28'], +] + + +def write_csv(path, headers, rows): + with open(path, 'w', newline='', encoding='utf-8') as f: + w = csv.writer(f) + if headers is not None: + w.writerow(headers) + for r in rows: + w.writerow(r) + + +def csv_to_xlsx(csv_path, xlsx_path): + """Convert a CSV to XLSX using headless LibreOffice (no extra python deps).""" + tmp_profile = '/tmp/loprofile_initial' + cmd = ( + f'soffice --headless -env:UserInstallation=file://{tmp_profile} ' + f'--convert-to xlsx --outdir "{os.path.dirname(xlsx_path)}" "{csv_path}"' + ) + subprocess.run(shlex.split(cmd), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, check=False) + # LibreOffice names the output after the input stem. + expected = os.path.join(os.path.dirname(xlsx_path), + os.path.splitext(os.path.basename(csv_path))[0] + '.xlsx') + if expected != xlsx_path and os.path.exists(expected): + os.replace(expected, xlsx_path) + return os.path.exists(xlsx_path) + + +def launch_gui(command, delay_sec=2.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + + +def wait_for_window(substr, timeout=30): + """Poll wmctrl until a window containing `substr` appears.""" + deadline = time.time() + timeout + while time.time() < deadline: + try: + out = subprocess.run(['wmctrl', '-l'], capture_output=True, + text=True, check=False).stdout + if substr.lower() in out.lower(): + return True + except Exception: + pass + time.sleep(1.0) + return False + + +def create_initial(): + # 1. Salesforce source CSV + write_csv(SALESFORCE_CSV, + ['Opportunity ID', 'Account Name', 'Stage', 'Close Date', 'Amount'], + SALESFORCE_ROWS) + print(f'Salesforce source created: {SALESFORCE_CSV}') + + # 2. Report XLSX (header + 4 existing rows, NO stale opps) + tmp_csv = f'{WORKDIR}/_report_tmp.csv' + report_rows = [REPORT_HEADERS] + [list(r) for r in REPORT_EXISTING] + write_csv(tmp_csv, None, report_rows) + ok = csv_to_xlsx(tmp_csv, REPORT_XLSX) + if os.path.exists(tmp_csv): + os.remove(tmp_csv) + if not ok: + raise RuntimeError(f'Failed to convert report CSV to XLSX: {REPORT_XLSX}') + print(f'Report (initial) created: {REPORT_XLSX}') + + # 3. GUI-ready: open BOTH files in LibreOffice Calc for the agent. + launch_gui(f'libreoffice --calc "{REPORT_XLSX}" "{SALESFORCE_CSV}"', delay_sec=3.0) + wait_for_window('LibreOffice Calc', timeout=30) + time.sleep(2.0) + print('GUI_READY: launched LibreOffice Calc with report + Salesforce source (DISPLAY=:0)') + + +if __name__ == '__main__': + create_initial() diff --git a/legacy/prof19_hygiene_report_001/reward.py b/legacy/prof19_hygiene_report_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..74fbb30f44fc358a8ddceac89cd814a687e6737e --- /dev/null +++ b/legacy/prof19_hygiene_report_001/reward.py @@ -0,0 +1,242 @@ +""" +Reward Script: CRM Hygiene Report — append 3 stale open opportunities. +Task ID: prof19_hygiene_report_001 +Domain: libreoffice_calc +Scoring: The .xlsx tab 'Stale Open Opps' must gain exactly 3 new rows + (OPP-4821, OPP-4833, OPP-4840) each with Flagged By='RevOps' and + Date Flagged='2026-07-02', while OPP-4855 must NOT be added. + +NOTE: The VM has no openpyxl/pandas and no internet. We read the spreadsheet +by converting it to CSV with headless LibreOffice (soffice) and parsing with +the stdlib csv module. All paths are VM-local (/home/user/...). +""" +import json +import os +import csv +import subprocess +import tempfile + +WORKDIR = '/home/user' # VM path — all reward scripts run on the VM +TASK_ID = 'prof19_hygiene_report_001' +XLSX_PATH = f'{WORKDIR}/{TASK_ID}.xlsx' + +# Ground-truth golden_stale rows (task-introduced change). These are the three +# opportunities whose Close Date is in the past while still open. +EXPECTED_STALE = { + 'OPP-4821': { + 'account': 'Northwind Logistics — Platform Seat Expansion', + 'close_date': '2026-05-19', + 'amount': '48000', + }, + 'OPP-4833': { + 'account': 'Helios Health — Analytics Add-on', + 'close_date': '2026-06-08', + 'amount': '27500', + }, + 'OPP-4840': { + 'account': 'Cobalt Retail — Multi-region Rollout', + 'close_date': '2026-04-30', + 'amount': '61000', + }, +} +# The four pre-existing rows that must remain untouched (NOT scored, used as +# a baseline/anchor only). +BASELINE_IDS = {'OPP-4801', 'OPP-4802', 'OPP-4803', 'OPP-4804'} +# The distractor: future close date, must NOT appear. +DISTRACTOR_ID = 'OPP-4855' +EXPECTED_FLAGGED_BY = 'RevOps' +EXPECTED_DATE_FLAGGED = '2026-07-02' + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility. + + Parsed by the evaluator to report which sub-objectives passed/failed + instead of only a single aggregate float. Format: ``COMPONENT: ``. + """ + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check function, emit PASS/FAIL + COMPONENT line. + + Args: + idx: component id (1-based). + name: short component name. + weight: max points for this component. + fn: a ``check_component_N`` function returning (passed, score, detail). + args: tuple of positional args for fn. + + Returns: + (passed, score, detail) — score is 0.0 on exception. + """ + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +def _load_rows(xlsx_path): + """Convert the xlsx to CSV via headless LibreOffice and parse it. + + Returns a list of row dicts (header-derived keys) or None on failure. + """ + if not os.path.exists(xlsx_path): + return None + tmpdir = tempfile.mkdtemp(prefix='reward_') + csv_path = os.path.join(tmpdir, os.path.basename(xlsx_path) + '.csv') + try: + subprocess.run( + ['soffice', '--headless', '--convert-to', 'csv', + '--outdir', tmpdir, xlsx_path], + check=True, capture_output=True, timeout=120, + ) + except Exception as e: + # Fall back: maybe conversion wrote under a different name. + print(f'WARN: soffice conversion issue: {e}') + if not os.path.exists(csv_path): + # soffice may name the csv after the sheet; search the tmpdir + cands = [f for f in os.listdir(tmpdir) if f.endswith('.csv')] + if not cands: + return None + csv_path = os.path.join(tmpdir, cands[0]) + with open(csv_path, newline='', encoding='utf-8') as fh: + reader = csv.reader(fh) + rows = [r for r in reader if any(c.strip() for c in r)] + if not rows: + return None + header = [h.strip() for h in rows[0]] + out = [] + for r in rows[1:]: + # pad / trim to header length + rec = {} + for i, h in enumerate(header): + rec[h] = r[i].strip() if i < len(r) else '' + out.append(rec) + return out + + +def normalize_amount(val): + """Normalize an amount cell to a comparable string (strip $ , spaces).""" + if val is None: + return '' + return str(val).replace('$', '').replace(',', '').replace(' ', '').strip() + + +def check_component_1(rows): + """Verify exactly 3 new rows exist beyond the 4 baseline OPP-4801..4804. + Pass condition: total data rows == 7 (4 baseline + 3 new).""" + if rows is None: + return False, 0.0, 'could not parse spreadsheet' + total = len(rows) + if total == 7: + return True, 0.2, f'exactly 7 data rows (4 baseline + 3 new), found {total}' + return False, 0.0, f'expected 7 data rows (4 baseline + 3 new), found {total}' + + +def check_component_2(rows): + """Verify the 3 new rows are OPP-4821, OPP-4833, OPP-4840 with correct + Account Name, Close Date, and Amount (matching the stale opps from Salesforce). + Pass condition: all 3 stale IDs present with matching account/date/amount.""" + if rows is None: + return False, 0.0, 'could not parse spreadsheet' + by_id = {r.get('Opportunity ID', '').strip(): r for r in rows} + missing = [] + for opp_id, exp in EXPECTED_STALE.items(): + rec = by_id.get(opp_id) + if rec is None: + missing.append(f'{opp_id} absent') + continue + if rec.get('Account Name', '').strip() != exp['account']: + missing.append(f'{opp_id} account mismatch') + if rec.get('Close Date', '').strip() != exp['close_date']: + missing.append(f'{opp_id} close date mismatch') + if normalize_amount(rec.get('Amount', '')) != exp['amount']: + missing.append(f'{opp_id} amount mismatch') + if not missing: + return True, 0.4, 'all 3 stale opps present with correct account/date/amount' + return False, 0.0, '; '.join(missing) + + +def check_component_3(rows): + """Verify the 3 new stale rows each have Flagged By='RevOps' and + Date Flagged='2026-07-02' (the specific task action). + Pass condition: all 3 stale rows carry RevOps / 2026-07-02.""" + if rows is None: + return False, 0.0, 'could not parse spreadsheet' + by_id = {r.get('Opportunity ID', '').strip(): r for r in rows} + bad = [] + for opp_id in EXPECTED_STALE: + rec = by_id.get(opp_id) + if rec is None: + bad.append(f'{opp_id} absent') + continue + if rec.get('Flagged By', '').strip() != EXPECTED_FLAGGED_BY: + bad.append(f'{opp_id} Flagged By={rec.get("Flagged By","")!r}') + if rec.get('Date Flagged', '').strip() != EXPECTED_DATE_FLAGGED: + bad.append(f'{opp_id} Date Flagged={rec.get("Date Flagged","")!r}') + if not bad: + return True, 0.4, "all 3 stale rows flagged RevOps / 2026-07-02" + return False, 0.0, '; '.join(bad) + + +def verify_task(file_path): + """Verify task completion with progressive scoring. + Returns: float between 0.0 and 1.0 + """ + rows = _load_rows(file_path) + if rows is None: + print(f"CRITICAL: Cannot load / convert file {file_path}") + print("REWARD: 0.0") + return 0.0 + + # Precondition gate (NOT a scored component): the distractor OPP-4855 must + # not be present. It is absent in BOTH initial and golden states, so it + # cannot earn points (it is not a task-introduced change). If it IS present + # the agent made an error and the whole task fails. + ids = {r.get('Opportunity ID', '').strip() for r in rows} + if DISTRACTOR_ID in ids: + print(f'FAIL: precondition — distractor {DISTRACTOR_ID} must not be present') + print("REWARD: 0.0") + return 0.0 + + total_score = 0.0 + for idx, name, weight, fn in [ + (1, 'Exactly 3 new rows beyond baseline', 0.2, check_component_1), + (2, '3 stale opps with correct account/date/amount', 0.4, check_component_2), + (3, '3 stale rows flagged RevOps / 2026-07-02', 0.4, check_component_3), + ]: + _, score, _ = _run_component(idx, name, weight, fn, (rows,)) + total_score += score + + # Float-artifact guard: weights are designed to sum to exactly 1.0, but + # binary floats (e.g. 0.2+0.4+0.4) can yield 0.9000000000000001. When the + # achieved total is within rounding distance of 1.0, treat as 1.0. + final_score = round(total_score, 4) + if final_score >= 0.9999: + final_score = 1.0 + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +if __name__ == '__main__': + if not os.path.exists(XLSX_PATH): + print(f"File not found: {XLSX_PATH}") + print("REWARD: 0.0") + else: + verify_task(XLSX_PATH) diff --git a/legacy/prof19_hygiene_report_001/reward_label.json b/legacy/prof19_hygiene_report_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..eacff0de2adca7ac39cfe8fad454f413f5f19c14 --- /dev/null +++ b/legacy/prof19_hygiene_report_001/reward_label.json @@ -0,0 +1,53 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof19_hygiene_report_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:30:12", + "label": { + "task_id": "prof19_hygiene_report_001", + "domain": "libreoffice_calc", + "summary": "验证在 .xlsx 文件的 'Stale Open Opps' 工作表中是否正确追加了 3 个指定的过期未结机会(OPP-4821、OPP-4833、OPP-4840),且每行包含 Flagged By='RevOps' 和 Date Flagged='2026-07-02',同时确保未添加干扰项 OPP-4855", + "is_placeholder": false, + "data_sources": [ + "/home/user/prof19_hygiene_report_001.xlsx", + "headless LibreOffice (soffice) 转换生成的 CSV" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.2, + "description": "验证数据行总数是否恰好为 7 行(4 个基线行 + 3 个新增行)", + "check_logic": "调用 check_component_1,检查 len(rows) == 7,即 4 个基线 ID(OPP-4801..OPP-4804)加上 3 个新增行", + "pass_condition": "总行数等于 7" + }, + { + "name": "Component 2", + "weight": 0.4, + "description": "验证 3 个新增行是否为预期的过期机会 ID,且 Account Name、Close Date、Amount 与 EXPECTED_STALE 中的定义一致", + "check_logic": "调用 check_component_2,遍历 EXPECTED_STALE(OPP-4821、OPP-4833、OPP-4840),通过 Opportunity ID 查找对应行,并比对 Account Name、Close Date 和 normalize_amount(Amount) 是否与预期值完全匹配", + "pass_condition": "3 个预期 ID 全部存在,且 account、close_date、amount 字段均匹配" + }, + { + "name": "Component 3", + "weight": 0.4, + "description": "验证 3 个新增过期机会的 Flagged By 和 Date Flagged 字段是否符合任务要求", + "check_logic": "调用 check_component_3,遍历 EXPECTED_STALE 中的 3 个 ID,检查每行的 Flagged By 是否等于 'RevOps',Date Flagged 是否等于 '2026-07-02'", + "pass_condition": "3 个新增行的 Flagged By 均为 'RevOps',Date Flagged 均为 '2026-07-02'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加;若总和因浮点误差大于等于 0.9999,则钳制为 1.0", + "failure_modes": [ + "xlsx 文件不存在或 soffice 转换失败导致无法解析:返回 0.0", + "前置条件失败:表格中包含干扰项 OPP-4855,直接返回 0.0", + "Component 1 失败:数据行总数不是 7,该组件得 0.0 分", + "Component 2 失败:缺少预期 ID 或 Account Name / Close Date / Amount 不匹配,该组件得 0.0 分", + "Component 3 失败:Flagged By 或 Date Flagged 不匹配,该组件得 0.0 分", + "组件检查过程中发生异常:该组件得 0.0 分" + ], + "scoring_logic_explanation": "脚本首先通过 headless LibreOffice 将 /home/user/prof19_hygiene_report_001.xlsx 转换为 CSV 并解析为行字典列表。若文件缺失或转换失败,直接返回 0.0。接着进行前置条件门控:若行中存在 Opportunity ID 为 OPP-4855 的记录,视为错误并返回 0.0。随后依次执行三个评分组件:Component 1(权重 0.2)检查总行数是否恰好为 7(4 个基线 + 3 个新增);Component 2(权重 0.4)检查 3 个新增行是否为 OPP-4821、OPP-4833、OPP-4840,且 Account Name、Close Date、Amount 与预期一致;Component 3(权重 0.4)检查这 3 行的 Flagged By 是否为 'RevOps'、Date Flagged 是否为 '2026-07-02'。各组件得分累加得到总分,最后通过 round 和阈值修正处理浮点误差,输出最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: prof19_hygiene_report_001 (从 docstring 和 TASK_ID 变量中确认)\n2. **Domain**: libreoffice_calc (从 docstring 中确认)\n3. **Summary**: 验证在 .xlsx 文件的 'Stale Open Opps' 标签页中是否正确添加了 3 个新的过期未结机会(OPP-4821, OPP-4833, OPP-4840),每个都带有 Flagged By='RevOps' 和 Date Flagged='2026-07-02',并且没有添加 OPP-4855。\n4. **is_placeholder**: false - 这是一个真正的评分脚本,不是占位符。\n5. **data_sources**: \n - 本地文件 `/home/user/prof19_hygiene_report_001.xlsx` (XLSX_PATH)\n - 通过 headless LibreOffice (soffice) 将 xlsx 转换为 CSV 进行读取\n6. **scoring_components**:\n - Component 1: weight 0.2, 检查总行数是否为 7 (4 个基线 + 3 个新行)\n - Component 2: weight 0.4, 检查 3 个新行是否是 OPP-4821, OPP-4833, OPP-4840,并且 Account Name, Close Date, Amount 与 EXPECTED_STALE 匹配\n - Component 3: weight 0.4, 检查这 3 个新行的 Flagged By 是否为 'RevOps',Date Flagged 是否为 '2026-07-02'\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后进行浮点数修正(如果 >= 0.9999 则设为 1.0)\n9. **failure_modes**:\n - 文件不存在或无法通过 soffice 转换为 CSV:返回 0.0\n - 包含干扰项 OPP-4855:返回 0.0(前置条件门控)\n - 组件检查失败:该组件得 0.0 分\n - 异常:组件得 0.0 分\n10. **scoring_logic_explanation**: \n - 首先检查 xlsx 文件是否存在,使用 headless LibreOffice 将其转换为 CSV\n - 解析 CSV 获取所有行数据\n - 前置条件检查:如果存在 OPP-4855,直接返回 0.0\n - 然后依次执行三个组件检查:\n 1. 检查总行数是否为 7(4 基线 + 3 新增)\n 2. 检查 3 个新增机会的 ID、Account Name、Close Date、Amount 是否与预期一致\n 3. 检查 3 个新增机会的 Flagged By 和 Date Flagged 是否为 'RevOps' 和 '2026-07-02'\n - 各组件得分相加,进行浮点数修正后返回最终分数\n11. **confidence**: 1.0\n\n让我再仔细检查一下细节:\n- `_load_rows` 函数处理 CSV 转换和解析\n- `check_component_1` 检查 `len(rows) == 7`\n- `check_component_2` 检查 EXPECTED_STALE 中的三个 ID 是否存在,以及 account、close_date、amount 是否匹配\n- `check_component_3` 检查 Flagged By 和 Date Flagged\n- `DISTRACTOR_ID` (OPP-4855) 是一个前置条件门控,不是评分组件,如果存在则整个任务失败返回 0.0\n\nJSON 格式要求:\n- 不要输出 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n\n我需要确保 JSON 是有效的,并且所有字段都正确填充。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"prof19_hygiene_report_001\",\n \"domain\": \"libreoffice_calc\",\n \"summary\": \"验证在 .xlsx 文件的 'Stale Open Opps' 工作表中是否正确追加了 3 个指定的过期未结机会(OPP-4821、OPP-4833、OPP-4840),且每行包含 Flagged By='RevOps' 和 Date Flagged='2026-07-02',同时确保未添加干扰项 OPP-4855\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/home/user/prof19_hygiene_report_001.xlsx\", \"headless LibreOffice (soffice) 转换后的 CSV\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.2,\n \"description\": \"验证数据行总数是否恰好为 7 行(4 个基线行 + 3 个新增行)\",\n \"check_logic\": \"调用 check_component_1,检查 len(rows) == 7,即 4 个基线 ID(OPP-4801..OPP-4804)加上 3 个新增行\",\n \"pass_condition\": \"总行数等于 7\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.4,\n \"description\": \"验证 3 个新增行是否为预期的过期机会 ID,且 Account Name、Close Date、Amount 与 EXPECTED_STALE 中的定义一致\",\n \"check_logic\": \"调用 check_component_2,遍历 EXPECTED_STALE(OPP-4821、OPP-4833、OPP-4840),通过 Opportunity ID 查找对应行,并比对 Account Name、Close Date 和 normalize_amount(Amount) 是否与预期值完全匹配\",\n \"pass_condition\": \"3 个预期 ID 全部存在,且 account、close_date、amount 字段均匹配\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.4,\n \"description\": \"验证 3 个新增过期机会的 Flagged By 和 Date Flagged 字段是否符合任务要求\",\n \"check_logic\": \"调用 check_component_3,遍历 EXPECTED_STALE 中的 3 个 ID,检查每行的 Flagged By 是否等于 'RevOps',Date Flagged 是否等于 '2026-07-02'\",\n \"pass_condition\": \"3 个新增行的 Flagged By 均为 'RevOps',Date Flagged 均为 '2026-07-02'\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加;若总和因浮点误差大于等于 0.9999,则钳制为 1.0\",\n \"failure_modes\": [\n \"xlsx 文件不存在或 soffice 转换失败导致无法解析:返回 0.0\",\n \"前置条件失败:表格中包含干扰项 OPP-4855,直接返回 0.0\",\n \"Component 1 失败:数据行总数不是 7,该组件得 0.0 分\",\n \"Component 2 失败:缺少预期 ID 或 Account Name / Close Date / Amount 不匹配,该组件得 0.0 分\",\n \"Component 3 失败:Flagged By 或 Date Flagged 不匹配,该组件得 0.0 分\",\n \"组件检查过程中发生异常:该组件得 0.0 分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先通过 headless LibreOffice 将 /home/user/prof19_hygiene_report_001.xlsx 转换为 CSV 并解析为行字典列表。若文件缺失或转换失败,直接返回 0.0。接着进行前置条件门控:若行中存在 Opportunity ID 为 OPP-4855 的记录,视为错误并返回 0.0。随后依次执行三个评分组件:Component 1(权重 0.2)检查总行数是否恰好为 7(4 个基线 + 3 个新增);Component 2(权重 0.4)检查 3 个新增行是否为 OPP-4821、OPP-4833、OPP-4840,且 Account Name、Close Date、Amount 与预期一致;Component 3(权重 0.4)检查这 3 行的 Flagged By 是否为 'RevOps'、Date Flagged 是否为 '2026-07-02'。各组件得分累加得到总分,最后通过 round 和阈值修正处理浮点误差,输出最终 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查是否符合要求:\n- task_id: prof19_hygiene_report_001 ✓\n- domain: libreoffice_calc ✓\n- summary: 中文概括 ✓\n- is_placeholder: false ✓\n- data_sources: 包含文件路径和 soffice ✓\n- scoring_components: 3 个组件,包含 name, weight, description, check_logic, pass_condition ✓\n- total_max_score: 1.0 ✓\n- score_aggregation: 中文说明 ✓\n- failure_modes: 列出了关键失败路径 ✓\n- scoring_logic_explanation: 详细中文解释 ✓\n- confidence: 1.0 ✓\n\n确保没有 Markdown 代码块,没有额外文字,第一个字符是 {,最后一个字符是 }。\n\n等等,我需要再检查一下 data_sources 的表述。代码中是从本地 xlsx 文件获取,并通过 soffice 转换。data_sources 应该列出脚本从哪些数据源获取状态。这里应该是本地文件和 soffice 转换服务。\n\n另外,注意 docstring 中提到 \"The .xlsx tab 'Stale Open Opps'\",但代码中并没有显式检查工作表名称,它只是转换整个 xlsx 文件。转换后的 CSV 默认可能是活动工作表或第一个工作表。代码中 `_load_rows` 会处理转换后的 CSV。这一点我无需在 JSON 中臆测,只需如实描述。\n\n再检查一下 weight 字段。代码中显式给出了:\n- Component 1: 0.2\n- Component 2: 0.4\n- Component 3: 0.4\n\npass_condition 和 check_logic 需要准确。\n\n一切看起来都正确。 {\"task_id\":\"prof19_hygiene_report_001\",\"domain\":\"libreoffice_calc\",\"summary\":\"验证在 .xlsx 文件的 'Stale Open Opps' 工作表中是否正确追加了 3 个指定的过期未结机会(OPP-4821、OPP-4833、OPP-4840),且每行包含 Flagged By='RevOps' 和 Date Flagged='2026-07-02',同时确保未添加干扰项 OPP-4855\",\"is_placeholder\":false,\"data_sources\":[\"/home/user/prof19_hygiene_report_001.xlsx\",\"headless LibreOffice (soffice) 转换生成的 CSV\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.2,\"description\":\"验证数据行总数是否恰好为 7 行(4 个基线行 + 3 个新增行)\",\"check_logic\":\"调用 check_component_1,检查 len(rows) == 7,即 4 个基线 ID(OPP-4801..OPP-4804)加上 3 个新增行\",\"pass_condition\":\"总行数等于 7\"},{\"name\":\"Component 2\",\"weight\":0.4,\"description\":\"验证 3 个新增行是否为预期的过期机会 ID,且 Account Name、Close Date、Amount 与 EXPECTED_STALE 中的定义一致\",\"check_logic\":\"调用 check_component_2,遍历 EXPECTED_STALE(OPP-4821、OPP-4833、OPP-4840),通过 Opportunity ID 查找对应行,并比对 Account Name、Close Date 和 normalize_amount(Amount) 是否与预期值完全匹配\",\"pass_condition\":\"3 个预期 ID 全部存在,且 account、close_date、amount 字段均匹配\"},{\"name\":\"Component 3\",\"weight\":0.4,\"description\":\"验证 3 个新增过期机会的 Flagged By 和 Date Flagged 字段是否符合任务要求\",\"check_logic\":\"调用 check_component_3,遍历 EXPECTED_STALE 中的 3 个 ID,检查每行的 Flagged By 是否等于 'RevOps',Date Flagged 是否等于 '2026-07-02'\",\"pass_condition\":\"3 个新增行的 Flagged By 均为 'RevOps',Date Flagged 均为 '2026-07-02'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加;若总和因浮点误差大于等于 0.9999,则钳制为 1.0\",\"failure_modes\":[\"xlsx 文件不存在或 soffice 转换失败导致无法解析:返回 0.0\",\"前置条件失败:表格中包含干扰项 OPP-4855,直接返回 0.0\",\"Component 1 失败:数据行总数不是 7,该组件得 0.0 分\",\"Component 2 失败:缺少预期 ID 或 Account Name / Close Date / Amount 不匹配,该组件得 0.0 分\",\"Component 3 失败:Flagged By 或 Date Flagged 不匹配,该组件得 0.0 分\",\"组件检查过程中发生异常:该组件得 0.0 分\"],\"scoring_logic_explanation\":\"脚本首先通过 headless LibreOffice 将 /home/user/prof19_hygiene_report_001.xlsx 转换为 CSV 并解析为行字典列表。若文件缺失或转换失败,直接返回 0.0。接着进行前置条件门控:若行中存在 Opportunity ID 为 OPP-4855 的记录,视为错误并返回 0.0。随后依次执行三个评分组件:Component 1(权重 0.2)检查总行数是否恰好为 7(4 个基线 + 3 个新增);Component 2(权重 0.4)检查 3 个新增行是否为 OPP-4821、OPP-4833、OPP-4840,且 Account Name、Close Date、Amount 与预期一致;Component 3(权重 0.4)检查这 3 行的 Flagged By 是否为 'RevOps'、Date Flagged 是否为 '2026-07-02'。各组件得分累加得到总分,最后通过 round 和阈值修正处理浮点误差,输出最终 REWARD。\",\"confidence\":1.0}" +} diff --git a/mktg_inbound_qualify_009__long/_cua_gym_vm_bridge.sh b/mktg_inbound_qualify_009__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_inbound_qualify_009__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/mktg_inbound_qualify_009__long/initial_setup.py b/mktg_inbound_qualify_009__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..007d218b0e10d67efc3c23187b245e3a55137938 --- /dev/null +++ b/mktg_inbound_qualify_009__long/initial_setup.py @@ -0,0 +1,664 @@ +""" +Initial Setup: marketing-mql-routing — qualify & route this morning's inbound +Task ID: mktg_inbound_qualify_009__long +Persona: Riley Morgan, marketing ops +Mocks: hubspot_marketing_mock,google_docs_mock,google_drive_mock,slack_mock + +Ground-truth embedding (read by reward.py from initial_state): + - hubspot_marketing contacts[]._tier ('hot'|'warm'|'cold') on every inbound + contact to route. Distractors (already-'customer', see below) carry no _tier. + - contacts[]._expected_stage : the lifecycleStage the contact must be set to + (hot -> 'sales_qualified_lead'; warm -> 'marketing_qualified_lead'; + cold -> LEAVE, i.e. its own current stage). PRECOMPUTED in Python. + - contacts[]._expected_owner_email : the owner the contact must be assigned to + (hot -> the AE email; warm -> the nurture-rep email; cold -> unassigned + queue email). PRECOMPUTED in Python. contactOwner stores a USER ID; reward + resolves id->email via the users[] table. + - contacts[]._hot (bool) : whether the contact needs a Docs briefing row + doc + share with its AE. + - google_docs top-level '_task_briefing_doc_id' : the id of the 'AE Briefing' + doc the agent edits + shares. + - google_drive top-level '_task_briefing_item_id' / '_task_sales_handoff_folder_id': + the Drive item id of the 'AE Briefing' doc and the target 'Sales Handoff' + folder id (briefing doc must be moved under it). + +Observable outputs kept ABSENT at injection (Rule 3): + - every routable contact still sits at lifecycleStage 'lead' with owner + 'user-1' (Riley) -> stage+owner routing is a real edit for all of them. + - the 'AE Briefing' Google Doc holds ONLY a header (no per-contact briefing + rows -> no hot contact name appears in the body). + - the 'AE Briefing' doc is NOT shared with any AE (sharedWith == []). + - the 'AE Briefing' Drive item sits in ROOT (parentId == None), not in the + 'Sales Handoff' folder. + - Slack #marketing channel has zero messages. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +TODAY = '2026-06-29' + +# --------------------------------------------------------------------------- +# Routing rule (documented in the instruction; encoded here only via the +# precomputed answer keys, NOT re-derived in reward): +# hot -> lifecycleStage 'sales_qualified_lead' + owner = the AE +# warm -> lifecycleStage 'marketing_qualified_lead'+ owner = the nurture rep +# cold -> LEAVE lifecycleStage + owner = unassigned queue +# --------------------------------------------------------------------------- +NURTURE_EMAIL = 'nadia.cole@acmecorp.com' # user-2 (warm owner) +UNASSIGNED_EMAIL = 'unassigned@acmecorp.com' # user-unassigned (cold owner) + +TIER_STAGE = { + 'hot': 'sales_qualified_lead', + 'warm': 'marketing_qualified_lead', + # 'cold' resolved per-contact to its own current stage (leave as-is) +} + + +# --------------------------------------------------------------------------- +# hubspot_marketing — contacts to route. Builder embeds the answer key. +# --------------------------------------------------------------------------- +def contact(cid, first, last, company, company_id, job_title, city, st, + source, start_stage, start_owner, tier=None, ae_email=None, + create_date='2026-06-29T07:30:00Z'): + """Inbound marketing contact. tier ('hot'|'warm'|'cold') marks a contact the + agent must route and precomputes _expected_stage/_expected_owner_email; + contacts with tier=None are distractors (no answer key, must be left).""" + rec = { + 'id': cid, 'firstName': first, 'lastName': last, 'email': + f'{first.lower()}.{last.lower()}@{company_id_domain(company_id)}', + 'phone': '+1 (555) 555-0100', 'company': company, 'companyId': company_id, + 'jobTitle': job_title, 'lifecycleStage': start_stage, + 'leadStatus': 'new', 'contactOwner': start_owner, + 'createDate': create_date, 'lastActivityDate': '2026-06-29T07:45:00Z', + 'source': source, 'marketingStatus': 'marketing', 'city': city, + 'state': st, 'country': 'United States', 'tags': [], 'notes': '', + } + if tier is not None: + rec['_tier'] = tier + rec['_hot'] = (tier == 'hot') + if tier == 'hot': + rec['_expected_stage'] = TIER_STAGE['hot'] + rec['_expected_owner_email'] = ae_email + elif tier == 'warm': + rec['_expected_stage'] = TIER_STAGE['warm'] + rec['_expected_owner_email'] = NURTURE_EMAIL + else: # cold -> leave stage, owner unassigned + rec['_expected_stage'] = start_stage + rec['_expected_owner_email'] = UNASSIGNED_EMAIL + return rec + + +_DOMAINS = { + 'company-1': 'techflow.com', 'company-2': 'greenleaf.com', + 'company-3': 'beacon.io', 'company-4': 'stellar.com', + 'company-5': 'cloudpeak.com', 'company-6': 'novabridge.com', + 'company-7': 'urbanedge.co', 'company-8': 'pacific.com', +} + + +def company_id_domain(company_id): + return _DOMAINS.get(company_id, 'example.com') + + +HS_USERS = [ + {'id': 'user-1', 'firstName': 'Riley', 'lastName': 'Morgan', 'email': 'riley.morgan@acmecorp.com', 'role': 'Marketing Operations'}, + {'id': 'user-2', 'firstName': 'Nadia', 'lastName': 'Cole', 'email': NURTURE_EMAIL, 'role': 'Nurture Rep'}, + {'id': 'user-ae1', 'firstName': 'Aaron', 'lastName': 'Reyes', 'email': 'aaron.reyes@acmecorp.com', 'role': 'Account Executive'}, + {'id': 'user-ae2', 'firstName': 'Bianca', 'lastName': 'Fox', 'email': 'bianca.fox@acmecorp.com', 'role': 'Account Executive'}, + {'id': 'user-unassigned', 'firstName': 'Unassigned', 'lastName': 'Queue', 'email': UNASSIGNED_EMAIL, 'role': 'Unassigned'}, +] + +AE1_EMAIL = 'aaron.reyes@acmecorp.com' +AE2_EMAIL = 'bianca.fox@acmecorp.com' + +# 7 contacts: 2 hot, 2 warm, 2 cold, + 1 already-'customer' distractor to leave. +# Every routable contact starts at 'lead' owned by user-1 so stage AND owner are +# both real edits. Cold expected_stage == 'lead' (leave); only owner changes. +CONTACTS = [ + # ---- HOT: -> sales_qualified_lead + owner = an AE; needs briefing + share ---- + contact('contact-h1', 'Marcus', 'Thompson', 'Beacon Digital', 'company-3', + 'VP Engineering', 'Chicago', 'IL', 'demo_request', + start_stage='lead', start_owner='user-1', tier='hot', ae_email=AE1_EMAIL), + contact('contact-h2', 'Daniel', 'Kim', 'CloudPeak Systems', 'company-5', + 'Head of Growth', 'Seattle', 'WA', 'demo_request', + start_stage='lead', start_owner='user-1', tier='hot', ae_email=AE2_EMAIL), + # ---- WARM: -> marketing_qualified_lead + owner = nurture rep ---- + contact('contact-w1', 'Alex', 'Turner', 'UrbanEdge Media', 'company-7', + 'Content Strategist', 'Miami', 'FL', 'gated_content', + start_stage='lead', start_owner='user-1', tier='warm'), + contact('contact-w2', 'Priya', 'Sharma', 'Pacific Rim Consulting', 'company-8', + 'Business Analyst', 'San Jose', 'CA', 'webinar', + start_stage='lead', start_owner='user-1', tier='warm'), + # ---- COLD: leave stage, owner -> unassigned queue; must NOT be shared/briefed ---- + contact('contact-c1', 'Sofia', 'Rodriguez', 'Greenleaf Analytics', 'company-2', + 'Data Scientist', 'Oakland', 'CA', 'newsletter', + start_stage='lead', start_owner='user-1', tier='cold'), + contact('contact-c2', 'Carlos', 'Mendez', 'NovaBridge Inc', 'company-6', + 'Student Researcher', 'Brooklyn', 'NY', 'newsletter', + start_stage='lead', start_owner='user-1', tier='cold'), + # ---- DISTRACTOR: already a customer (not a lead) — LEAVE untouched. + # No _tier / answer key; touching it lowers the decision-set via denom. ---- + contact('contact-d1', 'Jennifer', 'Walsh', 'TechFlow Solutions', 'company-1', + 'Director of Operations', 'Boston', 'MA', 'referral', + start_stage='customer', start_owner='user-ae1', tier=None, + create_date='2024-02-08T09:15:00Z'), +] + +HS_COMPANIES = [ + {'id': 'company-1', 'name': 'TechFlow Solutions', 'domain': 'techflow.com', 'industry': 'Software & Technology', 'employeeCount': 450, 'annualRevenue': '$28M', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'phone': '+1 (617) 555-9000', 'owner': 'user-1', 'createDate': '2024-01-10T08:00:00Z', 'contactCount': 1}, + {'id': 'company-2', 'name': 'Greenleaf Analytics', 'domain': 'greenleaf.com', 'industry': 'Data & Analytics', 'employeeCount': 120, 'annualRevenue': '$8.5M', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'phone': '+1 (415) 555-9001', 'owner': 'user-2', 'createDate': '2024-01-20T08:00:00Z', 'contactCount': 1}, + {'id': 'company-3', 'name': 'Beacon Digital', 'domain': 'beacon.io', 'industry': 'Digital Marketing', 'employeeCount': 85, 'annualRevenue': '$5.2M', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'phone': '+1 (312) 555-9002', 'owner': 'user-1', 'createDate': '2024-02-01T08:00:00Z', 'contactCount': 1}, + {'id': 'company-5', 'name': 'CloudPeak Systems', 'domain': 'cloudpeak.com', 'industry': 'Cloud Infrastructure', 'employeeCount': 340, 'annualRevenue': '$22M', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'phone': '+1 (206) 555-9004', 'owner': 'user-1', 'createDate': '2024-02-20T08:00:00Z', 'contactCount': 1}, + {'id': 'company-6', 'name': 'NovaBridge Inc', 'domain': 'novabridge.com', 'industry': 'Business Consulting', 'employeeCount': 60, 'annualRevenue': '$4.1M', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'phone': '+1 (212) 555-9005', 'owner': 'user-3', 'createDate': '2024-03-01T08:00:00Z', 'contactCount': 1}, + {'id': 'company-7', 'name': 'UrbanEdge Media', 'domain': 'urbanedge.co', 'industry': 'Media & Publishing', 'employeeCount': 35, 'annualRevenue': '$2.8M', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'phone': '+1 (305) 555-9006', 'owner': 'user-2', 'createDate': '2024-03-15T08:00:00Z', 'contactCount': 1}, + {'id': 'company-8', 'name': 'Pacific Rim Consulting', 'domain': 'pacific.com', 'industry': 'Management Consulting', 'employeeCount': 180, 'annualRevenue': '$14.6M', 'city': 'San Jose', 'state': 'CA', 'country': 'United States', 'phone': '+1 (408) 555-9007', 'owner': 'user-4', 'createDate': '2024-04-01T08:00:00Z', 'contactCount': 1}, +] + +HUBSPOT_STATE = { + 'currentUser': {'id': 'user-1', 'firstName': 'Riley', 'lastName': 'Morgan', + 'email': 'riley.morgan@acmecorp.com', 'avatar': None, + 'role': 'Marketing Operations', 'company': 'Acme Corp', + 'timezone': 'America/New_York'}, + 'users': HS_USERS, + 'contacts': CONTACTS, + 'activities': {}, + 'companies': HS_COMPANIES, + 'deals': [], + 'lists': [ + {'id': 'list-1', 'name': 'All Inbound (June 29)', 'type': 'active', 'size': 6, 'createdDate': '2026-06-29T07:00:00Z', 'updatedDate': '2026-06-29T07:30:00Z', 'filters': [], 'createdBy': 'user-1'}, + {'id': 'list-4', 'name': 'MQLs This Quarter', 'type': 'active', 'size': 156, 'createdDate': '2026-01-01T08:00:00Z', 'updatedDate': '2026-06-01T00:00:00Z', 'filters': [{'property': 'lifecycleStage', 'operator': 'eq', 'value': 'marketing_qualified_lead'}], 'createdBy': 'user-2'}, + ], + 'settings': { + 'general': {'accountName': 'Acme Corp', 'timezone': 'America/New_York', 'dateFormat': 'MM/DD/YYYY', 'currency': 'USD'}, + 'email': {'defaultFromName': 'Acme Corp Marketing', 'defaultFromEmail': 'marketing@acmecorp.com', 'footerInfo': '123 Marketing Lane, Boston, MA 02101'}, + 'marketing': {'utmTracking': True, 'defaultLifecycleStage': 'lead'}, + }, +} + +# --------------------------------------------------------------------------- +# google_docs — 'AE Briefing' doc: header only, shared with nobody. AE users +# exist (by email) so the Share dialog can resolve typed AE emails to userIds. +# --------------------------------------------------------------------------- +BRIEFING_DOC_ID = 'doc-ae-briefing' + +GDOC_USERS = [ + {'id': 'user-1', 'name': 'Riley Morgan', 'email': 'riley.morgan@acmecorp.com', 'avatar': 'https://picsum.photos/100/100?random=1'}, + {'id': 'user-2', 'name': 'Nadia Cole', 'email': NURTURE_EMAIL, 'avatar': 'https://picsum.photos/100/100?random=2'}, + {'id': 'user-ae1', 'name': 'Aaron Reyes', 'email': AE1_EMAIL, 'avatar': 'https://picsum.photos/100/100?random=3'}, + {'id': 'user-ae2', 'name': 'Bianca Fox', 'email': AE2_EMAIL, 'avatar': 'https://picsum.photos/100/100?random=4'}, + {'id': 'user-5', 'name': 'Priya Shah', 'email': 'priya.shah@acmecorp.com', 'avatar': 'https://picsum.photos/100/100?random=5'}, +] + +GOOGLE_DOCS_STATE = { + '_task_briefing_doc_id': BRIEFING_DOC_ID, + 'currentUser': GDOC_USERS[0], + 'users': GDOC_USERS, + 'documents': { + BRIEFING_DOC_ID: { + 'id': BRIEFING_DOC_ID, 'title': 'AE Briefing', + 'content': '

AE Briefing

' + '

Sales-qualified handoff briefing. Add one row per hot ' + 'contact below: name, company, and the AE it is routed to.

' + '

Briefings

' + '

(no briefings recorded yet)

', + 'ownerId': 'user-1', 'starred': True, + 'created': '2026-06-29T07:00:00Z', 'updated': '2026-06-29T07:00:00Z', + 'sharedWith': [], + 'linkSharing': {'enabled': False, 'permission': 'viewer'}, + }, + 'doc-playbook': { + 'id': 'doc-playbook', 'title': 'Marketing Ops Playbook', + 'content': '

Marketing Ops Playbook

Unrelated reference doc.

', + 'ownerId': 'user-1', 'starred': False, + 'created': '2026-05-01T10:00:00Z', 'updated': '2026-05-01T10:00:00Z', + 'sharedWith': [{'userId': 'user-2', 'permission': 'editor'}], + 'linkSharing': {'enabled': False, 'permission': 'viewer'}, + }, + # Lead-Tier Playbook: makes the hot/warm/cold rule explicit and observable + # so agents don't have to guess how tiers are derived. NOTE: this doc is + # NOT read by reward.py (reward only looks at BRIEFING_DOC_ID='doc-ae-briefing'); + # it's a reference doc for the agent, injected as part of the initial state. + 'doc-lead-tier-playbook': { + 'id': 'doc-lead-tier-playbook', 'title': 'Lead Tier Playbook', + 'content': ( + '

Lead Tier Playbook

' + '

How to derive the fit tier for each inbound contact. ' + 'Apply the rules in order and stop at the first match.

' + '

Step 1 — Skip existing customers

' + '

If a contact\'s Lifecycle Stage is already Customer, ' + 'it is not a fresh lead. Leave it completely untouched.

' + '

Step 2 — Map by Original Source

' + '' + '' + '' + '' + '' + '' + '
Original SourceTier
demo_requestHOT
gated_contentWARM
webinarWARM
newsletterCOLD
' + '

Step 3 — Routed AE (HOT only)

' + '

Each HOT contact must be routed to the Account Executive who ' + 'owns that contact\'s company territory. Look up the contact\'s ' + 'Company on its detail page, then find the AE below.

' + '' + '' + '' + '' + '' + '' + '
TerritoryAccount ExecutiveCompanies
East / CentralAaron Reyes
aaron.reyes@acmecorp.com
Beacon Digital · TechFlow Solutions · UrbanEdge Media · NovaBridge Inc
West / PacificBianca Fox
bianca.fox@acmecorp.com
CloudPeak Systems · Greenleaf Analytics · Pacific Rim Consulting · Stellar Dynamics
' + '

Set the Contact Owner of each HOT contact to the AE that owns ' + 'its company. WARM contacts go to Nadia Cole (nurture rep); COLD ' + 'contacts go to the Unassigned Queue.

' + '

Notes

' + '

The Source field is shown on each contact\'s detail page under ' + 'Original Source. This playbook is the single source of truth for ' + 'tier assignment in this task.

' + ), + 'ownerId': 'user-1', 'starred': False, + 'created': '2026-06-01T09:00:00Z', 'updated': '2026-06-01T09:00:00Z', + 'sharedWith': [], + 'linkSharing': {'enabled': True, 'permission': 'viewer'}, + }, + }, + 'comments': [], + 'ui': {'currentDocId': None, 'sidebarOpen': False, 'sidebarTab': 'comments', + 'shareDialogOpen': False, 'findReplaceOpen': False, 'viewMode': 'editing', + 'zoom': 100, 'documentListView': 'grid', 'searchQuery': ''}, +} + +# --------------------------------------------------------------------------- +# google_drive — 'AE Briefing' item sits in ROOT; 'Sales Handoff' folder exists. +# The briefing item must be moved under the Sales Handoff folder. +# --------------------------------------------------------------------------- +BRIEFING_ITEM_ID = 'file_ae_briefing' +SALES_HANDOFF_FOLDER_ID = 'folder_sales_handoff' + +_D_MS = 1750000000000 # fixed ms-epoch base for deterministic timestamps + + +def drv_folder(fid, name, parent=None): + return {'id': fid, 'parentId': parent, 'name': name, 'type': 'folder', + 'mimeType': 'application/vnd.google-apps.folder', 'size': 0, + 'ownerId': 'user_001', 'sharedWith': [], 'starred': False, + 'trashed': False, 'color': None, 'createdAt': _D_MS, + 'modifiedAt': _D_MS, 'accessedAt': _D_MS} + + +def drv_doc(fid, name, parent=None): + return {'id': fid, 'parentId': parent, 'name': name, 'type': 'doc', + 'mimeType': 'application/vnd.google-apps.document', 'size': 0, + 'ownerId': 'user_001', 'sharedWith': [], 'starred': False, + 'trashed': False, 'color': None, 'createdAt': _D_MS, + 'modifiedAt': _D_MS, 'accessedAt': _D_MS} + + +GOOGLE_DRIVE_STATE = { + '_task_briefing_item_id': BRIEFING_ITEM_ID, + '_task_sales_handoff_folder_id': SALES_HANDOFF_FOLDER_ID, + 'currentUser': {'id': 'user_001', 'name': 'Riley Morgan', 'email': 'riley.morgan@acmecorp.com', 'avatar': 'https://ui-avatars.com/api/?name=Riley+Morgan&background=4285F4&color=fff'}, + 'users': { + 'user_001': {'id': 'user_001', 'name': 'Riley Morgan', 'email': 'riley.morgan@acmecorp.com', 'avatar': 'https://ui-avatars.com/api/?name=Riley+Morgan&background=4285F4&color=fff'}, + 'user_002': {'id': 'user_002', 'name': 'Aaron Reyes', 'email': AE1_EMAIL, 'avatar': 'https://ui-avatars.com/api/?name=Aaron+Reyes&background=EA4335&color=fff'}, + }, + 'items': { + SALES_HANDOFF_FOLDER_ID: drv_folder(SALES_HANDOFF_FOLDER_ID, 'Sales Handoff', None), + 'folder_campaigns': drv_folder('folder_campaigns', 'Campaigns', None), + 'folder_reports': drv_folder('folder_reports', 'Reports', None), + BRIEFING_ITEM_ID: drv_doc(BRIEFING_ITEM_ID, 'AE Briefing', None), # in ROOT (Rule 3) + 'file_deck': drv_doc('file_deck', 'Q3 Campaign Deck', 'folder_campaigns'), + 'file_metrics': drv_doc('file_metrics', 'Funnel Metrics', 'folder_reports'), + }, + 'viewMode': 'grid', + 'sortConfig': {'key': 'name', 'direction': 'asc'}, + 'uploadQueue': [], + 'storageUsed': 3210000000, + 'storageTotal': 16106127360, + 'selectedItems': [], +} + +# --------------------------------------------------------------------------- +# slack — #marketing starts empty; decoy chatter elsewhere. Full key set (Rule 4). +# --------------------------------------------------------------------------- +SLACK_STATE = { + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide chatter', 'topic': 'Welcome!', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'marketing', 'name': 'marketing', 'description': 'Marketing ops — routing summaries and campaign updates', 'topic': 'Post a routing summary after each qualification batch', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'sales', 'name': 'sales', 'description': 'Sales floor', 'topic': 'Close them', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_3'], 'createdBy': 'user_3', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': {'userId': 'user_1', 'fullName': 'Riley Morgan', 'displayName': 'Riley', 'email': 'riley.morgan@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Marketing Operations', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + 'users': [ + {'userId': 'user_1', 'fullName': 'Riley Morgan', 'displayName': 'Riley', 'email': 'riley.morgan@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Marketing Operations', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Nadia Cole', 'displayName': 'Nadia', 'email': NURTURE_EMAIL, 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Nurture Rep', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'}, + {'userId': 'user_3', 'fullName': 'Aaron Reyes', 'displayName': 'Aaron', 'email': AE1_EMAIL, 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Account Executive', 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + ], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': "Morning! This morning's inbound batch is in HubSpot for qualification.", 'timestamp': '2026-06-29T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_2', 'senderId': 'user_3', 'content': 'Ping me in #marketing once the SQLs are routed and briefed.', 'timestamp': '2026-06-29T13:05:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'marketing': [], + 'sales': [ + {'messageId': 'm_s_1', 'senderId': 'user_3', 'content': 'Pipeline review at 3pm.', 'timestamp': '2026-06-29T12:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], +} + + +APP_STATES = [ + ('http://28.7.184.198:8149', HUBSPOT_STATE), # hubspot_marketing_mock (anchor) + ('http://28.7.184.198:8142', GOOGLE_DOCS_STATE), # google_docs_mock + ('http://28.7.184.198:8143', GOOGLE_DRIVE_STATE), # google_drive_mock + ('http://28.7.184.198:8178', SLACK_STATE), # slack_mock +] + +for placeholder, state in APP_STATES: + resp = requests.post( + f'{placeholder}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {placeholder}: {resp.text}' + ) + print(f'State injected: {placeholder} sid={sid}') + +for placeholder, _ in APP_STATES: + go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state') is not None, ( + f'initial_state is None after injection for {placeholder}' + ) + print(f'Verified initial_state set: {placeholder}') + + +def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8): + """Pure-HTTP readiness: wait for every mock to serve its injected state. + No CDP / 9222 probing (that hangs on local review boxes).""" + import urllib.request as _urlreq + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + deadline = time.time() + timeout + todo = list(urls) + while todo and time.time() < deadline: + rest = [] + for _u in todo: + try: + _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5) + if _r.status == 200: + print(f" {_u}: ready") + continue + except Exception: + pass + rest.append(_u) + todo = rest + if todo: + time.sleep(2) + print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}" + + (f" (pending: {todo})" if todo else "")) + time.sleep(render_buffer) + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/mktg_inbound_qualify_009__long/reward.py b/mktg_inbound_qualify_009__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc2de66a265e403eeebd3325cf1d2ca9def72e8 --- /dev/null +++ b/mktg_inbound_qualify_009__long/reward.py @@ -0,0 +1,344 @@ +""" +Reward Script: marketing-mql-routing — qualify & route this morning's inbound +Task ID: mktg_inbound_qualify_009__long +Mocks: hubspot_marketing_mock,google_docs_mock,google_drive_mock,slack_mock + +Answer key (sole source of truth, embedded in initial_state): + - hubspot_marketing contacts[]._tier / _expected_stage / _expected_owner_email + / _hot (precomputed by initial_setup from the tier routing rule). + - google_docs '_task_briefing_doc_id' (the 'AE Briefing' doc). + - google_drive '_task_briefing_item_id' / '_task_sales_handoff_folder_id'. + +Scoring (sub-weights sum to 1.0; ALL frac/F1 over absent-at-injection outputs +so do-nothing == 0.0, no penalties — leak shows only through precision/denom): + 0.35 hubspot stage+owner decision-set : per routable contact (has _tier), + lifecycleStage == _expected_stage AND resolved owner email == + _expected_owner_email. denom = #routable + #wrongly-touched customer + distractors (a distractor whose stage OR owner changed from initial), + so touching the leave-alone customer lowers the score via the denom. + 0.20 Docs share F1 (hot) : true = AE emails of hot contacts; pred = emails of + users in the AE-Briefing doc sharedWith (id->email). Extra/wrong shares + lower precision; missing AEs lower recall. + 0.13 Docs briefing-row recall (hot) : frac of hot contacts whose full name + appears in the current AE-Briefing doc body (a briefing row). + 0.14 Drive move : the AE-Briefing item's current parentId == the Sales Handoff + folder id. + 0.13 Slack post : a non-empty message exists in #marketing (empty at injection). + 0.05 Slack pin (gated) : a message that actually lives in #marketing is pinned + (only counts if a post exists). +""" +import copy +import re +import sys + +import requests + +# --- Read sid (fatal if missing) --- +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +APP_URLS = { + 'hubspot_marketing': 'http://28.7.184.198:8149', + 'google_docs': 'http://28.7.184.198:8142', + 'google_drive': 'http://28.7.184.198:8143', + 'slack': 'http://28.7.184.198:8178', +} +_GO_CACHE = {} + + +# --- Shared utils --- +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def f1(true_set, pred_set): + if not true_set and not pred_set: + return 1.0 + tp = len(true_set & pred_set) + if tp == 0: + return 0.0 + prec = tp / len(pred_set) + rec = tp / len(true_set) + return 2 * prec * rec / (prec + rec) + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def has_text(haystack, *needles): + s = (haystack or '').lower() + return all(n.lower() in s for n in needles) + + +def _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +def _strip_html(s): + return re.sub(r'<[^>]+>', ' ', str(s or '')) + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) + target = None + for ch in channels: + if norm(ch.get('name')) == norm(channel_name): + target = ch + break + if target is None: + return [] + ch_msgs = target.get('messages') + if isinstance(ch_msgs, list): + return ch_msgs + msg_map = slack_state.get('messages', {}) + if isinstance(msg_map, dict): + return msg_map.get(target.get('channelId'), []) or [] + return [] + + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _materialize_slack(payload): + """Merge top-level messages[cid] map into channels[*].messages so + _slack_channel_messages works regardless of where the mock stores them.""" + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, 'messageId': mid, 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'slack': + _materialize_slack(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward === +def reward(go): + hs = go('hubspot_marketing') + hs_i = hs.get('initial_state', {}) or {} + hs_c = hs.get('current_state', {}) or {} + + contacts_i = hs_i.get('contacts', []) or [] + contacts_c = {c.get('id'): c for c in (hs_c.get('contacts', []) or []) + if isinstance(c, dict)} + + # user id -> email (union of initial + current users tables) + id_to_email = {} + for u in (hs_i.get('users', []) or []) + (hs_c.get('users', []) or []): + if isinstance(u, dict) and u.get('id'): + id_to_email[u['id']] = norm(u.get('email')) + + def owner_email(contact): + """Resolve a contact's contactOwner to an email; if it already looks + like an email, use it directly.""" + ow = contact.get('contactOwner') + if ow is None: + return '' + if '@' in str(ow): + return norm(ow) + return id_to_email.get(ow, norm(ow)) + + routable = [c for c in contacts_i if isinstance(c, dict) and c.get('_tier')] + distractors = [c for c in contacts_i if isinstance(c, dict) and not c.get('_tier')] + + # ---- 1) hubspot stage+owner decision-set (0.35) ---- + correct = 0 + for c in routable: + cid = c.get('id') + cur = contacts_c.get(cid, {}) + stage_ok = norm(cur.get('lifecycleStage')) == norm(c.get('_expected_stage')) + owner_ok = owner_email(cur) == norm(c.get('_expected_owner_email')) + if stage_ok and owner_ok: + correct += 1 + + # wrongly-touched distractors: a leave-alone contact whose stage OR owner + # changed from its injected value -> inflates the denominator (precision leak) + wrong_touched = 0 + for c in distractors: + cid = c.get('id') + cur = contacts_c.get(cid, {}) + if not cur: + continue + if (norm(cur.get('lifecycleStage')) != norm(c.get('lifecycleStage')) + or owner_email(cur) != owner_email(c)): + wrong_touched += 1 + + dec_den = len(routable) + wrong_touched + dec_score = frac(correct, dec_den) + + # ---- Hot contacts (need briefing row + doc share) ---- + hot = [c for c in routable if c.get('_hot')] + n_hot = len(hot) + hot_ae_emails = {norm(c.get('_expected_owner_email')) for c in hot + if c.get('_expected_owner_email')} + + # ---- 2) Docs share F1 (hot AEs) (0.20) ---- + docs = go('google_docs') + docs_i = docs.get('initial_state', {}) or {} + docs_c = docs.get('current_state', {}) or {} + briefing_doc_id = docs_i.get('_task_briefing_doc_id') + + def _docs_id_to_email(state): + m = {} + for u in (state.get('users', []) or []): + if isinstance(u, dict) and u.get('id'): + m[u['id']] = norm(u.get('email')) + return m + + docs_id_email = {} + docs_id_email.update(_docs_id_to_email(docs_i)) + docs_id_email.update(_docs_id_to_email(docs_c)) + + docs_map_c = docs_c.get('documents', {}) if isinstance(docs_c.get('documents'), dict) else {} + brief_doc_c = docs_map_c.get(briefing_doc_id, {}) if isinstance(docs_map_c, dict) else {} + shared_emails = set() + for entry in (brief_doc_c.get('sharedWith', []) or []): + if isinstance(entry, dict): + em = docs_id_email.get(entry.get('userId'), norm(entry.get('userId'))) + if em: + shared_emails.add(em) + share_f1 = f1(hot_ae_emails, shared_emails) + + # ---- 3) Docs briefing-row recall (hot) (0.13) ---- + brief_body = _strip_html(brief_doc_c.get('content', '')).lower() + brief_hits = 0 + for c in hot: + first = norm(c.get('firstName')) + last = norm(c.get('lastName')) + if first and last and has_text(brief_body, first, last): + brief_hits += 1 + brief_score = frac(brief_hits, n_hot) + + # ---- 4) Drive move (0.14) ---- + drive = go('google_drive') + drive_i = drive.get('initial_state', {}) or {} + drive_c = drive.get('current_state', {}) or {} + brief_item_id = drive_i.get('_task_briefing_item_id') + handoff_folder_id = drive_i.get('_task_sales_handoff_folder_id') + items_c = drive_c.get('items', {}) if isinstance(drive_c.get('items'), dict) else {} + brief_item_c = items_c.get(brief_item_id, {}) if isinstance(items_c, dict) else {} + move_ok = (norm(brief_item_c.get('parentId')) == norm(handoff_folder_id) + and bool(handoff_folder_id)) + move_score = 1.0 if move_ok else 0.0 + + # ---- 5) Slack post to #marketing (0.13) ---- + slack = go('slack') + slack_c = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + mkt_msgs = _slack_channel_messages(slack_c, 'marketing') + _mkt_kw = ('sql', 'mql', 'unassigned', 'routed', 'routing', 'qualified') + def _is_mkt_summary(m): + t = (_msg_text(m) or '').lower() + return bool(t.strip()) and any(k in t for k in _mkt_kw) and any(c.isdigit() for c in t) + post_ok = any(_is_mkt_summary(m) for m in mkt_msgs if isinstance(m, dict)) + post_score = 1.0 if post_ok else 0.0 + + # ---- 6) Slack pin (gated) (0.05) ---- + mkt_ch = None + for ch in (slack_c.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == 'marketing': + mkt_ch = ch + break + pinned_ids = (mkt_ch.get('pinnedMessages') or []) if isinstance(mkt_ch, dict) else [] + mkt_msg_ids = {(m.get('messageId') or m.get('id')) + for m in mkt_msgs if isinstance(m, dict)} + pin_ok = bool(post_ok and any(pid in mkt_msg_ids for pid in pinned_ids)) + pin_score = 1.0 if pin_ok else 0.0 + + # ---- Combine ---- + s_dec = 0.35 * dec_score + s_share = 0.20 * share_f1 + s_brief = 0.13 * brief_score + s_move = 0.14 * move_score + s_post = 0.13 * post_score + s_pin = 0.05 * pin_score + score = s_dec + s_share + s_brief + s_move + s_post + s_pin + + print( + 'DEBUG_MKTG ' + f'routable={len(routable)} correct={correct} wrong_touched={wrong_touched} ' + f'dec_den={dec_den} dec_score={round(dec_score, 4)} ' + f'n_hot={n_hot} hot_aes={sorted(hot_ae_emails)} shared={sorted(shared_emails)} ' + f'share_f1={round(share_f1, 4)} brief_hits={brief_hits}/{n_hot} ' + f'brief_score={round(brief_score, 4)} move_ok={move_ok} ' + f'slack_post={post_ok} slack_pin={pin_ok} ' + f'w_dec={round(s_dec, 4)} w_share={round(s_share, 4)} w_brief={round(s_brief, 4)} ' + f'w_move={round(s_move, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} ' + f'total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/mktg_leadhandoff_002/_cua_gym_vm_bridge.sh b/mktg_leadhandoff_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_leadhandoff_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/mktg_leadhandoff_002/initial_setup.py b/mktg_leadhandoff_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9e042c65b881fd32c03590d751b1677b5fbb8058 --- /dev/null +++ b/mktg_leadhandoff_002/initial_setup.py @@ -0,0 +1,306 @@ +""" +Initial Setup: Product Demo Request lead handoff (HubSpot -> Airtable -> Slack) +Task ID: mktg_leadhandoff_001 +Domain: mock_websites +Mocks: hubspot_mock, airtable_mock, slack_mock + +Pre-task state: +- HubSpot CRM with 8 contacts in the 'mql' lifecycle stage (the Product Demo + Request campaign leads), each with owner = "Unassigned". Distractor contacts + in other lifecycle stages already have owners. A "Product Demo Request" lead + form (8 submissions) reinforces the campaign narrative. Jordan Blake is NOT + yet the owner of any MQL contact. +- Airtable base "RevOps" with a "Lead Handoff" table + (fields: Campaign, Lead Count, Assigned To, Handoff Date) containing one prior + unrelated handoff record. NO "Product Demo Request" record yet. +- Slack workspace with a #sales-handoff channel containing prior chatter. + Jordan Blake (@jordan) is a member. NO handoff message for this campaign yet. + +Isolation note: initial_env and golden_env are SEPARATE containers that share +the xlang.ai HTTP server. To keep their server states independent, each env +uses its OWN sid. initial_setup uses the '-init' sid; golden_patch uses +'-gold' and independently rebuilds the same baseline before applying its +changes (see golden_patch.py). reward.py on each VM reads the sid this script +(or golden_patch) writes to /tmp/task_web_sid. +""" + +import hashlib +import os +import shlex +import subprocess +import time + +import requests + +# --- Configuration --- +TASK_ID = 'mktg_leadhandoff_001' + +HUBSPOT_URL = 'http://28.7.184.198:8150' +AIRTABLE_URL = 'http://28.7.184.198:8109' +SLACK_URL = 'http://28.7.184.198:8178' + +_BASE = 'cua-' + hashlib.md5(TASK_ID.encode()).hexdigest()[:12] +SID = _BASE + '-init' # initial_env sid (distinct from golden_env) + +with open('/tmp/task_web_sid', 'w') as f: + f.write(SID) +print(f'Session ID (initial_env): {SID}') + + +# --------------------------------------------------------------------------- +# Shared baseline (pre-task) state builders. +# NOTE: golden_patch.py duplicates equivalent builders so that golden_env can +# independently reconstruct this exact baseline before applying its changes +# (Rule 1: no cross-env dependency). +# --------------------------------------------------------------------------- +def build_hubspot_state(): + companies = [ + {"id": "comp1", "name": "Brightwave Analytics", "domain": "brightwave.io", + "industry": "Technology", "phone": "+1 (555) 100-0001", "city": "Austin", + "state": "TX", "country": "United States", "numberOfEmployees": 120, + "annualRevenue": 8000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Analytics platform for product teams.", + "createDate": "2026-02-10T09:00:00Z"}, + {"id": "comp2", "name": "Northpeak Logistics", "domain": "northpeak.com", + "industry": "Manufacturing", "phone": "+1 (555) 100-0002", "city": "Denver", + "state": "CO", "country": "United States", "numberOfEmployees": 340, + "annualRevenue": 22000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Freight and supply-chain logistics.", + "createDate": "2026-02-15T09:00:00Z"}, + {"id": "comp3", "name": "Vertex Health", "domain": "vertexhealth.org", + "industry": "Healthcare", "phone": "+1 (555) 100-0003", "city": "Boston", + "state": "MA", "country": "United States", "numberOfEmployees": 210, + "annualRevenue": 15000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Patient engagement software.", + "createDate": "2026-03-01T09:00:00Z"}, + {"id": "comp4", "name": "Lumina Retail", "domain": "luminaretail.com", + "industry": "Other", "phone": "+1 (555) 100-0004", "city": "Chicago", + "state": "IL", "country": "United States", "numberOfEmployees": 95, + "annualRevenue": 6000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Omnichannel retail operations.", + "createDate": "2026-03-05T09:00:00Z"}, + ] + + mql_leads = [ + ("c1", "Daniel", "Brooks", "daniel.brooks@brightwave.io", "+1 (555) 010-1001", "VP Product", "comp1"), + ("c2", "Priya", "Raman", "priya.raman@brightwave.io", "+1 (555) 010-1002", "Head of Analytics", "comp1"), + ("c3", "Marcus", "Webb", "marcus.webb@northpeak.com", "+1 (555) 010-1003", "Operations Director", "comp2"), + ("c4", "Elena", "Foster", "elena.foster@northpeak.com", "+1 (555) 010-1004", "Logistics Manager", "comp2"), + ("c5", "Tobias", "Klein", "tobias.klein@vertexhealth.org", "+1 (555) 010-1005", "CTO", "comp3"), + ("c6", "Hannah", "Cole", "hannah.cole@vertexhealth.org", "+1 (555) 010-1006", "Product Lead", "comp3"), + ("c7", "Victor", "Nguyen", "victor.nguyen@luminaretail.com", "+1 (555) 010-1007", "Director of Digital", "comp4"), + ("c8", "Sofia", "Marenco", "sofia.marenco@luminaretail.com", "+1 (555) 010-1008", "Ecommerce Manager", "comp4"), + ] + contacts = [] + for cid, fn, ln, email, phone, title, comp in mql_leads: + contacts.append({ + "id": cid, "firstName": fn, "lastName": ln, "email": email, "phone": phone, + "jobTitle": title, "companyId": comp, "lifecycleStage": "mql", + "leadStatus": "open", "owner": "Unassigned", "city": "United States", + "state": "", "country": "United States", + "createDate": "2026-06-25T11:00:00Z", "lastActivityDate": "2026-06-28T16:00:00Z", + "timeline": [], + }) + + # Distractors — other lifecycle stages, already owned. The agent must NOT + # touch these. c11 is already owned by Jordan Blake (an SQL contact) to make + # naive "all Jordan contacts" reasoning insufficient. + distractors = [ + ("c9", "Alice", "Freeman", "alice@oldcorp.com", "+1 (555) 010-2001", "CFO", "comp1", "customer", "connected", "Admin User"), + ("c10", "Grace", "Liu", "grace.liu@northpeak.com", "+1 (555) 010-2002", "Analyst", "comp2", "lead", "new", "Admin User"), + ("c11", "Omar", "Haddad", "omar.haddad@vertexhealth.org", "+1 (555) 010-2003", "Engineering Manager", "comp3", "sql", "open_deal", "Jordan Blake"), + ("c12", "Nina", "Alvarez", "nina.alvarez@luminaretail.com", "+1 (555) 010-2004", "VP Marketing", "comp4", "opportunity", "open_deal", "Casey Morgan"), + ] + for cid, fn, ln, email, phone, title, comp, stage, ls, owner in distractors: + contacts.append({ + "id": cid, "firstName": fn, "lastName": ln, "email": email, "phone": phone, + "jobTitle": title, "companyId": comp, "lifecycleStage": stage, + "leadStatus": ls, "owner": owner, "city": "United States", "state": "", + "country": "United States", "createDate": "2026-01-20T10:00:00Z", + "lastActivityDate": "2026-06-20T14:00:00Z", "timeline": [], + }) + + deal_stages = { + "appointment_scheduled": {"id": "appointment_scheduled", "label": "Appointment Scheduled", "probability": 20, "color": "#E5F4FF", "order": 1}, + "qualified_to_buy": {"id": "qualified_to_buy", "label": "Qualified to Buy", "probability": 40, "color": "#FFF0E6", "order": 2}, + "presentation_scheduled": {"id": "presentation_scheduled", "label": "Presentation Scheduled", "probability": 60, "color": "#FFF8E6", "order": 3}, + "decision_maker_bought_in": {"id": "decision_maker_bought_in", "label": "Decision Maker Bought-In", "probability": 80, "color": "#E8F5E9", "order": 4}, + "contract_sent": {"id": "contract_sent", "label": "Contract Sent", "probability": 90, "color": "#E6FFFA", "order": 5}, + "closed_won": {"id": "closed_won", "label": "Closed Won", "probability": 100, "color": "#E6FFEC", "order": 6}, + "closed_lost": {"id": "closed_lost", "label": "Closed Lost", "probability": 0, "color": "#FFE6E6", "order": 7}, + } + ticket_statuses = { + "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1}, + "waiting_on_contact": {"id": "waiting_on_contact", "label": "Waiting on Contact", "color": "#FFF8E6", "order": 2}, + "waiting_on_us": {"id": "waiting_on_us", "label": "Waiting on Us", "color": "#FFF0E6", "order": 3}, + "in_progress": {"id": "in_progress", "label": "In Progress", "color": "#E6FFFA", "order": 4}, + "closed": {"id": "closed", "label": "Closed", "color": "#E6FFEC", "order": 5}, + } + + return { + "contacts": contacts, + "companies": companies, + "deals": [], + "tickets": [], + "tasks": [], + "notes": [], + "templates": [], + "meetings": [], + "forms": [ + {"id": "f1", "name": "Product Demo Request", "status": "active", + "submissions": 8, "fields": ["email", "first_name", "last_name", "company", "job_title"], + "createDate": "2026-06-20T10:00:00Z", "lastSubmission": "2026-06-28T16:00:00Z"}, + {"id": "f2", "name": "Newsletter Signup", "status": "active", + "submissions": 230, "fields": ["email"], + "createDate": "2026-01-10T10:00:00Z", "lastSubmission": "2026-06-29T09:00:00Z"}, + ], + "dealStages": deal_stages, + "ticketStatuses": ticket_statuses, + "appState": { + "sidebarOpen": True, + "currentUser": {"name": "Admin User", "email": "admin@example.com", "avatar": None}, + }, + } + + +def build_airtable_state(): + collaborators = [ + {"id": "user_1", "name": "John Doe", "email": "john.doe@example.com", + "avatar": "https://ui-avatars.com/api/?name=John+Doe&background=8B5CF6&color=fff"}, + {"id": "user_2", "name": "Alice Chen", "email": "alice.chen@example.com", + "avatar": "https://ui-avatars.com/api/?name=Alice+Chen&background=EC4899&color=fff"}, + ] + fields = [ + {"id": "fld_campaign", "name": "Campaign", "type": "text", "primary": True}, + {"id": "fld_count", "name": "Lead Count", "type": "number"}, + {"id": "fld_assigned", "name": "Assigned To", "type": "text"}, + {"id": "fld_date", "name": "Handoff Date", "type": "date"}, + ] + records = [ + {"id": "rec_prior_1", "createdTime": "2026-06-10T09:30:00.000Z", + "fields": {"fld_campaign": "Spring Newsletter Signups", "fld_count": 5, + "fld_assigned": "Casey Morgan", "fld_date": "2026-06-10"}}, + ] + return { + "currentUser": collaborators[0], + "collaborators": collaborators, + "bases": {"base_revops": {"id": "base_revops", "name": "RevOps", + "color": "bg-teal-600", "tables": ["tbl_handoff"]}}, + "tables": {"tbl_handoff": { + "id": "tbl_handoff", "name": "Lead Handoff", "baseId": "base_revops", + "fields": fields, "records": records, + "views": [{"id": "view_grid", "name": "All Handoffs", "type": "grid", + "filters": [], "sorts": [], "groupBy": [], "hiddenFieldIds": [], + "fieldWidths": {}, "rowHeight": "short"}], + "activeViewId": "view_grid"}}, + "activeBaseId": "base_revops", + "activeTableId": "tbl_handoff", + "ui": {"viewSidebarOpen": False, "expandedRecordId": None, + "searchQuery": "", "isSearching": False}, + } + + +def build_slack_state(): + users = [ + {"userId": "user_1", "fullName": "Maya Patel", "displayName": "maya", + "email": "maya.patel@company.com", "avatar": "https://picsum.photos/200/200?random=1", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_2", "fullName": "Jordan Blake", "displayName": "jordan", + "email": "jordan.blake@company.com", "avatar": "https://picsum.photos/200/200?random=2", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"}, + {"userId": "user_3", "fullName": "Casey Morgan", "displayName": "casey", + "email": "casey.morgan@company.com", "avatar": "https://picsum.photos/200/200?random=3", + "status": "away", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"}, + {"userId": "user_4", "fullName": "Dana Reed", "displayName": "dana", + "email": "dana.reed@company.com", "avatar": "https://picsum.photos/200/200?random=4", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + ] + return { + "currentUser": users[0], + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme RevOps", "icon": ""}, + "users": users, + "channels": [ + {"channelId": "sales-handoff", "name": "sales-handoff", + "description": "Marketing-to-sales lead handoffs", "topic": "Qualified leads ready for sales", + "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_1", + "createdAt": "2026-05-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "general", "name": "general", "description": "General chat", "topic": "", + "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3", "user_4"], + "createdBy": "user_1", "createdAt": "2026-05-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "sales-handoff": [ + {"messageId": "msg_h1", "senderId": "user_3", + "content": "Handed off the 5 Spring Newsletter leads earlier this month — @jordan let me know if you need the list again.", + "timestamp": "2026-06-10T09:35:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + {"messageId": "msg_h2", "senderId": "user_2", + "content": "Got them, thanks Casey. Following up this week.", + "timestamp": "2026-06-10T10:00:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + "general": [ + {"messageId": "msg_g1", "senderId": "user_4", "content": "Morning team!", + "timestamp": "2026-06-30T08:00:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + + +# --------------------------------------------------------------------------- +# Inject baseline state under the initial_env sid (action: set). +# --------------------------------------------------------------------------- +MOCKS = { + HUBSPOT_URL: build_hubspot_state(), + AIRTABLE_URL: build_airtable_state(), + SLACK_URL: build_slack_state(), +} + +print("Resetting any stale state and injecting initial state...") +for url, state in MOCKS.items(): + requests.post(f'{url}/post?sid={SID}', json={'action': 'reset'}, timeout=30) + r = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': state}, timeout=30) + r.raise_for_status() + print(f"OK: injected {url}") + +# --- Verify --- +print("Verifying state injection...") +hs_go = requests.get(f'{HUBSPOT_URL}/go?sid={SID}', timeout=10).json() +assert hs_go['initial_state'] is not None, 'HubSpot initial_state is None' +mql = [c for c in hs_go['current_state']['contacts'] if c['lifecycleStage'] == 'mql'] +assert len(mql) == 8, f'Expected 8 MQL contacts, got {len(mql)}' +assert all(c['owner'] == 'Unassigned' for c in mql), 'Some MQL contacts already have an owner' +# Pre-task: no Product Demo Request handoff record, no handoff message yet. +at_go = requests.get(f'{AIRTABLE_URL}/go?sid={SID}', timeout=10).json() +campaigns = [r['fields'].get('fld_campaign') for r in at_go['current_state']['tables']['tbl_handoff']['records']] +assert 'Product Demo Request' not in campaigns, 'Handoff record already present in initial state' +sl_go = requests.get(f'{SLACK_URL}/go?sid={SID}', timeout=10).json() +assert len(sl_go['current_state']['messages']['sales-handoff']) == 2, 'Unexpected #sales-handoff message count' +print(f"OK: verified 8 unassigned MQL contacts, no handoff record, no handoff message") + +# --------------------------------------------------------------------------- +# Launch browsers (GUI-ready start state) +# --------------------------------------------------------------------------- +def launch_gui(command: str, delay_sec: float = 1.0): + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + +print("Launching browsers...") +launch_gui(f'google-chrome "{HUBSPOT_URL}/?sid={SID}"', delay_sec=2.0) +launch_gui(f'google-chrome "{AIRTABLE_URL}/?sid={SID}"', delay_sec=1.5) +launch_gui(f'google-chrome "{SLACK_URL}/?sid={SID}"', delay_sec=1.0) +print('GUI_READY: launched HubSpot, Airtable and Slack mock websites with DISPLAY=:0') +print(f'Session ID: {SID}') diff --git a/mktg_leadhandoff_002/reward.py b/mktg_leadhandoff_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..77415345bead0e055e6be78f4b2c52c3dddb15c2 --- /dev/null +++ b/mktg_leadhandoff_002/reward.py @@ -0,0 +1,244 @@ +""" +Reward Script: Lead handoff — reassign 8 MQL contacts to Jordan Blake in HubSpot, +log the handoff in Airtable 'Lead Handoff', and notify @jordan in Slack #sales-handoff. +Task ID: mktg_leadhandoff_001 +Domain: mock_websites (multi-mock: hubspot + airtable + slack) + +Scoring (all structural / deterministic — no LLM judge needed): + Component 1 — HubSpot reassignment 0.40 + Component 2 — Airtable 'Lead Handoff' record 0.35 + Component 3 — Slack #sales-handoff message 0.25 + Total 1.00 + +Each component verifies a TASK-INTRODUCED change (fails on initial_env, passes on +golden_env). Target contacts are derived from the task description ("8 contacts in +MQL lifecycle stage, none yet assigned an owner") against the INITIAL state, not by +peeking at the golden answer. +""" +import datetime +import sys + +import requests + +HUBSPOT_URL = 'http://28.7.184.198:8150' +AIRTABLE_URL = 'http://28.7.184.198:8109' +SLACK_URL = 'http://28.7.184.198:8178' + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def fetch(base_url): + """Fetch /go state for a mock. Returns (initial, current) or (None, None) on failure.""" + try: + data = requests.get(f'{base_url}/go?sid={sid}', timeout=20).json() + except Exception as e: + print(f'ERROR: cannot fetch {base_url}: {e}') + return None, None + return data.get('initial_state') or {}, data.get('current_state') or {} + + +def verify_task(): + total_score = 0.0 + + # ===================== Component 1: HubSpot reassignment (0.40) ===================== + # Derive the target set from the task: contacts that in the INITIAL state are in the + # 'mql' lifecycle stage AND have no owner assigned ("Unassigned"). The task says these + # 8 must be reassigned to owner == "Jordan Blake". We anchor to the change, and also + # guard against over-assignment (contacts that should NOT have been touched). + try: + hs_init, hs_cur = fetch(HUBSPOT_URL) + if hs_cur is None or not hs_cur.get('contacts'): + print('FAIL: Component 1 — could not read HubSpot contacts') + else: + init_contacts = {c['id']: c for c in hs_init.get('contacts', [])} + cur_contacts = {c['id']: c for c in hs_cur.get('contacts', [])} + + def is_unassigned(owner): + return (owner or '').strip().lower() in ('', 'unassigned', 'none') + + # Target contacts (from task requirement, evaluated on INITIAL state) + targets = [ + cid for cid, c in init_contacts.items() + if (c.get('lifecycleStage') or '').lower() == 'mql' and is_unassigned(c.get('owner')) + ] + n_targets = len(targets) + + # How many targets are now owned by Jordan Blake? + correct = [ + cid for cid in targets + if (cur_contacts.get(cid, {}).get('owner') or '').strip().lower() == 'jordan blake' + ] + + # Over-assignment guard: contacts NOT in the target set whose owner newly + # became 'Jordan Blake' (were not Jordan in initial). These should not exist. + extras = [] + for cid, c in cur_contacts.items(): + if cid in targets: + continue + cur_owner = (c.get('owner') or '').strip().lower() + init_owner = (init_contacts.get(cid, {}).get('owner') or '').strip().lower() + if cur_owner == 'jordan blake' and init_owner != 'jordan blake': + extras.append(cid) + + if n_targets == 0: + print('FAIL: Component 1 — no MQL/unassigned target contacts found in initial state') + else: + base = 0.40 * (len(correct) / n_targets) + # Penalize over-assignment: halve the component if unrelated contacts were + # reassigned to Jordan (task says "No other contacts ... are affected"). + if extras: + base *= 0.5 + print(f'WARN: Component 1 — over-assignment to Jordan on non-target contacts: {extras}') + total_score += base + print(f'{"PASS" if len(correct)==n_targets and not extras else "PARTIAL"}: ' + f'Component 1 — {len(correct)}/{n_targets} target MQL contacts reassigned to ' + f'Jordan Blake ({base:.3f} pts). targets={sorted(targets)}') + except Exception as e: + print(f'ERROR: Component 1 — {e}') + + # ===================== Component 2: Airtable 'Lead Handoff' record (0.35) ===================== + # A NEW record in the 'Lead Handoff' table with: + # Campaign = 'Product Demo Request', Lead Count = 8, + # Assigned To = 'Jordan Blake', Handoff Date = today. + # Sub-scores: campaign 0.15, count 0.08, assigned 0.07, date 0.05. + try: + at_init, at_cur = fetch(AIRTABLE_URL) + if at_cur is None or not at_cur.get('tables'): + print('FAIL: Component 2 — could not read Airtable tables') + else: + def find_handoff_table(state): + for tid, t in state.get('tables', {}).items(): + if t.get('name', '').strip().lower() == 'lead handoff': + return t + return None + + init_tbl = find_handoff_table(at_init) + cur_tbl = find_handoff_table(at_cur) + if cur_tbl is None: + print('FAIL: Component 2 — Lead Handoff table not found') + else: + # Map field names -> field ids (resilient to id naming) + fid = {f.get('name', '').strip().lower(): f['id'] for f in cur_tbl.get('fields', [])} + f_campaign = fid.get('campaign') + f_count = fid.get('lead count') + f_assigned = fid.get('assigned to') + f_date = fid.get('handoff date') + + init_ids = {r['id'] for r in (init_tbl.get('records', []) if init_tbl else [])} + new_records = [r for r in cur_tbl.get('records', []) if r['id'] not in init_ids] + + today = datetime.date.today().isoformat() + + def norm(v): + return str(v).strip().lower() if v is not None else '' + + # Find the best-matching new record (one mentioning the campaign) + target_rec = None + for r in new_records: + fields = r.get('fields', {}) + if f_campaign and 'product demo request' in norm(fields.get(f_campaign)): + target_rec = r + break + if target_rec is None and new_records: + # fall back to any new record for partial credit on other fields + target_rec = new_records[0] + + if target_rec is None: + print('FAIL: Component 2 — no new record added to Lead Handoff table') + else: + flds = target_rec.get('fields', {}) + # Campaign (0.15) + if f_campaign and 'product demo request' in norm(flds.get(f_campaign)): + total_score += 0.15 + print('PASS: Component 2a — Campaign = Product Demo Request (0.15 pts)') + else: + print(f'FAIL: Component 2a — Campaign mismatch: {flds.get(f_campaign)!r}') + # Lead Count (0.08) + try: + if f_count and int(float(flds.get(f_count))) == 8: + total_score += 0.08 + print('PASS: Component 2b — Lead Count = 8 (0.08 pts)') + else: + print(f'FAIL: Component 2b — Lead Count != 8: {flds.get(f_count)!r}') + except Exception: + print(f'FAIL: Component 2b — Lead Count not numeric: {flds.get(f_count)!r}') + # Assigned To (0.07) + if f_assigned and norm(flds.get(f_assigned)) == 'jordan blake': + total_score += 0.07 + print('PASS: Component 2c — Assigned To = Jordan Blake (0.07 pts)') + else: + print(f'FAIL: Component 2c — Assigned To mismatch: {flds.get(f_assigned)!r}') + # Handoff Date = today (0.05) + if f_date and norm(flds.get(f_date)) == today: + total_score += 0.05 + print(f'PASS: Component 2d — Handoff Date = today ({today}) (0.05 pts)') + else: + print(f'FAIL: Component 2d — Handoff Date != today ({today}): {flds.get(f_date)!r}') + except Exception as e: + print(f'ERROR: Component 2 — {e}') + + # ===================== Component 3: Slack #sales-handoff message (0.25) ===================== + # A NEW message in the #sales-handoff channel that mentions @jordan and references + # following up on the new leads. + # Sub-scores: new message mentioning @jordan 0.15, references follow-up of leads 0.10. + try: + sl_init, sl_cur = fetch(SLACK_URL) + if sl_cur is None or not sl_cur.get('channels'): + print('FAIL: Component 3 — could not read Slack state') + else: + # Resolve #sales-handoff channelId + ch_id = None + for ch in sl_cur.get('channels', []): + if ch.get('name', '').strip().lower() == 'sales-handoff': + ch_id = ch.get('channelId') + break + if ch_id is None: + print('FAIL: Component 3 — #sales-handoff channel not found') + else: + init_msgs = sl_init.get('messages', {}).get(ch_id, []) + cur_msgs = sl_cur.get('messages', {}).get(ch_id, []) + new_msgs = cur_msgs[len(init_msgs):] if len(cur_msgs) > len(init_msgs) else [] + + if not new_msgs: + print('FAIL: Component 3 — no new message in #sales-handoff') + else: + # Sub 3a: a new message mentioning @jordan (0.15) + mention_msgs = [m for m in new_msgs if '@jordan' in (m.get('content') or '').lower()] + if mention_msgs: + total_score += 0.15 + print('PASS: Component 3a — new #sales-handoff message mentions @jordan (0.15 pts)') + else: + print('FAIL: Component 3a — new message(s) exist but none mention @jordan') + + # Sub 3b: that message references following up on the leads (0.10) + # Deterministic: content references "follow" up AND ("8" leads or "lead"). + def references_followup(text): + t = (text or '').lower() + has_follow = 'follow' in t + has_leads = ('lead' in t) or ('8' in t) + return has_follow and has_leads + candidates = mention_msgs if mention_msgs else new_msgs + if any(references_followup(m.get('content')) for m in candidates): + total_score += 0.10 + print('PASS: Component 3b — message asks Jordan to follow up on the leads (0.10 pts)') + else: + print('FAIL: Component 3b — message does not clearly ask to follow up on the (8) leads') + except Exception as e: + print(f'ERROR: Component 3 — {e}') + + final_score = round(min(total_score, 1.0), 4) + print(f'\nScore: {total_score:.4f}/1.0') + print(f'REWARD: {final_score}') + return final_score + + +verify_task() diff --git a/mktg_leadhandoff_002/reward_label.json b/mktg_leadhandoff_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..8f94a9351c9aa3fe174bf46e1181c57db212d88f --- /dev/null +++ b/mktg_leadhandoff_002/reward_label.json @@ -0,0 +1,57 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/mktg_leadhandoff_001_v2/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:27:47", + "label": { + "task_id": "mktg_leadhandoff_001", + "domain": "mock_websites", + "summary": "验证将8个MQL联系人重新分配给Jordan Blake、在Airtable的Lead Handoff表中记录交接信息,并在Slack的#sales-handoff频道通知@jordan的任务行为", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "hubspot_mock (http://28.7.186.212:8170)", + "airtable_mock (http://28.7.186.212:8129)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Component 1: HubSpot reassignment", + "weight": 0.4, + "description": "检查初始状态中为MQL且未分配负责人的目标联系人是否被重新分配给Jordan Blake,且无过度分配", + "check_logic": "从hs_init中筛选 lifecycleStage == 'mql' 且 owner 为未分配(空/unassigned/none)的联系人作为targets;计算targets中当前owner为'jordan blake'的比例,乘以0.40作为base;遍历非target联系人,若当前owner为'jordan blake'且初始不是,则判定为over-assignment,base乘以0.5惩罚", + "pass_condition": "所有目标MQL未分配联系人都被分配给Jordan Blake,且没有其他联系人被错误分配给Jordan Blake" + }, + { + "name": "Component 2: Airtable 'Lead Handoff' record", + "weight": 0.35, + "description": "检查Airtable的Lead Handoff表中是否新增了符合要求的记录", + "check_logic": "对比at_init和at_cur找出Lead Handoff表中的新记录(id不在init_ids中);优先选取fields中Campaign字段包含'product demo request'的记录,否则取第一条新记录;逐项检查Campaign(0.15)、Lead Count是否为8(0.08)、Assigned To是否为'jordan blake'(0.07)、Handoff Date是否为今天(0.05)并累加", + "pass_condition": "新增记录包含Campaign为Product Demo Request、Lead Count为8、Assigned To为Jordan Blake、Handoff Date为当天" + }, + { + "name": "Component 3: Slack #sales-handoff message", + "weight": 0.25, + "description": "检查Slack的#sales-handoff频道是否有新增消息提及@jordan并要求跟进线索", + "check_logic": "通过对比init_msgs和cur_msgs获取#sales-handoff频道的新消息;检查new_msgs中是否有内容包含'@jordan'(0.15);在mention_msgs(若无则取全部new_msgs)中检查是否有消息内容同时包含'follow'和('lead'或'8')(0.10)", + "pass_condition": "有新增消息提及@jordan,且内容要求跟进8个线索" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件及子项分数直接累加,最终用 round(min(total_score, 1.0), 4) 钳制到上限1.0并输出", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,直接输出 REWARD: 0.0 并 sys.exit(0)", + "任一 mock 服务 fetch 失败(返回None):对应组件无法评分,该组件得0分", + "HubSpot 初始状态无 MQL/unassigned 目标联系人:Component 1 失败", + "HubSpot 非目标联系人被过度分配给 Jordan Blake:Component 1 基础分乘以0.5", + "Airtable 中 Lead Handoff 表不存在或无新记录:Component 2 失败", + "Slack 中 #sales-handoff 频道不存在或无新消息:Component 3 失败", + "Slack 新消息未提及 @jordan:Component 3a 不得分", + "Slack 消息未包含 follow 和 lead/8 关键词:Component 3b 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接返回0.0并退出。随后分别向三个mock服务获取initial_state和current_state。Component 1 从HubSpot初始状态中自动推导出处于MQL生命周期阶段且未分配负责人的联系人作为目标集,按正确分配给Jordan Blake的比例计算0.40基础分;若存在非目标联系人被过度分配给Jordan Blake,则基础分减半。Component 2 在Airtable的Lead Handoff表中查找新增记录,按Campaign(0.15)、Lead Count(0.08)、Assigned To(0.07)、Handoff Date(0.05)四个子项逐项加分。Component 3 在Slack的#sales-handoff频道检查新增消息,按是否提及@jordan(0.15)和是否要求跟进线索(0.10)加分。所有子分数累加后,最终用min(total_score, 1.0)钳制并四舍五入到4位小数作为最终REWARD输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: mktg_leadhandoff_001(从 docstring 中明确提取)\n - Domain: mock_websites (multi-mock: hubspot + airtable + slack)(从 docstring 中提取)\n - Summary: 验证将8个MQL联系人重新分配给Jordan Blake,在Airtable中记录交接,并在Slack中通知@jordan的任务行为。\n\n2. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - HubSpot mock:`http://28.7.186.212:8170`\n - Airtable mock:`http://28.7.186.212:8129`\n - Slack mock:`http://28.7.186.212:8198`\n\n3. **评分组件**:\n\n **Component 1 (0.40)**:HubSpot 重新分配\n - 从初始状态找出 lifecycleStage == 'mql' 且 owner 为未分配(空/unassigned/none)的联系人作为目标\n - 检查这些目标联系人当前是否被分配给 \"Jordan Blake\"\n - 检查是否有非目标联系人被错误分配给 Jordan Blake(过度分配惩罚)\n - 基础分 = 0.40 * (正确分配的目标数 / 目标总数)\n - 如果存在过度分配,基础分减半\n - 如果初始状态没有目标联系人,失败\n\n **Component 2 (0.35)**:Airtable 'Lead Handoff' 记录\n - 在 'Lead Handoff' 表中查找新记录(与初始状态对比)\n - 优先找 Campaign 包含 'product demo request' 的新记录,否则取第一个新记录\n - 子分数:\n - Campaign = 'Product Demo Request':0.15\n - Lead Count = 8:0.08\n - Assigned To = 'Jordan Blake':0.07\n - Handoff Date = 今天:0.05\n - 如果没有新记录,全部失败\n\n **Component 3 (0.25)**:Slack #sales-handoff 消息\n - 在 #sales-handoff 频道查找新消息\n - 子分数:\n - 新消息提到 @jordan:0.15\n - 消息内容包含 \"follow\" 且包含 \"lead\" 或 \"8\":0.10\n - 如果存在 @jordan 的消息,从中检查 follow-up;否则从所有新消息中检查\n\n4. **分数汇总**:\n - 各组件分数相加\n - 最终分数 = round(min(total_score, 1.0), 4)\n - 钳制到 1.0\n\n5. **失败模式**:\n - 读取 sid 失败(/tmp/task_web_sid 不存在或为空):打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - fetch 失败(任何 mock 服务无法连接):对应组件失败,得 0 分\n - HubSpot:当前状态无联系人、无目标 MQL 联系人、过度分配(扣分)\n - Airtable:表不存在、无新记录、字段不匹配\n - Slack:频道不存在、无新消息、消息不包含 @jordan 或 follow-up 关键词\n\n6. **is_placeholder**:false,因为脚本进行了详细的状态检查和评分。\n\n7. **confidence**:1.0,因为代码逻辑清晰完整。\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"mktg_leadhandoff_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证将8个MQL联系人重新分配给Jordan Blake、在Airtable的Lead Handoff表中记录交接信息,并在Slack的#sales-handoff频道通知@jordan的任务行为\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"hubspot_mock (http://28.7.186.212:8170)\", \"airtable_mock (http://28.7.186.212:8129)\", \"slack_mock (http://28.7.186.212:8198)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1: HubSpot reassignment\",\n \"weight\": 0.40,\n \"description\": \"检查初始状态中为MQL且未分配负责人的8个目标联系人是否被重新分配给Jordan Blake,且无过度分配\",\n \"check_logic\": \"从初始状态筛选 lifecycleStage == 'mql' 且 owner 为未分配(空/unassigned/none)的联系人作为目标集;计算当前状态中这些目标集联系人 owner == 'jordan blake' 的比例作为基础分;检查非目标联系人是否有 owner 被改为 'jordan blake',若有则基础分乘以0.5惩罚\",\n \"pass_condition\": \"所有目标MQL未分配联系人都被分配给Jordan Blake,且没有其他联系人被错误分配给Jordan Blake\"\n },\n {\n \"name\": \"Component 2: Airtable 'Lead Handoff' record\",\n \"weight\": 0.35,\n \"description\": \"检查Airtable的Lead Handoff表中是否新增了符合要求的记录\",\n \"check_logic\": \"对比初始和当前状态找出Lead Handoff表中的新记录;优先匹配Campaign包含'product demo request'的记录;逐项检查Campaign(0.15)、Lead Count是否为8(0.08)、Assigned To是否为Jordan Blake(0.07)、Handoff Date是否为今天(0.05)\",\n \"pass_condition\": \"新增记录包含Campaign为Product Demo Request、Lead Count为8、Assigned To为Jordan Blake、Handoff Date为当天\"\n },\n {\n \"name\": \"Component 3: Slack #sales-handoff message\",\n \"weight\": 0.25,\n \"description\": \"检查Slack的#sales-handoff频道是否有新增消息提及@jordan并要求跟进线索\",\n \"check_logic\": \"获取#sales-handoff频道的新消息(当前消息列表长度大于初始的部分);检查是否有消息内容包含'@jordan'(0.15);检查消息内容是否同时包含'follow'和'lead'或'8'(0.10),优先从提及@jordan的消息中检查,否则从所有新消息检查\",\n \"pass_condition\": \"有新增消息提及@jordan,且内容要求跟进8个线索\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 round(min(total_score, 1.0), 4) 钳制到上限1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,直接返回 0.0 并退出\",\n \"任一 mock 服务 fetch 失败:对应组件无法评分,该组件得 0 分\",\n \"HubSpot 初始状态无 MQL/unassigned 目标联系人:Component 1 失败\",\n \"HubSpot 非目标联系人被过度分配给 Jordan Blake:Component 1 基础分减半\",\n \"Airtable 中 Lead Handoff 表不存在或无新记录:Component 2 失败\",\n \"Slack 中 #sales-handoff 频道不存在或无新消息:Component 3 失败\",\n \"Slack 新消息未提及 @jordan 或未包含跟进线索的关键词:对应子项不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接返回0.0。随后分别向三个mock服务(HubSpot、Airtable、Slack)获取初始状态和当前状态。Component 1 从HubSpot初始状态中自动推导出8个MQL且未分配的联系人作为目标集,按正确分配给Jordan Blake的比例计算0.40基础分,若存在非目标联系人被过度分配则基础分减半。Component 2 在Airtable的Lead Handoff表中查找新增记录,按Campaign(0.15)、Lead Count(0.08)、Assigned To(0.07)、Handoff Date(0.05)四个子项逐项加分。Component 3 在Slack的#sales-handoff频道检查新增消息,按是否提及@jordan(0.15)和是否要求跟进线索(0.10)加分。所有子分数累加后,最终用min(total_score, 1.0)钳制并四舍五入到4位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON 对象,不要 Markdown 代码块标记\n- 不要额外解释\n- 不要思考过程\n- 不要输出 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n确认 JSON 格式正确,没有多余内容。 {\n \"task_id\": \"mktg_leadhandoff_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证将8个MQL联系人重新分配给Jordan Blake、在Airtable的Lead Handoff表中记录交接信息,并在Slack的#sales-handoff频道通知@jordan的任务行为\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"hubspot_mock (http://28.7.186.212:8170)\", \"airtable_mock (http://28.7.186.212:8129)\", \"slack_mock (http://28.7.186.212:8198)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1: HubSpot reassignment\",\n \"weight\": 0.40,\n \"description\": \"检查初始状态中为MQL且未分配负责人的目标联系人是否被重新分配给Jordan Blake,且无过度分配\",\n \"check_logic\": \"从hs_init中筛选 lifecycleStage == 'mql' 且 owner 为未分配(空/unassigned/none)的联系人作为targets;计算targets中当前owner为'jordan blake'的比例,乘以0.40作为base;遍历非target联系人,若当前owner为'jordan blake'且初始不是,则判定为over-assignment,base乘以0.5惩罚\",\n \"pass_condition\": \"所有目标MQL未分配联系人都被分配给Jordan Blake,且没有其他联系人被错误分配给Jordan Blake\"\n },\n {\n \"name\": \"Component 2: Airtable 'Lead Handoff' record\",\n \"weight\": 0.35,\n \"description\": \"检查Airtable的Lead Handoff表中是否新增了符合要求的记录\",\n \"check_logic\": \"对比at_init和at_cur找出Lead Handoff表中的新记录(id不在init_ids中);优先选取fields中Campaign字段包含'product demo request'的记录,否则取第一条新记录;逐项检查Campaign(0.15)、Lead Count是否为8(0.08)、Assigned To是否为'jordan blake'(0.07)、Handoff Date是否为今天(0.05)并累加\",\n \"pass_condition\": \"新增记录包含Campaign为Product Demo Request、Lead Count为8、Assigned To为Jordan Blake、Handoff Date为当天\"\n },\n {\n \"name\": \"Component 3: Slack #sales-handoff message\",\n \"weight\": 0.25,\n \"description\": \"检查Slack的#sales-handoff频道是否有新增消息提及@jordan并要求跟进线索\",\n \"check_logic\": \"通过对比init_msgs和cur_msgs获取#sales-handoff频道的新消息;检查new_msgs中是否有内容包含'@jordan'(0.15);在mention_msgs(若无则取全部new_msgs)中检查是否有消息内容同时包含'follow'和('lead'或'8')(0.10)\",\n \"pass_condition\": \"有新增消息提及@jordan,且内容要求跟进8个线索\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件及子项分数直接累加,最终用 round(min(total_score, 1.0), 4) 钳制到上限1.0并输出\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,直接输出 REWARD: 0.0 并 sys.exit(0)\",\n \"任一 mock 服务 fetch 失败(返回None):对应组件无法评分,该组件得0分\",\n \"HubSpot 初始状态无 MQL/unassigned 目标联系人:Component 1 失败\",\n \"HubSpot 非目标联系人被过度分配给 Jordan Blake:Component 1 基础分乘以0.5\",\n \"Airtable 中 Lead Handoff 表不存在或无新记录:Component 2 失败\",\n \"Slack 中 #sales-handoff 频道不存在或无新消息:Component 3 失败\",\n \"Slack 新消息未提及 @jordan:Component 3a 不得分\",\n \"Slack 消息未包含 follow 和 lead/8 关键词:Component 3b 不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接返回0.0并退出。随后分别向三个mock服务获取initial_state和current_state。Component 1 从HubSpot初始状态中自动推导出处于MQL生命周期阶段且未分配负责人的联系人作为目标集,按正确分配给Jordan Blake的比例计算0.40基础分;若存在非目标联系人被过度分配给Jordan Blake,则基础分减半。Component 2 在Airtable的Lead Handoff表中查找新增记录,按Campaign(0.15)、Lead Count(0.08)、Assigned To(0.07)、Handoff Date(0.05)四个子项逐项加分。Component 3 在Slack的#sales-handoff频道检查新增消息,按是否提及@jordan(0.15)和是否要求跟进线索(0.10)加分。所有子分数累加后,最终用min(total_score, 1.0)钳制并四舍五入到4位小数作为最终REWARD输出。\",\n \"confidence\": 1.0\n}" +} diff --git a/mktg_report_003/_cua_gym_vm_bridge.sh b/mktg_report_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_report_003/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/mktg_report_003/initial_setup.py b/mktg_report_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7d7235ee559d9f2481d76e0d34b2252531a26427 --- /dev/null +++ b/mktg_report_003/initial_setup.py @@ -0,0 +1,158 @@ +""" +Initial Setup: Spring Nurture campaign metrics — transcribe into 'Campaign Performance' + Google Sheet, then post a one-line summary in Slack #marketing. +Task ID: mktg_report_003 +Domain: mock_websites (google_sheets + slack) + +The three target metrics (MQLs=142, open rate=38.5%, conversion rate=4.2%) are +given directly in the instruction (there is no readable HubSpot campaign mock), +so the agent's job is to transcribe them into the sheet and summarize in Slack. + +Pre-task state (so reward scores ONLY task-introduced deltas): + - Google Sheets: 'Campaign Performance' workbook. The 'Spring Nurture' row has + EMPTY MQLs / Open Rate / Conversion Rate cells. Other rows are filled. + - Slack: #marketing channel with prior chatter, NO metrics summary yet. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +SHEETS_URL = 'http://28.7.184.198:8145' +SLACK_URL = 'http://28.7.184.198:8178' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated session ID: {sid}') + + +# ===================================================================== +# Google Sheets — 'Campaign Performance'; Spring Nurture metrics empty. +# ===================================================================== +def build_sheets_state(): + headers = ['Campaign', 'MQLs', 'Open Rate', 'Conversion Rate', 'Notes'] + # (campaign, mqls, open_rate_fraction, conv_rate_fraction, notes) — None = empty cell + rows = [ + ['Winter Re-engagement', 98, 0.312, 0.028, 'Q4 win-back series'], + ['Spring Nurture', None, None, None, 'Lead nurture drip, 5 emails'], + ['Product Launch Blast', 215, 0.441, 0.061, 'New SKU announcement'], + ['Webinar Follow-up', 64, 0.503, 0.072, 'Post-event sequence'], + ['Holiday Promo', 187, 0.366, 0.039, 'Seasonal discount push'], + ['Referral Drive', 41, 0.289, 0.051, 'Customer referral asks'], + ['Onboarding Series', 130, 0.477, 0.084, 'New customer education'], + ] + + def col_letter(idx): + return chr(ord('A') + idx) + + data = {} + for c, h in enumerate(headers): + data[f'{col_letter(c)}1'] = { + 'value': h, 'formula': h, + 'style': {'bold': True, 'bg': '#4472C4', 'align': 'center'}, + } + for r, row in enumerate(rows, start=2): + for c, val in enumerate(row): + if val is None: + continue # leave metric cell empty for the agent to fill + cell = f'{col_letter(c)}{r}' + entry = {'value': str(val), 'formula': str(val)} + if c in (2, 3): # Open Rate / Conversion Rate -> percentage + entry['format'] = 'percent' + data[cell] = entry + + sheet = { + 'id': 'sheet_1', 'name': 'Campaign Performance', + 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0, + 'tabColor': None, 'isHidden': False, + 'columnWidths': {'0': 170, '1': 80, '2': 100, '3': 120, '4': 200}, + 'data': data, + } + return { + 'id': 'workbook_1', 'title': 'Campaign Performance', 'activeSheetId': 'sheet_1', + 'selectedCell': 'A1', 'selectionRange': None, 'clipboard': None, 'isDragging': False, + 'undoStack': [], 'redoStack': [], 'namedRanges': [], 'conditionalFormats': [], + 'charts': [], 'showGridlines': True, 'showFormulas': False, 'zoom': 100, + 'sheets': [sheet], + } + + +# ===================================================================== +# Slack — #marketing with prior chatter; no metrics summary yet. +# ===================================================================== +def build_slack_state(): + u1 = {'userId': 'user_1', 'fullName': 'Morgan Lee', 'displayName': 'Morgan', + 'email': 'morgan.lee@company.com', 'avatar': '', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'} + u2 = {'userId': 'user_2', 'fullName': 'Dana Cruz', 'displayName': 'Dana', + 'email': 'dana.cruz@company.com', 'avatar': '', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'} + return { + 'currentUser': u1, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Company Marketing', 'icon': ''}, + 'users': [u1, u2], + 'channels': [ + {'channelId': 'marketing', 'name': 'marketing', 'description': 'Marketing team', + 'topic': 'Campaigns & reporting', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2'], 'createdBy': 'user_1', + 'createdAt': '2026-01-02T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide', + 'topic': '', 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_2'], 'createdBy': 'user_1', + 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'messages': { + 'marketing': [ + {'messageId': 'msg_m1', 'senderId': 'user_2', + 'content': 'Can someone drop the Spring Nurture numbers into the Campaign Performance sheet?', + 'timestamp': '2026-06-29T15:00:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'general': [], + }, + 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], 'notifications': [], + } + + +# ===================================================================== +# Inject baseline state (action: "set") +# ===================================================================== +mocks = [ + ("Sheets", SHEETS_URL, build_sheets_state()), + ("Slack", SLACK_URL, build_slack_state()), +] +for name, url, state in mocks: + print(f'Injecting initial state into {name} mock...') + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name} state injection failed: {resp.status_code} {resp.text}' +for name, url, _ in mocks: + go = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state'), f'{name} initial_state is None after injection' + assert go.get('current_state'), f'{name} current_state is None after injection' +print(f'States injected + verified: sid={sid}') + + +# ===================================================================== +# Launch GUI (Chrome) with DISPLAY=:0 +# ===================================================================== +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + + +launch_gui(f'google-chrome "{SHEETS_URL}/?sid={sid}"', delay_sec=2.5) +print(f'GUI_READY: launched Google Sheets at {SHEETS_URL}/?sid={sid}') +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched Slack at {SLACK_URL}/?sid={sid}') + +print('Initial setup complete - Campaign Performance sheet and Slack are ready for the agent') diff --git a/mktg_report_003/reward.py b/mktg_report_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb873664214f792d1622fa41720e11ac1b3fa5c --- /dev/null +++ b/mktg_report_003/reward.py @@ -0,0 +1,219 @@ +""" +Reward Script: Transcribe Spring Nurture metrics into 'Campaign Performance' Google + Sheet + post a one-line summary in Slack #marketing. +Task ID: mktg_report_003 +Domain: mock_websites (google_sheets + slack) + +All checks are DELTA vs initial_state (added/changed cells; new messages), so +reward(initial_env) == 0.0. Fully deterministic / rule-based. + +Scoring (total 1.0): + Component 1 — GOOGLE SHEETS 'Spring Nurture' row (0.70): + 1a (0.24) MQLs cell filled with 142. + 1b (0.23) Open Rate cell filled with 38.5% (0.385 fraction or 38.5). + 1c (0.23) Conversion Rate cell filled with 4.2% (0.042 fraction or 4.2). + Component 2 — SLACK #marketing summary (0.30): + A NEW #marketing message that states all three metrics (142 / 38.5 / 4.2). +""" +import re +import sys + +import requests + +SHEETS_URL = 'http://28.7.184.198:8145' +SLACK_URL = 'http://28.7.184.198:8178' + +EXP_MQLS = 142.0 +EXP_OPEN = 0.385 # 38.5% +EXP_CONV = 0.042 # 4.2% +PCT_TOL = 0.0005 + + +def read_sid(): + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid empty') + return sid + except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + return None + + +def fetch(url, sid): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=20).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + except Exception as e: + print(f'ERROR: cannot fetch {url}: {e}') + return None, None + + +def to_number(v): + if v is None: + return None + s = str(v).strip().replace('%', '').replace(',', '').replace(' ', '') + if s == '': + return None + try: + return float(s) + except ValueError: + return None + + +def normalize_rate(v): + """Return a fraction. Accepts 0.385 or 38.5 or '38.5%'.""" + if v is None: + return None + is_pct = isinstance(v, str) and '%' in v + n = to_number(v) + if n is None: + return None + if is_pct or n > 1: + return n / 100.0 + return n + + +def index_added_cells(initial, current): + """Return {cell_id: cell} for cells added or changed between initial and current.""" + def sheet_data(state): + for sh in (state or {}).get('sheets', []) or []: + # single-sheet workbook in this task + return sh.get('data', {}) or {} + return {} + + init_data = sheet_data(initial) + cur_data = sheet_data(current) + out = {} + for cell_id, cell in cur_data.items(): + if init_data.get(cell_id) == cell: + continue + out[cell_id] = cell + return out + + +def cell_number(cell): + if not isinstance(cell, dict): + return None + for key in ('computed', 'value', 'formula'): + n = to_number(cell.get(key)) + if n is not None: + return n + return None + + +def cell_rate(cell): + if not isinstance(cell, dict): + return None + for key in ('computed', 'value', 'formula'): + r = normalize_rate(cell.get(key)) + if r is not None: + return r + return None + + +def verify_sheets(sid): + """Component 1 (0.70): Spring Nurture MQLs / Open Rate / Conversion Rate filled.""" + init, cur = fetch(SHEETS_URL, sid) + if cur is None: + print('FAIL: Sheets unreachable') + return 0.0 + score = 0.0 + try: + # Locate the Spring Nurture row from current sheet data (column A label). + def sheet_data(state): + for sh in (state or {}).get('sheets', []) or []: + return sh.get('data', {}) or {} + return {} + + cur_data = sheet_data(cur) + spring_row = None + for cell_id, cell in cur_data.items(): + m = re.match(r'^A(\d+)$', cell_id) + if not m: + continue + val = str((cell or {}).get('value') or (cell or {}).get('formula') or '').strip().lower() + if val == 'spring nurture': + spring_row = int(m.group(1)) + break + if spring_row is None: + print('FAIL: C1 — Spring Nurture row not found in column A') + return 0.0 + + added = index_added_cells(init, cur) + b = added.get(f'B{spring_row}') # MQLs + c = added.get(f'C{spring_row}') # Open Rate + d = added.get(f'D{spring_row}') # Conversion Rate + + # 1a: MQLs == 142 (0.24) + b_num = cell_number(b) if b is not None else None + if b_num is not None and abs(b_num - EXP_MQLS) < 0.5: + print(f'PASS: 1a — MQLs = {b_num} (0.24)') + score += 0.24 + else: + print(f'FAIL: 1a — MQLs expected 142, added cell B{spring_row}={b!r}') + + # 1b: Open Rate == 38.5% (0.23) + c_frac = cell_rate(c) if c is not None else None + if c_frac is not None and abs(c_frac - EXP_OPEN) <= PCT_TOL: + print(f'PASS: 1b — Open Rate = {c_frac} (0.23)') + score += 0.23 + else: + print(f'FAIL: 1b — Open Rate expected 0.385, added cell C{spring_row}={c!r} (norm={c_frac})') + + # 1c: Conversion Rate == 4.2% (0.23) + d_frac = cell_rate(d) if d is not None else None + if d_frac is not None and abs(d_frac - EXP_CONV) <= PCT_TOL: + print(f'PASS: 1c — Conversion Rate = {d_frac} (0.23)') + score += 0.23 + else: + print(f'FAIL: 1c — Conversion Rate expected 0.042, added cell D{spring_row}={d!r} (norm={d_frac})') + return score + except Exception as e: + print(f'ERROR: Sheets component — {e}') + return score + + +def verify_slack(sid): + """Component 2 (0.30): NEW #marketing message stating all three metrics.""" + init, cur = fetch(SLACK_URL, sid) + if cur is None: + print('FAIL: Slack unreachable') + return 0.0 + try: + init_ids = {m.get('messageId') for m in (init.get('messages') or {}).get('marketing', [])} + new_msgs = [m for m in (cur.get('messages') or {}).get('marketing', []) + if m.get('messageId') not in init_ids] + for m in new_msgs: + content = m.get('content') or '' + norm = content.replace(',', '') + have_mqls = '142' in norm + have_open = bool(re.search(r'38\.5\s*%?', norm)) + have_conv = bool(re.search(r'4\.2\s*%?', norm)) + print(f'SLACK: new msg mqls={have_mqls} open={have_open} conv={have_conv} ' + f'content={content!r}') + if have_mqls and have_open and have_conv: + print('PASS: C2 — #marketing summary states all three metrics (0.30)') + return 0.30 + print(f'FAIL: C2 — no new #marketing message with all three metrics ({len(new_msgs)} new)') + return 0.0 + except Exception as e: + print(f'ERROR: Slack component — {e}') + return 0.0 + + +def main(): + sid = read_sid() + if not sid: + print('REWARD: 0.0') + return + total = 0.0 + total += verify_sheets(sid) + total += verify_slack(sid) + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + + +main() diff --git a/mktg_report_003/reward_label.json b/mktg_report_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..4f33f5d0299b80301b0b3eef43542426064000ce --- /dev/null +++ b/mktg_report_003/reward_label.json @@ -0,0 +1,47 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/mktg_report_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:27:49", + "label": { + "task_id": "mktg_report_003", + "domain": "mock_websites", + "summary": "验证用户是否将 Spring Nurture 的三个指标(MQLs 142、Open Rate 38.5%、Conversion Rate 4.2%)正确填入 Google Sheets 的 Campaign Performance 表,并在 Slack #marketing 频道发布一条包含这三个指标的新摘要消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8165 (Google Sheets mock)", + "http://28.7.186.212:8198 (Slack mock)" + ], + "scoring_components": [ + { + "name": "Component 1 — Google Sheets 'Spring Nurture' 行", + "weight": 0.7, + "description": "检查 Google Sheets 中 Spring Nurture 行的三个指标单元格是否被正确填写", + "check_logic": "通过 HTTP GET /go?sid={sid} 获取 Sheets 的 initial_state 与 current_state;在 column A 中查找值为 'spring nurture' 的行号;计算新增或修改的单元格(index_added_cells);检查该行 B 列(MQLs)数值是否为 142(容差<0.5,得 0.24)、C 列(Open Rate)归一化后是否为 0.385(容差<=0.0005,得 0.23)、D 列(Conversion Rate)归一化后是否为 0.042(容差<=0.0005,得 0.23)。支持百分比字符串、分数及小数形式。", + "pass_condition": "B 列 MQLs 等于 142(+0.24),C 列 Open Rate 等于 38.5%(+0.23),D 列 Conversion Rate 等于 4.2%(+0.23)" + }, + { + "name": "Component 2 — Slack #marketing 摘要", + "weight": 0.3, + "description": "检查 Slack #marketing 频道是否有新增消息同时包含全部三个指标", + "check_logic": "通过 HTTP GET /go?sid={sid} 获取 Slack 的 initial_state 与 current_state;提取 messages.marketing 中 messageId 不在初始集合的新消息;对消息内容去除逗号后,检查是否同时包含 '142'、'38.5'(可选后跟 %)和 '4.2'(可选后跟 %)。", + "pass_condition": "存在至少一条新的 #marketing 消息同时包含 142、38.5% 和 4.2% 三个指标(+0.30)" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件得分相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并提前退出,REWARD 为 0.0", + "Sheets mock 服务不可达(fetch 返回 None):Component 1 返回 0.0", + "未在 column A 找到 'spring nurture' 行:Component 1 返回 0.0", + "Slack mock 服务不可达(fetch 返回 None):Component 2 返回 0.0", + "没有新的 #marketing 消息或新消息未同时包含三个指标:Component 2 返回 0.0", + "各子项数值不匹配:对应子项不加分,但不影响其他子项得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接输出 REWARD: 0.0 并退出。随后顺序执行两个验证:1) 对 Google Sheets,通过 sid 拉取 initial_state 与 current_state,在 column A 定位值为 'spring nurture' 的行,比较得到新增或修改的单元格,逐项验证 B 列(MQLs=142,容差<0.5,得 0.24)、C 列(Open Rate=0.385,容差<=0.0005,得 0.23)、D 列(Conversion Rate=0.042,容差<=0.0005,得 0.23)。2) 对 Slack,同样拉取状态,筛选 #marketing 频道中 messageId 为新的消息,检查内容是否同时包含 142、38.5% 和 4.2%(支持百分比字符串与数字形式),满足则得 0.30。两个组件得分相加后,用 min(total, 1.0) 限制上限并四舍五入到 4 位小数,输出最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **任务信息**:\n - Task ID: mktg_report_001\n - Domain: mock_websites (google_sheets + slack)\n - 任务:将 Spring Nurture 指标转录到 Google Sheet 的 'Campaign Performance' 中,并在 Slack #marketing 中发布一行摘要\n\n2. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - `http://28.7.186.212:8165`:Google Sheets mock 服务\n - `http://28.7.186.212:8198`:Slack mock 服务\n\n3. **评分组件**:\n - Component 1 (0.70):Google Sheets 'Spring Nurture' 行\n - 1a (0.24):MQLs 单元格填写 142\n - 1b (0.23):Open Rate 单元格填写 38.5%(0.385 或 38.5)\n - 1c (0.23):Conversion Rate 单元格填写 4.2%(0.042 或 4.2)\n - Component 2 (0.30):Slack #marketing 摘要\n - 新的 #marketing 消息包含所有三个指标(142 / 38.5 / 4.2)\n\n4. **评分逻辑**:\n - 读取 sid\n - 分别验证 sheets 和 slack\n - 分数相加,上限 1.0\n - 不是占位脚本,有具体检查逻辑\n\n5. **失败模式**:\n - 读取 sid 失败(提前退出,输出 REWARD: 0.0)\n - Sheets 不可达(返回 0.0)\n - 找不到 Spring Nurture 行(返回 0.0)\n - Slack 不可达(返回 0.0)\n - 没有新的 #marketing 消息包含所有三个指标(返回 0.0)\n - 各子项不匹配(不加分)\n\n6. **检查逻辑细节**:\n - Sheets:比较 initial_state 和 current_state,找新增/修改的单元格\n - 在 column A 找 \"spring nurture\" 行\n - 检查 B{row} (MQLs)、C{row} (Open Rate)、D{row} (Conversion Rate)\n - MQLs: 数值 142,容差 < 0.5\n - Open Rate: 0.385,容差 <= 0.0005 (PCT_TOL)\n - Conversion Rate: 0.042,容差 <= 0.0005\n - Slack:比较 initial 和 current 的 messages.marketing\n - 找新消息(messageId 不在 initial 中)\n - 内容需包含 142、38.5(可能带%)、4.2(可能带%)\n - 去掉逗号后检查\n\n7. **分数聚合**:\n - 相加,然后 min(total, 1.0),四舍五入到4位小数\n\n8. **is_placeholder**:false,有完整检查逻辑\n\n9. **confidence**:1.0,代码清晰完整\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"mktg_report_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证用户是否将 Spring Nurture 的三个指标(MQLs 142、Open Rate 38.5%、Conversion Rate 4.2%)正确填入 Google Sheets 的 Campaign Performance 表,并在 Slack #marketing 频道发布包含这三个指标的新摘要消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"http://28.7.186.212:8165 (Google Sheets mock)\", \"http://28.7.186.212:8198 (Slack mock)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 — Google Sheets 'Spring Nurture' 行\",\n \"weight\": 0.7,\n \"description\": \"检查 Google Sheets 中 Spring Nurture 行的三个指标单元格是否被正确填写\",\n \"check_logic\": \"通过 /go?sid={sid} 获取 Sheets 的 initial_state 和 current_state,在 column A 中查找值为 'spring nurture' 的行号,然后检查该行 B/C/D 列在 added/changed cells 中是否包含正确数值:B 列 MQLs 数值需为 142(容差<0.5),C 列 Open Rate 需为 0.385(容差<=0.0005),D 列 Conversion Rate 需为 0.042(容差<=0.0005)。支持百分比字符串和分数形式。\",\n \"pass_condition\": \"三个子项分别通过:1a MQLs==142(+0.24),1b Open Rate==38.5%(+0.23),1c Conversion Rate==4.2%(+0.23)\"\n },\n {\n \"name\": \"Component 2 — Slack #marketing 摘要\",\n \"weight\": 0.3,\n \"description\": \"检查 Slack #marketing 频道是否有新增消息包含全部三个指标\",\n \"check_logic\": \"通过 /go?sid={sid} 获取 Slack 的 initial_state 和 current_state,提取 messages.marketing 中 messageId 不在初始状态的新消息,检查消息内容(去除逗号后)是否同时包含 '142'、'38.5'(可选后跟%)和 '4.2'(可选后跟%)。\",\n \"pass_condition\": \"存在至少一条新的 #marketing 消息同时包含 142、38.5% 和 4.2% 三个指标(+0.30)\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并提前退出,REWARD 为 0.0\",\n \"Sheets mock 服务不可达(fetch 返回 None):Component 1 返回 0.0\",\n \"未在 column A 找到 'spring nurture' 行:Component 1 返回 0.0\",\n \"Slack mock 服务不可达(fetch 返回 None):Component 2 返回 0.0\",\n \"没有新的 #marketing 消息或新消息未同时包含三个指标:Component 2 返回 0.0\",\n \"各子项数值不匹配:对应子项不加分,但不影响其他子项\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID;若失败则直接返回 0.0。随后并行检查两个组件(实际为顺序执行):1) 对 Google Sheets,通过 HTTP 获取 initial/current state,在 column A 定位 'spring nurture' 行,比较初始和当前状态得到新增/修改的单元格,分别验证 B 列(MQLs=142,容差<0.5,得 0.24)、C 列(Open Rate=0.385,容差<=0.0005,得 0.23)、D 列(Conversion Rate=0.042,容差<=0.0005,得 0.23)。2) 对 Slack,同样获取状态,筛选出 #marketing 频道中 messageId 为新的消息,检查内容是否同时包含 142、38.5% 和 4.2%(支持百分比字符串和数字形式),若满足则得 0.30。两个组件得分相加后,用 min(total, 1.0) 限制上限并四舍五入到 4 位小数输出最终 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id/domain/字段名保留原样\n- weight 填写显式分值:Component 1 总权重 0.70,Component 2 总权重 0.30。但子项有明确分值。我应该按顶层组件分还是按子项分?题目说 \"weight 字段填写代码中显式给出的分值(如 0.3);若代码未显式分值但有通过/失败二值判定,weight 填 1.0\"。这里有两个主要组件,分别有 0.70 和 0.30 的权重。子项也有明确分值。我觉得按 docstring 中的 Component 1 和 Component 2 作为两个 scoring_components 更合适,因为它们的权重是显式给出的(0.70 和 0.30)。在 check_logic 中再说明子项分值。\n\n等等,docstring 说:\nComponent 1 — GOOGLE SHEETS 'Spring Nurture' row (0.70):\nComponent 2 — SLACK #marketing summary (0.30):\n\n所以两个组件的 weight 应该是 0.7 和 0.3。在 description/check_logic 中说明子项分值。\n\n再检查 data_sources:应该列出脚本从哪些数据源获取状态。有 /tmp/task_web_sid,SHEETS_URL,SLACK_URL。\n\n确认 domain:docstring 中明确写了 Domain: mock_websites (google_sheets + slack)。所以 domain 应该是 \"mock_websites\"。\n\n确认 task_id:mktg_report_001。\n\n确认 is_placeholder:false。\n\n确认 failure_modes:需要列出会导致提前退出、返回 0.0 或扣分的异常/失败路径。\n\n确认 score_aggregation:相加,钳制到上限。\n\n一切看起来正确。 {\n \"task_id\": \"mktg_report_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证用户是否将 Spring Nurture 的三个指标(MQLs 142、Open Rate 38.5%、Conversion Rate 4.2%)正确填入 Google Sheets 的 Campaign Performance 表,并在 Slack #marketing 频道发布一条包含这三个指标的新摘要消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"http://28.7.186.212:8165 (Google Sheets mock)\", \"http://28.7.186.212:8198 (Slack mock)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 — Google Sheets 'Spring Nurture' 行\",\n \"weight\": 0.7,\n \"description\": \"检查 Google Sheets 中 Spring Nurture 行的三个指标单元格是否被正确填写\",\n \"check_logic\": \"通过 HTTP GET /go?sid={sid} 获取 Sheets 的 initial_state 与 current_state;在 column A 中查找值为 'spring nurture' 的行号;计算新增或修改的单元格(index_added_cells);检查该行 B 列(MQLs)数值是否为 142(容差<0.5,得 0.24)、C 列(Open Rate)归一化后是否为 0.385(容差<=0.0005,得 0.23)、D 列(Conversion Rate)归一化后是否为 0.042(容差<=0.0005,得 0.23)。支持百分比字符串、分数及小数形式。\",\n \"pass_condition\": \"B 列 MQLs 等于 142(+0.24),C 列 Open Rate 等于 38.5%(+0.23),D 列 Conversion Rate 等于 4.2%(+0.23)\"\n },\n {\n \"name\": \"Component 2 — Slack #marketing 摘要\",\n \"weight\": 0.3,\n \"description\": \"检查 Slack #marketing 频道是否有新增消息同时包含全部三个指标\",\n \"check_logic\": \"通过 HTTP GET /go?sid={sid} 获取 Slack 的 initial_state 与 current_state;提取 messages.marketing 中 messageId 不在初始集合的新消息;对消息内容去除逗号后,检查是否同时包含 '142'、'38.5'(可选后跟 %)和 '4.2'(可选后跟 %)。\",\n \"pass_condition\": \"存在至少一条新的 #marketing 消息同时包含 142、38.5% 和 4.2% 三个指标(+0.30)\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件得分相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并提前退出,REWARD 为 0.0\",\n \"Sheets mock 服务不可达(fetch 返回 None):Component 1 返回 0.0\",\n \"未在 column A 找到 'spring nurture' 行:Component 1 返回 0.0\",\n \"Slack mock 服务不可达(fetch 返回 None):Component 2 返回 0.0\",\n \"没有新的 #marketing 消息或新消息未同时包含三个指标:Component 2 返回 0.0\",\n \"各子项数值不匹配:对应子项不加分,但不影响其他子项得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接输出 REWARD: 0.0 并退出。随后顺序执行两个验证:1) 对 Google Sheets,通过 sid 拉取 initial_state 与 current_state,在 column A 定位值为 'spring nurture' 的行,比较得到新增或修改的单元格,逐项验证 B 列(MQLs=142,容差<0.5,得 0.24)、C 列(Open Rate=0.385,容差<=0.0005,得 0.23)、D 列(Conversion Rate=0.042,容差<=0.0005,得 0.23)。2) 对 Slack,同样拉取状态,筛选 #marketing 频道中 messageId 为新的消息,检查内容是否同时包含 142、38.5% 和 4.2%(支持百分比字符串与数字形式),满足则得 0.30。两个组件得分相加后,用 min(total, 1.0) 限制上限并四舍五入到 4 位小数,输出最终 REWARD。\",\n \"confidence\": 1.0\n}" +} diff --git a/mktg_webinar_mql_008/_cua_gym_vm_bridge.sh b/mktg_webinar_mql_008/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_webinar_mql_008/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/mktg_webinar_mql_008/initial_setup.py b/mktg_webinar_mql_008/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0827dca704e0928dcf9ec945468f4fa6da9446 --- /dev/null +++ b/mktg_webinar_mql_008/initial_setup.py @@ -0,0 +1,363 @@ +""" +Initial Setup: Q3 Product Launch Webinar -> MQL pipeline +Task ID: mktg_webinar_mql_008 +Domain: mock_websites (multi-app: airtable + hubspot + slack) +Mocks: airtable (8129), hubspot (8170), slack (8198) + +This script establishes the PRE-TASK initial state: + - Airtable: base 'Marketing Ops' with table 'Webinar Attendees' (6 columns), 0 records. + - HubSpot: 8 attendee leads keyed by email, none with Lifecycle Stage = MQL. + - Slack: workspace with a #marketing-ops channel (empty), current user John Smith. +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# ---------------------------------------------------------------------------- +# Config +# ---------------------------------------------------------------------------- +AIRTABLE_URL = "http://28.7.184.198:8109" +HUBSPOT_URL = "http://28.7.184.198:8150" +SLACK_URL = "http://28.7.184.198:8178" + +# Same sid across all three mocks +sid = str(uuid.uuid4()) +with open("/tmp/task_web_sid", "w") as f: + f.write(sid) + +print(f"[initial_setup] sid = {sid}") + +# ---------------------------------------------------------------------------- +# Shared attendee data (fixed inputs from task instruction) +# ---------------------------------------------------------------------------- +ATTENDEES = [ + # (first, last, email, company, attended_live, qualified) + ("Priya", "Nair", "priya.nair@cobaltstack.io", "Cobalt Stack", "Yes", "Yes"), + ("Marcus", "Lee", "marcus.lee@denovaworks.com", "Denova Works", "Yes", "Yes"), + ("Sofia", "Romano", "sofia.romano@everlytics.io", "Everlytics", "No", "Yes"), + ("Tom", "Becker", "tom.becker@finchpay.com", "Finch Pay", "Yes", "No"), + ("Aisha", "Khan", "aisha.khan@heliosys.com", "Heliosys", "No", "Yes"), + ("Diego", "Alvarez", "diego.alvarez@ironcladlabs.io", "Ironclad Labs", "Yes", "Yes"), + ("Lena", "Hofer", "lena.hofer@greydesk.com", "GreyDesk", "No", "No"), + ("Ben", "Carter", "ben.carter@bexter.com", "Bexter", "Yes", "No"), +] + +QUALIFIED_EMAILS = {a[2] for a in ATTENDEES if a[5] == "Yes"} + +# ---------------------------------------------------------------------------- +# 1. Airtable state +# ---------------------------------------------------------------------------- +def build_airtable_state(): + base_id = "base_mktops" + table_id = "tbl_webinar_attendees" + fld_name = "fld_attendee_name" + fld_email = "fld_email" + fld_company = "fld_company" + fld_live = "fld_attended_live" + fld_qualified = "fld_qualified" + fld_pushed = "fld_pushed" + + state = { + "bases": { + base_id: { + "id": base_id, + "name": "Marketing Ops", + "color": "bg-teal-600", + "tables": [table_id], + } + }, + "tables": { + table_id: { + "id": table_id, + "name": "Webinar Attendees", + "baseId": base_id, + "fields": [ + {"id": fld_name, "name": "Attendee Name", "type": "text", "primary": True}, + {"id": fld_email, "name": "Email", "type": "email"}, + {"id": fld_company, "name": "Company", "type": "text"}, + { + "id": fld_live, + "name": "Attended Live?", + "type": "single_select", + "options": [ + {"id": "opt_yes", "name": "Yes", "color": "bg-green-100 text-green-800"}, + {"id": "opt_no", "name": "No", "color": "bg-red-100 text-red-800"}, + ], + }, + { + "id": fld_qualified, + "name": "Qualified?", + "type": "single_select", + "options": [ + {"id": "opt_yes", "name": "Yes", "color": "bg-green-100 text-green-800"}, + {"id": "opt_no", "name": "No", "color": "bg-red-100 text-red-800"}, + ], + }, + { + "id": fld_pushed, + "name": "Pushed to HubSpot?", + "type": "single_select", + "options": [ + {"id": "opt_yes", "name": "Yes", "color": "bg-green-100 text-green-800"}, + {"id": "opt_no", "name": "No", "color": "bg-red-100 text-red-800"}, + ], + }, + ], + "records": [], # EMPTY initially (0 records) + "views": [ + { + "id": "view_grid", + "name": "Grid View", + "type": "grid", + "filters": [], + "sorts": [], + "groupBy": [], + "hiddenFieldIds": [], + "fieldWidths": {}, + "rowHeight": "short", + } + ], + "activeViewId": "view_grid", + } + }, + "activeBaseId": base_id, + "activeTableId": table_id, + "ui": { + "viewSidebarOpen": False, + "expandedRecordId": None, + "searchQuery": "", + "isSearching": False, + }, + "activityLog": [], + } + return state + + +# ---------------------------------------------------------------------------- +# 2. HubSpot state +# ---------------------------------------------------------------------------- +def build_hubspot_state(): + contacts = [] + for i, (fn, ln, email, company, live, qual) in enumerate(ATTENDEES, start=1): + contacts.append({ + "id": f"c{i}", + "firstName": fn, + "lastName": ln, + "email": email, + # 'company' as a plain string is fine for the contacts table; also keep companyId + "company": company, + "companyId": f"comp{i}", + "jobTitle": "Webinar Attendee", + "lifecycleStage": "lead", # none is MQL yet + "leadStatus": "new", + "owner": "Admin User", + "city": "", + "state": "", + "country": "", + "phone": "", + "createDate": "2026-07-02T10:00:00Z", + "lastActivityDate": "2026-07-02T10:00:00Z", + "timeline": [], + }) + + companies = [] + for i, (fn, ln, email, company, live, qual) in enumerate(ATTENDEES, start=1): + companies.append({ + "id": f"comp{i}", + "name": company, + "domain": company.lower().replace(" ", "") + ".com", + "industry": "Technology", + "phone": "", + "city": "", + "state": "", + "country": "United States", + "numberOfEmployees": 50, + "annualRevenue": 5000000, + "lifecycleStage": "lead", + "owner": "Admin User", + "description": f"{company} - webinar attendee company", + "createDate": "2026-07-02T10:00:00Z", + }) + + state = { + "contacts": contacts, + "companies": companies, + "deals": [], + "tickets": [], + "tasks": [], + "notes": [], + "templates": [], + "meetings": [], + "forms": [], + "dealStages": { + "appointment_scheduled": {"id": "appointment_scheduled", "label": "Appointment Scheduled", "probability": 20, "color": "#E5F4FF", "order": 1}, + "qualified_to_buy": {"id": "qualified_to_buy", "label": "Qualified to Buy", "probability": 40, "color": "#FFF0E6", "order": 2}, + "presentation_scheduled": {"id": "presentation_scheduled", "label": "Presentation Scheduled", "probability": 60, "color": "#FFF8E6", "order": 3}, + "decision_maker_bought_in": {"id": "decision_maker_bought_in", "label": "Decision Maker Bought-In", "probability": 80, "color": "#E8F5E9", "order": 4}, + "contract_sent": {"id": "contract_sent", "label": "Contract Sent", "probability": 90, "color": "#E6FFFA", "order": 5}, + "closed_won": {"id": "closed_won", "label": "Closed Won", "probability": 100, "color": "#E6FFEC", "order": 6}, + "closed_lost": {"id": "closed_lost", "label": "Closed Lost", "probability": 0, "color": "#FFE6E6", "order": 7}, + }, + "ticketStatuses": { + "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1}, + "waiting_on_contact": {"id": "waiting_on_contact", "label": "Waiting on Contact", "color": "#FFF8E6", "order": 2}, + "waiting_on_us": {"id": "waiting_on_us", "label": "Waiting on Us", "color": "#FFF0E6", "order": 3}, + "in_progress": {"id": "in_progress", "label": "In Progress", "color": "#E6FFFA", "order": 4}, + "closed": {"id": "closed", "label": "Closed", "color": "#E6FFEC", "order": 5}, + }, + "appState": { + "sidebarOpen": True, + "currentUser": {"name": "Admin User", "email": "admin@example.com", "avatar": None}, + }, + } + return state + + +# ---------------------------------------------------------------------------- +# 3. Slack state +# ---------------------------------------------------------------------------- +def build_slack_state(): + state = { + "currentUser": { + "userId": "user_1", + "fullName": "John Smith", + "displayName": "John", + "email": "john.smith@company.com", + "avatar": "https://picsum.photos/200/200?random=1", + "status": "online", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York", + }, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", "icon": ""}, + "users": [ + {"userId": "user_1", "fullName": "John Smith", "displayName": "John", "email": "john.smith@company.com", "avatar": "https://picsum.photos/200/200?random=1", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York", "title": "Marketing Ops Analyst"}, + {"userId": "user_2", "fullName": "Sarah Johnson", "displayName": "Sarah", "email": "sarah.johnson@company.com", "avatar": "https://picsum.photos/200/200?random=2", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York", "title": "Growth Marketer"}, + ], + "channels": [ + {"channelId": "general", "name": "general", "description": "Company-wide announcements and general discussion", "topic": "", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2"], "createdBy": "user_1", "createdAt": "2026-07-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "marketing-ops", "name": "marketing-ops", "description": "Marketing Operations - webinar pipeline, lead routing, and campaign tracking", "topic": "Webinar MQL pipeline", "isPrivate": False, "isStarred": True, "members": ["user_1", "user_2"], "createdBy": "user_1", "createdAt": "2026-07-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "general": [ + {"messageId": "msg_gen_1", "senderId": "user_2", "content": "Welcome to the Q3 planning channel!", "timestamp": "2026-07-01T09:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False} + ], + "marketing-ops": [], # empty channel at start + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + return state + + +# ---------------------------------------------------------------------------- +# Inject all three mocks (action: set) +# ---------------------------------------------------------------------------- +def inject(url, state): + resp = requests.post( + f"{url}/post?sid={sid}", + json={"action": "set", "state": state}, + timeout=30, + ) + assert resp.status_code == 200, f"State injection failed at {url}: {resp.text}" + print(f"[initial_setup] injected state at {url} (sid={sid})") + + +inject(AIRTABLE_URL, build_airtable_state()) +inject(HUBSPOT_URL, build_hubspot_state()) +inject(SLACK_URL, build_slack_state()) + +# ---------------------------------------------------------------------------- +# Verify initial_state is set on each mock +# ---------------------------------------------------------------------------- +for name, url in [("airtable", AIRTABLE_URL), ("hubspot", HUBSPOT_URL), ("slack", SLACK_URL)]: + go = requests.get(f"{url}/go?sid={sid}", timeout=10).json() + assert go["initial_state"] is not None, f"{name}: initial_state is None after injection" + print(f"[initial_setup] verified initial_state present for {name}") + +# ---------------------------------------------------------------------------- +# Launch Chrome for each mock +# ---------------------------------------------------------------------------- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + + +launch_gui(f'google-chrome "{AIRTABLE_URL}/?sid={sid}"', delay_sec=0.5) +launch_gui(f'google-chrome "{HUBSPOT_URL}/?sid={sid}"', delay_sec=0.5) +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=0.5) + + +# ---------------------------------------------------------------------------- +# Wait until each mock serves the injected state AND renders +# ---------------------------------------------------------------------------- +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + raise RuntimeError(f'Mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 5s') + _t.sleep(5.0) + return + with sync_playwright() as p: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', + timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 100", + timeout=int(render_timeout * 1000)) + html = page.content() + if len(html) < 2000: + raise RuntimeError( + f'[{name}] rendered DOM too small ({len(html)} bytes) - blank/stuck loading') + print(f'[{name}] rendered OK ({len(html)} bytes)') + finally: + page.close() + finally: + browser.close() + + +wait_for_mocks_loaded({ + "airtable": AIRTABLE_URL, + "hubspot": HUBSPOT_URL, + "slack": SLACK_URL, +}, sid) + +print(f"GUI_READY: launched and verified all 3 mocks (sid={sid})") diff --git a/mktg_webinar_mql_008/reward.py b/mktg_webinar_mql_008/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..3d35d99725bdbb2e3729c72ae812f57ed4b28e3f --- /dev/null +++ b/mktg_webinar_mql_008/reward.py @@ -0,0 +1,327 @@ +""" +Reward Script: Post-webinar MQL pipeline (Airtable -> HubSpot -> Airtable -> Slack) +Task ID: mktg_webinar_mql_008 +Domain: mock_websites (libreoffice_calc label is a misnomer; this is a 3-mock HTTP pipeline) +Mocks: airtable @ http://28.7.184.198:8109 + hubspot @ http://28.7.184.198:8150 + slack @ http://28.7.184.198:8178 +Scoring (sum = 1.0): + - C1 Airtable: 8 attendee records with correct Name/Email/Company/Attended Live?/Qualified? (0.35) + - C2 Airtable: qualified(5)='Yes' on 'Pushed to HubSpot?'; unqualified(3)='No' or empty (0.15) + - C3 HubSpot: the 5 qualified leads are MQL and the 3 unqualified leads are unchanged (0.30) + - C4 Slack: exactly one #marketing-ops message with the exact required summary text (0.20) +All checks are deterministic (no LLM judge — no API key available). The script +reads the session id from /tmp/task_web_sid, fetches /go?sid= from each +mock, and scores current_state against the task's golden criteria. When the +environment's current_state is the baseline (no progress) the score is 0.0. +""" +import json +import sys + +import requests + +# --- Mock endpoints (from task_config.json task_instruction) --- +AIRTABLE_URL = "http://28.7.184.198:8109" +HUBSPOT_URL = "http://28.7.184.198:8150" +SLACK_URL = "http://28.7.184.198:8178" + +# --- Ground truth from task_config.json --- +# (name, email, company, attended_live, qualified) +ATTENDEES = [ + ("Priya Nair", "priya.nair@cobaltstack.io", "Cobalt Stack", "Yes", "Yes"), + ("Marcus Lee", "marcus.lee@denovaworks.com", "Denova Works", "Yes", "Yes"), + ("Sofia Romano", "sofia.romano@everlytics.io", "Everlytics", "No", "Yes"), + ("Tom Becker", "tom.becker@finchpay.com", "Finch Pay", "Yes", "No"), + ("Aisha Khan", "aisha.khan@heliosys.com", "Heliosys", "No", "Yes"), + ("Diego Alvarez", "diego.alvarez@ironcladlabs.io", "Ironclad Labs", "Yes", "Yes"), + ("Lena Hofer", "lena.hofer@greydesk.com", "GreyDesk", "No", "No"), + ("Ben Carter", "ben.carter@bexter.com", "Bexter", "Yes", "No"), +] +QUALIFIED_EMAILS = {a[1] for a in ATTENDEES if a[4] == "Yes"} +UNQUALIFIED_EMAILS = {a[1] for a in ATTENDEES if a[4] == "No"} + +EXPECTED_SLACK_TEXT = ( + "Q3 Product Launch Webinar: 8 attendees, 5 qualified (Priya Nair, Marcus Lee, " + "Sofia Romano, Aisha Khan, Diego Alvarez) pushed to HubSpot as MQLs. 3 not qualified " + "(Tom Becker, Lena Hofer, Ben Carter)." +) +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f"error: {e}" + status = "PASS" if passed else "FAIL" + suffix = f" ({weight} pts)" if passed else f" — {detail}" + print(f"{status}: Component {idx} — {name}{suffix}") + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or "").strip()) + return passed, score, detail + + +# --------------------------------------------------------------------------- +# State fetchers +# --------------------------------------------------------------------------- +def _fetch_current_state(base_url, sid): + """Fetch current_state from a mock's /go endpoint. Returns dict or {}.""" + try: + resp = requests.get(f"{base_url}/go?sid={sid}", timeout=20) + resp.raise_for_status() + data = resp.json() + return data.get("current_state", {}) or {} + except Exception as e: + print(f"WARN: cannot fetch {base_url}/go?sid={sid}: {e}") + return {} + + +def _fetch_state_diff(base_url, sid): + """Fetch state_diff from a mock's /go endpoint. Non-empty means the agent + (or golden_patch) changed the state relative to the frozen baseline. An empty + state_diff means NO progress was made -> this is the initial / no-op state. + Returns dict (possibly empty).""" + try: + resp = requests.get(f"{base_url}/go?sid={sid}", timeout=20) + resp.raise_for_status() + data = resp.json() + return data.get("state_diff", {}) or {} + except Exception as e: + print(f"WARN: cannot fetch diff {base_url}/go?sid={sid}: {e}") + return {} + + +def _get_airtable_records(current): + """Extract the list of Webinar Attendees records from Airtable current_state.""" + try: + table = current["tables"]["tbl_webinar_attendees"] + return table.get("records", []) or [] + except Exception: + return [] + + +def _get_hubspot_contacts(current): + """Extract the list of HubSpot contacts from current_state.""" + return current.get("contacts", []) or [] + + +def _get_slack_messages(current): + """Extract #marketing-ops messages from Slack current_state.""" + try: + return current["messages"].get("marketing-ops", []) or [] + except Exception: + return [] + + +# --------------------------------------------------------------------------- +# Per-component checks +# --------------------------------------------------------------------------- +def check_component_1(current_at): + """Airtable has exactly 8 attendee records with correct Name/Email/Company/ + Attended Live?/Qualified? values. + Pass condition: every one of the 8 expected attendees appears as a record with + all five field values matching exactly. Partial credit = matching/8 * 0.35. + """ + records = _get_airtable_records(current_at) + if not records: + return False, 0.0, "no Airtable records found" + # Build a lookup keyed by lowercased email + by_email = {} + for r in records: + f = r.get("fields", {}) + email = (f.get("fld_email") or "").strip().lower() + by_email[email] = f + matched = 0 + missing = [] + for (name, email, company, attended, qualified) in ATTENDEES: + f = by_email.get(email.lower()) + if not f: + missing.append(email) + continue + if (str(f.get("fld_attendee_name", "")).strip() == name and + str(f.get("fld_company", "")).strip() == company and + str(f.get("fld_attended_live", "")).strip() == attended and + str(f.get("fld_qualified", "")).strip() == qualified): + matched += 1 + else: + missing.append(email) + frac = matched / len(ATTENDEES) + score = round(0.35 * frac, 4) + if matched == len(ATTENDEES): + return True, score, f"all {matched}/8 attendee records correct" + return False, score, f"{matched}/8 records correct; missing/mismatched: {missing}" + + +def check_component_2(current_at): + """Airtable 'Pushed to HubSpot?' = 'Yes' for the 5 qualified, 'No' for the 3 unqualified. + Pass condition: all 8 Pushed flags match qualification. Partial = correct/8 * 0.15. + + For qualified records, fld_pushed must be 'Yes'. For unqualified records, the + task instruction only says to set 'Yes' on qualified records (Step 3) without + explicitly instructing to set 'No' on unqualified ones, so we accept either + 'No' or empty (unset) as correct for unqualified. + """ + records = _get_airtable_records(current_at) + if not records: + return False, 0.0, "no Airtable records found" + by_email = {} + for r in records: + f = r.get("fields", {}) + email = (f.get("fld_email") or "").strip().lower() + by_email[email] = f + correct = 0 + wrong = [] + for (name, email, company, attended, qualified) in ATTENDEES: + f = by_email.get(email.lower()) + if not f: + wrong.append(email) + continue + actual = str(f.get("fld_pushed", "")).strip() + if qualified == "Yes": + expected = "Yes" + ok = actual == expected + else: + # Unqualified: accept 'No' or empty (task doesn't require setting it) + ok = actual in ("No", "") + if ok: + correct += 1 + else: + expected = "Yes" if qualified == "Yes" else "No/empty" + wrong.append(f"{email}={actual}(exp {expected})") + frac = correct / len(ATTENDEES) + score = round(0.15 * frac, 4) + if correct == len(ATTENDEES): + return True, score, f"all {correct}/8 Pushed-to-HubSpot flags correct" + return False, score, f"{correct}/8 flags correct; wrong: {wrong}" + + +def check_component_3(current_hs): + """HubSpot: the 5 qualified leads are MQL and the 3 unqualified leads are unchanged. + Pass condition: all 5 qualified are MQL AND all 3 unqualified are not MQL. + Partial = (qualified_correct/5) * 0.30 (unqualified corruption is a hard fail). + """ + contacts = _get_hubspot_contacts(current_hs) + if not contacts: + return False, 0.0, "no HubSpot contacts found" + by_email = {} + for c in contacts: + by_email[(c.get("email") or "").strip().lower()] = c + + qualified_ok = 0 + q_problems = [] + for email in QUALIFIED_EMAILS: + c = by_email.get(email.lower()) + if not c: + q_problems.append(f"{email}: missing") + continue + stage = str(c.get("lifecycleStage", "")).strip().lower() + if stage == "mql": + qualified_ok += 1 + else: + q_problems.append(f"{email}: stage={stage}") + + # Unqualified must NOT be MQL + unq_bad = [] + for email in UNQUALIFIED_EMAILS: + c = by_email.get(email.lower()) + if c and str(c.get("lifecycleStage", "")).strip().lower() == "mql": + unq_bad.append(email) + + frac = qualified_ok / len(QUALIFIED_EMAILS) + score = 0.0 if unq_bad else round(0.30 * frac, 4) + if qualified_ok == len(QUALIFIED_EMAILS) and not unq_bad: + return True, score, "all 5 qualified are MQL; 3 unqualified unchanged" + detail = f"{qualified_ok}/5 qualified correct" + if q_problems: + detail += f"; problems: {q_problems}" + if unq_bad: + detail += f"; unqualified wrongly MQL: {unq_bad}" + return False, score, detail + + +def check_component_4(current_slack): + """Slack #marketing-ops has exactly one message with the exact required text. + Pass condition: exactly one new message whose content equals the expected text + (ignoring surrounding whitespace). Partial = 0.20 if present, else 0.0. + """ + msgs = _get_slack_messages(current_slack) + if not msgs: + return False, 0.0, "no messages in #marketing-ops" + normalized = [m.get("content", "").strip() for m in msgs] + exact = sum(1 for t in normalized if t == EXPECTED_SLACK_TEXT) + if exact == 1: + return True, 0.20, "exactly one #marketing-ops message matches expected text" + if exact > 1: + return False, 0.0, f"{exact} messages match expected text (expected exactly 1)" + # No exact match — check for a close/partial match to give partial credit signal + contains = sum(1 for t in normalized + if "Q3 Product Launch Webinar" in t and "pushed to HubSpot as MQLs" in t) + if contains >= 1: + return False, 0.0, "a webinar summary message exists but text does not exactly match" + return False, 0.0, "no matching #marketing-ops message found" + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- +def verify_task(): + # Read sid + try: + with open("/tmp/task_web_sid") as f: + sid = f.read().strip() + if not sid: + raise ValueError("sid is empty") + except Exception as e: + print(f"CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}") + print("REWARD: 0.0") + return 0.0 + + # Fetch current_state from all three mocks + current_at = _fetch_current_state(AIRTABLE_URL, sid) + current_hs = _fetch_current_state(HUBSPOT_URL, sid) + current_slack = _fetch_current_state(SLACK_URL, sid) + + # --- Progress gate (no-op / initial environment detection) --- + # The mocks are shared infrastructure: initial_state is the frozen baseline + # (0 Airtable records, 0 HubSpot MQLs, 0 Slack messages) and current_state is + # whatever the agent / golden_patch produced. If state_diff is empty for ALL + # three mocks, then current_state is identical to the baseline -> no task + # progress was made -> the environment is the initial state -> reward 0.0. + diff_at = _fetch_state_diff(AIRTABLE_URL, sid) + diff_hs = _fetch_state_diff(HUBSPOT_URL, sid) + diff_slack = _fetch_state_diff(SLACK_URL, sid) + if not diff_at and not diff_hs and not diff_slack: + print("INFO: state_diff empty across all mocks — no task progress detected (initial state).") + print("REWARD: 0.0") + return 0.0 + + total_score = 0.0 + # Independent components: dispatch via a table. + for idx, name, weight, fn, args in [ + (1, "Airtable 8 attendee records correct", 0.35, check_component_1, (current_at,)), + (2, "Airtable Pushed-to-HubSpot flags correct", 0.15, check_component_2, (current_at,)), + (3, "HubSpot 5 qualified = MQL", 0.30, check_component_3, (current_hs,)), + (4, "Slack #marketing-ops summary message", 0.20, check_component_4, (current_slack,)), + ]: + _, score, _ = _run_component(idx, name, weight, fn, args) + total_score += score + + final_score = round(min(total_score, 1.0), 4) + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +if __name__ == "__main__": + verify_task() diff --git a/mktg_webinar_mql_008/reward_label.json b/mktg_webinar_mql_008/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..4e35dcae29591f700232eab3f56d139228f94d07 --- /dev/null +++ b/mktg_webinar_mql_008/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof18_webinar_mql_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:29:53", + "label": { + "task_id": "mktg_webinar_mql_008", + "domain": "mock_websites", + "summary": "验证在 Airtable、HubSpot、Slack 三个 mock 服务中完成 webinar MQL 管道任务的状态,包括 8 条参会者记录、HubSpot 推送标记、MQL 转换与备注、Slack 摘要消息。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8129 (airtable mock)", + "http://28.7.186.212:8170 (hubspot mock)", + "http://28.7.186.212:8198 (slack mock)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.35, + "description": "检查 Airtable 中 8 条参会者记录的 Name、Email、Company、Attended Live?、Qualified? 字段是否与预期完全一致", + "check_logic": "从 Airtable current_state 中提取 tables['tbl_webinar_attendees'] 的 records,按 fld_email 建立索引,逐一比对 8 条预期记录的 fld_attendee_name、fld_company、fld_attended_live、fld_qualified 是否完全匹配;得分 = matched / 8 * 0.35", + "pass_condition": "8 条记录全部匹配" + }, + { + "name": "Component 2", + "weight": 0.15, + "description": "检查 Airtable 中 8 条记录的 'Pushed to HubSpot?' 字段是否按 qualified/unqualified 分别标记为 Yes/No", + "check_logic": "遍历 8 条预期记录,qualified='Yes' 时期望 fld_pushed='Yes',否则期望 'No';得分 = correct / 8 * 0.15", + "pass_condition": "8 条记录的 Pushed 标记全部正确" + }, + { + "name": "Component 3", + "weight": 0.3, + "description": "检查 HubSpot 中 5 个 qualified leads 的 lifecycleStage 是否为 'mql' 且 timeline 中包含指定 note;同时 3 个 unqualified leads 的 lifecycleStage 不得为 'mql'", + "check_logic": "对 5 个 qualified 邮箱检查 lifecycleStage=='mql'(不区分大小写)且 timeline 中存在 type='note' 且 body 包含 'Source: Q3 Product Launch Webinar';对 3 个 unqualified 邮箱检查 lifecycleStage!='mql';得分按 qualified_ok / 5 * 0.30 计算,unqualified 被错误改为 mql 会导致不通过但不额外扣分", + "pass_condition": "5 个 qualified 均为 MQL 且含正确 note,且 3 个 unqualified 未被改为 MQL" + }, + { + "name": "Component 4", + "weight": 0.2, + "description": "检查 Slack #marketing-ops 频道中是否恰好有一条消息内容完全等于预期摘要文本", + "check_logic": "获取 Slack current_state 中 messages['marketing-ops'],统计 content.strip() 完全等于 EXPECTED_SLACK_TEXT 的消息数量;exact==1 得 0.20,否则 0.0(包括 0 条或多条)", + "pass_condition": "恰好存在 1 条内容完全匹配的消息" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件得分相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接返回 0.0", + "三个 mock 的 state_diff 全部为空:判定为初始无进展状态,返回 0.0", + "Airtable 无记录:Component 1 和 Component 2 得 0.0", + "HubSpot 无 contacts:Component 3 得 0.0", + "Slack #marketing-ops 无消息、消息数量不为 1 或文本不完全匹配:Component 4 得 0.0", + "HubSpot 中 unqualified leads 被错误设为 MQL:Component 3 判定为失败(但得分仍按 qualified 正确比例计算)" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。然后分别向 Airtable、HubSpot、Slack 三个 mock 服务的 /go?sid= 端点获取 current_state 和 state_diff。如果三个 mock 的 state_diff 均为空,说明环境仍处于初始基线状态(无进展),直接返回 0.0。接着按顺序执行四个独立组件检查:1) 检查 Airtable 中 8 条参会者记录的 5 个字段是否完全匹配预期,按匹配比例给分(最高 0.35);2) 检查 Airtable 中 8 条记录的 'Pushed to HubSpot?' 字段是否按 qualified/unqualified 分别标记为 Yes/No,按正确比例给分(最高 0.15);3) 检查 HubSpot 中 5 个 qualified leads 的 lifecycleStage 是否为 'mql' 且 timeline 中包含指定 note,同时确保 3 个 unqualified leads 未被改为 MQL,按 qualified 正确比例给分(最高 0.30),unqualified 被污染会在 detail 中记录但不额外扣分;4) 检查 Slack #marketing-ops 频道中是否恰好有一条消息内容完全等于预期文本,完全匹配得 0.20,否则 0.0。各组件得分相加得到总分,最终用 min(总分, 1.0) 钳制并四舍五入到 4 位小数返回。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不包含任何额外文本、Markdown 代码块标记或思考过程。\n\n让我仔细阅读源码并提取所需信息:\n\n1. **task_id**: 从 docstring 中提取到 \"prof18_webinar_mql_002\"\n2. **domain**: 从 docstring 中提取到 \"mock_websites\"(注释说 libreoffice_calc label is a misnomer)\n3. **summary**: 一句话概括:验证在 Airtable、HubSpot 和 Slack 三个 mock 服务中完成 webinar MQL 管道任务的状态(8条参会者记录、HubSpot推送标记、MQL转换与备注、Slack摘要消息)。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: \n - /tmp/task_web_sid\n - airtable mock @ http://28.7.186.212:8129\n - hubspot mock @ http://28.7.186.212:8170\n - slack mock @ http://28.7.186.212:8198\n\n6. **scoring_components**:\n - Component 1: Airtable 8 attendee records correct, weight 0.35\n - 检查 8 条参会者记录的 Name/Email/Company/Attended Live?/Qualified? 是否正确\n - 通过条件:8条全部匹配\n - 部分得分:matched/8 * 0.35\n - Component 2: Airtable Pushed-to-HubSpot flags correct, weight 0.15\n - 检查 qualified(5条) 的 'Pushed to HubSpot?' 是否为 'Yes',unqualified(3条) 是否为 'No'\n - 通过条件:8条全部正确\n - 部分得分:correct/8 * 0.15\n - Component 3: HubSpot 5 qualified = MQL + note, weight 0.30\n - 检查 5 个 qualified leads 的 lifecycleStage 是否为 'mql' 且 timeline 中有包含 \"Source: Q3 Product Launch Webinar\" 的 note\n - 检查 3 个 unqualified leads 的 lifecycleStage 不是 'mql'\n - 部分得分:(qualified_correct/5) * 0.30(注意:如果 unqualified 被错误改为 MQL,会失败但分数仍按 qualified_ok/5 计算,不过 detail 会指出问题)\n - 通过条件:5个qualified都是MQL+note,且3个unqualified都不是MQL\n - Component 4: Slack #marketing-ops summary message, weight 0.20\n - 检查 #marketing-ops 频道是否恰好有一条消息内容完全等于 EXPECTED_SLACK_TEXT\n - 通过条件:exactly == 1\n - 部分得分:无,要么0.20要么0.0(代码里 if exact == 1 返回 0.20,其他情况返回 0.0)\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限(虽然总和就是1.0)\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL 错误,返回 0.0\n - 从三个 mock 获取 current_state 失败(会打印 WARN,但继续执行,返回空 dict)\n - 所有三个 mock 的 state_diff 都为空 -> 检测到无任务进展,返回 0.0\n - Component 1: 无 Airtable records -> 0分\n - Component 2: 无 Airtable records -> 0分\n - Component 3: 无 HubSpot contacts -> 0分;unqualified 被错误设为 MQL(detail 记录,但分数仍按 qualified 比例计算)\n - Component 4: 无 Slack messages -> 0分;消息数量不等于1(0或多于1)-> 0分;内容不完全匹配但包含关键词 -> 0分(有提示)\n\n10. **scoring_logic_explanation**: \n - 脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 然后分别向 Airtable、HubSpot、Slack 三个 mock 服务的 /go?sid= 端点获取 current_state 和 state_diff。\n - 如果三个 mock 的 state_diff 均为空,说明环境仍处于初始基线状态(无进展),直接返回 0.0。\n - 接着按顺序执行四个独立组件检查:\n 1. 检查 Airtable 中 8 条参会者记录的 5 个字段(Name/Email/Company/Attended Live?/Qualified?)是否完全匹配预期,按匹配比例给分(最高 0.35)。\n 2. 检查 Airtable 中 8 条记录的 \"Pushed to HubSpot?\" 字段是否按 qualified/unqualified 分别标记为 Yes/No,按正确比例给分(最高 0.15)。\n 3. 检查 HubSpot 中 5 个 qualified leads 的 lifecycleStage 是否为 \"mql\" 且 timeline 中包含指定 note,同时确保 3 个 unqualified leads 未被改为 MQL;按 qualified 正确比例给分(最高 0.30),unqualified 被污染会在 detail 中记录但不额外扣分(只是导致不通过)。\n 4. 检查 Slack #marketing-ops 频道中是否恰好有一条消息内容完全等于预期文本,完全匹配得 0.20,否则 0.0。\n - 各组件得分相加得到总分,最终用 min(总分, 1.0) 钳制并四舍五入到 4 位小数返回。\n\n11. **confidence**: 1.0(源码完整清晰)\n\n让我再仔细检查一下 Component 3 的部分得分逻辑。代码中:\n```python\nfrac = qualified_ok / len(QUALIFIED_EMAILS)\nscore = round(0.30 * frac, 4)\n```\n即使 unq_bad 非空,分数仍然是按 qualified_ok/5 计算。所以 unqualified 被错误改为 MQL 不会导致额外扣分,只是导致 passed=False。这应该在 check_logic 和 pass_condition 中准确描述。\n\nComponent 4 的部分得分:代码中 exact == 1 得 0.20,否则都是 0.0。contains 检查只是为了给出更详细的 failure detail,不给 partial credit。所以 weight 0.20,但无部分得分。\n\n现在构建 JSON。注意:\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n- 不要输出 Markdown 代码块标记。\n- 不要输出额外解释。\n- 第一个字符必须是 {,最后一个字符必须是 }。\n\n让我用中文填写各个字段。\n\nscoring_components 数组:\n[\n {\n \"name\": \"Component 1\",\n \"weight\": 0.35,\n \"description\": \"检查 Airtable 中 8 条参会者记录的 Name、Email、Company、Attended Live?、Qualified? 字段是否与预期完全一致\",\n \"check_logic\": \"从 Airtable current_state 中提取 tbl_webinar_attendees 表的 records,按 fld_email 建立索引,逐一比对 8 条预期记录的 fld_attendee_name、fld_company、fld_attended_live、fld_qualified 是否完全匹配;matched / 8 * 0.35 计算得分\",\n \"pass_condition\": \"8 条记录全部匹配\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.15,\n \"description\": \"检查 Airtable 中 8 条记录的 'Pushed to HubSpot?' 字段是否按 qualified/unqualified 分别标记为 Yes/No\",\n \"check_logic\": \"遍历 8 条预期记录,qualified='Yes' 时期望 fld_pushed='Yes',否则期望 'No';correct / 8 * 0.15 计算得分\",\n \"pass_condition\": \"8 条记录的 Pushed 标记全部正确\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.30,\n \"description\": \"检查 HubSpot 中 5 个 qualified leads 的 lifecycleStage 是否为 'mql' 且 timeline 中包含指定 note;同时 3 个 unqualified leads 的 lifecycleStage 不得为 'mql'\",\n \"check_logic\": \"对 5 个 qualified 邮箱检查 lifecycleStage=='mql'(不区分大小写)且 timeline 中存在 type='note' 且 body 包含 'Source: Q3 Product Launch Webinar';对 3 个 unqualified 邮箱检查 lifecycleStage!='mql';得分按 qualified_ok / 5 * 0.30 计算,unqualified 被错误改为 mql 会导致不通过但不额外扣分\",\n \"pass_condition\": \"5 个 qualified 均为 MQL 且含正确 note,且 3 个 unqualified 未被改为 MQL\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.20,\n \"description\": \"检查 Slack #marketing-ops 频道中是否恰好有一条消息内容完全等于预期摘要文本\",\n \"check_logic\": \"获取 Slack current_state 中 messages['marketing-ops'],统计 content.strip() 完全等于 EXPECTED_SLACK_TEXT 的消息数量;exact==1 得 0.20,否则 0.0(包括 0 条或多条)\",\n \"pass_condition\": \"恰好存在 1 条内容完全匹配的消息\"\n }\n]\n\nfailure_modes:\n- \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接返回 0.0\"\n- \"三个 mock 的 state_diff 全部为空:判定为初始无进展状态,返回 0.0\"\n- \"Airtable 无记录:Component 1 和 2 得 0.0\"\n- \"HubSpot 无 contacts:Component 3 得 0.0\"\n- \"Slack #marketing-ops 无消息、消息数量不为 1 或文本不完全匹配:Component 4 得 0.0\"\n- \"HubSpot 中 unqualified leads 被错误设为 MQL:Component 3 判定为失败(但得分仍按 qualified 正确比例计算)\"\n\nscore_aggregation: 各组件得分相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数。\n\n让我再确认一下 domain。docstring 说 \"Domain: mock_websites (libreoffice_calc label is a misnomer; this is a 3-mock HTTP pipeline)\",所以 domain 应该是 \"mock_websites\"。\n\ndata_sources 应该包含:\n- \"/tmp/task_web_sid\"\n- \"airtable mock @ http://28.7.186.212:8129\"\n- \"hubspot mock @ http://28.7.186.212:8170\"\n- \"slack mock @ http://28.7.186.212:8198\"\n\n或者简洁点:\n- \"/tmp/task_web_sid\"\n- \"http://28.7.186.212:8129 (airtable)\"\n- \"http://28.7.186.212:8170 (hubspot)\"\n- \"http://28.7.186.212:8198 (slack)\"\n\n我觉得用中文描述数据源也可以,保留 URL。\n\n再检查一下 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n\n确保所有字符串都是中文(除了代码标识符和 task_id/domain)。\n\n让我再仔细看看 Component 3 的 check_logic。代码中:\n```python\nnote_ok = any(\n EXPECTED_NOTE in (t.get(\"body\", \"\") or \"\")\n for t in (c.get(\"timeline\") or [])\n if t.get(\"type\") == \"note\"\n)\n```\n所以是检查 timeline 中 type 为 \"note\" 的项的 body 包含 EXPECTED_NOTE。\n\n还有 Component 1 的字段名:\n- fld_attendee_name\n- fld_email\n- fld_company\n- fld_attended_live\n- fld_qualified\n\nComponent 2 的字段名:\n- fld_pushed\n\n这些在 check_logic 中应该准确引用。\n\n现在我可以写出最终的 JSON 了。 {\"task_id\":\"prof18_webinar_mql_002\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Airtable、HubSpot、Slack 三个 mock 服务中完成 webinar MQL 管道任务的状态,包括 8 条参会者记录、HubSpot 推送标记、MQL 转换与备注、Slack 摘要消息。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"http://28.7.186.212:8129 (airtable mock)\",\"http://28.7.186.212:8170 (hubspot mock)\",\"http://28.7.186.212:8198 (slack mock)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.35,\"description\":\"检查 Airtable 中 8 条参会者记录的 Name、Email、Company、Attended Live?、Qualified? 字段是否与预期完全一致\",\"check_logic\":\"从 Airtable current_state 中提取 tables['tbl_webinar_attendees'] 的 records,按 fld_email 建立索引,逐一比对 8 条预期记录的 fld_attendee_name、fld_company、fld_attended_live、fld_qualified 是否完全匹配;得分 = matched / 8 * 0.35\",\"pass_condition\":\"8 条记录全部匹配\"},{\"name\":\"Component 2\",\"weight\":0.15,\"description\":\"检查 Airtable 中 8 条记录的 'Pushed to HubSpot?' 字段是否按 qualified/unqualified 分别标记为 Yes/No\",\"check_logic\":\"遍历 8 条预期记录,qualified='Yes' 时期望 fld_pushed='Yes',否则期望 'No';得分 = correct / 8 * 0.15\",\"pass_condition\":\"8 条记录的 Pushed 标记全部正确\"},{\"name\":\"Component 3\",\"weight\":0.30,\"description\":\"检查 HubSpot 中 5 个 qualified leads 的 lifecycleStage 是否为 'mql' 且 timeline 中包含指定 note;同时 3 个 unqualified leads 的 lifecycleStage 不得为 'mql'\",\"check_logic\":\"对 5 个 qualified 邮箱检查 lifecycleStage=='mql'(不区分大小写)且 timeline 中存在 type='note' 且 body 包含 'Source: Q3 Product Launch Webinar';对 3 个 unqualified 邮箱检查 lifecycleStage!='mql';得分按 qualified_ok / 5 * 0.30 计算,unqualified 被错误改为 mql 会导致不通过但不额外扣分\",\"pass_condition\":\"5 个 qualified 均为 MQL 且含正确 note,且 3 个 unqualified 未被改为 MQL\"},{\"name\":\"Component 4\",\"weight\":0.20,\"description\":\"检查 Slack #marketing-ops 频道中是否恰好有一条消息内容完全等于预期摘要文本\",\"check_logic\":\"获取 Slack current_state 中 messages['marketing-ops'],统计 content.strip() 完全等于 EXPECTED_SLACK_TEXT 的消息数量;exact==1 得 0.20,否则 0.0(包括 0 条或多条)\",\"pass_condition\":\"恰好存在 1 条内容完全匹配的消息\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件得分相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接返回 0.0\",\"三个 mock 的 state_diff 全部为空:判定为初始无进展状态,返回 0.0\",\"Airtable 无记录:Component 1 和 Component 2 得 0.0\",\"HubSpot 无 contacts:Component 3 得 0.0\",\"Slack #marketing-ops 无消息、消息数量不为 1 或文本不完全匹配:Component 4 得 0.0\",\"HubSpot 中 unqualified leads 被错误设为 MQL:Component 3 判定为失败(但得分仍按 qualified 正确比例计算)\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。然后分别向 Airtable、HubSpot、Slack 三个 mock 服务的 /go?sid= 端点获取 current_state 和 state_diff。如果三个 mock 的 state_diff 均为空,说明环境仍处于初始基线状态(无进展),直接返回 0.0。接着按顺序执行四个独立组件检查:1) 检查 Airtable 中 8 条参会者记录的 5 个字段是否完全匹配预期,按匹配比例给分(最高 0.35);2) 检查 Airtable 中 8 条记录的 'Pushed to HubSpot?' 字段是否按 qualified/unqualified 分别标记为 Yes/No,按正确比例给分(最高 0.15);3) 检查 HubSpot 中 5 个 qualified leads 的 lifecycleStage 是否为 'mql' 且 timeline 中包含指定 note,同时确保 3 个 unqualified leads 未被改为 MQL,按 qualified 正确比例给分(最高 0.30),unqualified 被污染会在 detail 中记录但不额外扣分;4) 检查 Slack #marketing-ops 频道中是否恰好有一条消息内容完全等于预期文本,完全匹配得 0.20,否则 0.0。各组件得分相加得到总分,最终用 min(总分, 1.0) 钳制并四舍五入到 4 位小数返回。\",\"confidence\":1.0}" +} diff --git a/ops_grade_report_011__long/.PLACEHOLDER b/ops_grade_report_011__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/ops_grade_report_011__long/.PLACEHOLDER @@ -0,0 +1,5 @@ +This directory is intentionally empty. +It exists only to satisfy start_our_benchmark_test.sh's uniform +'cache_dir// must exist' precheck. Non-mock tasks do not use +cua_gym cache; their evaluators read a vm_file tarball instead. +See docs/0716_迁移执行日志.md § S15 for details. diff --git a/ops_grade_report_011__long/0b50944b-e47d-590b-8c40-48b36c880427_template.docx b/ops_grade_report_011__long/0b50944b-e47d-590b-8c40-48b36c880427_template.docx new file mode 100644 index 0000000000000000000000000000000000000000..3386621a03cfebcc54c1e8af156c6c5e0c576904 Binary files /dev/null and b/ops_grade_report_011__long/0b50944b-e47d-590b-8c40-48b36c880427_template.docx differ diff --git a/ops_grade_report_011__long/4bdbf8db-66f1-5daf-952d-2dce205c5951_roster.json b/ops_grade_report_011__long/4bdbf8db-66f1-5daf-952d-2dce205c5951_roster.json new file mode 100644 index 0000000000000000000000000000000000000000..bd1e2683e35ee338e6cdae3ec93c76a0121a05a0 --- /dev/null +++ b/ops_grade_report_011__long/4bdbf8db-66f1-5daf-952d-2dce205c5951_roster.json @@ -0,0 +1,9 @@ +{ + "eligible": [ + "Alice Chen", + "Bob Kumar", + "Carol Diaz", + "David Okafor", + "Eve Tanaka" + ] +} diff --git a/ops_grade_report_011__long/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py b/ops_grade_report_011__long/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py new file mode 100644 index 0000000000000000000000000000000000000000..b48c427a8c05b22cf22112913ad02b2ee0ba26f8 --- /dev/null +++ b/ops_grade_report_011__long/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +"""Local fake SMTP daemon for task multi_apps_b2d9report. + +Runs on the VM (NOT part of the evaluator). Listens on localhost:2525, accepts +any mail for any recipient, and saves each delivered message verbatim as an +.eml file under /home/user/fake_smtp_mail/. + +Why: + Thunderbird's "Send" workflow requires a real SMTP endpoint to reach + "message accepted by server" state. Pointing at a non-existent host (e.g. + smtp.invalid) causes Thunderbird to surface modal error dialogs that + derail the agent. Pointing at a local always-accepting daemon removes + that failure mode while giving the evaluator a clean file-based signal + (each successful send -> one .eml on disk). + +Design constraints: + * Zero third-party deps — uses only the Python 3 stdlib socket module. + * Portable across Python 3.8..3.13+ (no reliance on the removed + `asyncore` / `smtpd` modules). OSWorld VM ships Python 3.10 today but + we want this script to keep working if the VM ever bumps. + * Silent by default except for a single startup log line. + * Crash-resistant: a broken connection does not bring the daemon down. + +Protocol support: + We implement the tiny subset of SMTP that Thunderbird's outbound worker + uses in "plain, no auth, no STARTTLS, no AUTH" mode: + HELO / EHLO -> 250 + MAIL FROM -> 250 + RCPT TO -> 250 (any recipient accepted) + DATA -> 354, then read until CRLF.CRLF -> 250 + NOOP -> 250 + RSET -> 250 + QUIT -> 221 + anything else -> 502 + EHLO advertises 8BITMIME + SMTPUTF8 + SIZE. No AUTH capability is + advertised, which combined with smtp1.authMethod=1 keeps Thunderbird + from attempting authentication. + +File-naming scheme inside MAIL_DIR: + __<6-hex>.eml + - NNN is a zero-padded monotonic counter (001, 002, ...) so that + lexicographic sort matches send order even within the same second. +""" + +import os +import secrets +import socket +import sys +import threading +import time + +HOST = "127.0.0.1" +PORT = 2525 +MAIL_DIR = "/home/user/fake_smtp_mail" + +_counter_lock = threading.Lock() +_counter = {"n": 0} + + +# ----------------------------------------------------------------------------- +# Persistence +# ----------------------------------------------------------------------------- + +def _save_mail(mailfrom: str, rcpttos: list, data: bytes) -> str: + os.makedirs(MAIL_DIR, exist_ok=True) + + with _counter_lock: + _counter["n"] += 1 + seq = _counter["n"] + + stamp = time.strftime("%Y%m%d_%H%M%S", time.localtime()) + suffix = secrets.token_hex(3) + fname = f"{seq:03d}_{stamp}_{suffix}.eml" + fpath = os.path.join(MAIL_DIR, fname) + + envelope = ( + f"X-Envelope-From: {mailfrom}\r\n" + f"X-Envelope-To: {', '.join(rcpttos)}\r\n" + ).encode("ascii", errors="replace") + + with open(fpath, "wb") as f: + f.write(envelope) + f.write(data) + + return fpath + + +# ----------------------------------------------------------------------------- +# Line-based socket helpers (SMTP is CRLF-terminated lines) +# ----------------------------------------------------------------------------- + +class _LineReader: + """Read CRLF-terminated lines from a blocking socket.""" + + def __init__(self, sock: socket.socket): + self.sock = sock + self.buf = b"" + + def readline(self, max_bytes: int = 1 << 20) -> bytes: + """Return one line including its trailing CRLF (or '' on EOF).""" + while b"\r\n" not in self.buf: + if len(self.buf) > max_bytes: + raise ValueError("line too long") + chunk = self.sock.recv(4096) + if not chunk: + # connection closed; return whatever is buffered + line, self.buf = self.buf, b"" + return line + self.buf += chunk + line, _, rest = self.buf.partition(b"\r\n") + self.buf = rest + return line + b"\r\n" + + def read_until_dot(self, max_bytes: int = 50 << 20) -> bytes: + """Read DATA payload until a line containing only '.'. + + Returns the payload with dot-stuffing undone and the terminator + stripped. Trailing CRLF after the last data line is preserved. + """ + chunks = [] + total = 0 + while True: + line = self.readline() + if not line: + # premature EOF — treat as end of DATA + break + if line == b".\r\n": + break + # SMTP dot-stuffing: client prefixes any line starting with '.' + # with an extra '.', which we must strip. + if line.startswith(b".."): + line = line[1:] + chunks.append(line) + total += len(line) + if total > max_bytes: + raise ValueError("DATA too large") + return b"".join(chunks) + + +# ----------------------------------------------------------------------------- +# Single-session handler +# ----------------------------------------------------------------------------- + +def _send(sock: socket.socket, code: int, text: str) -> None: + sock.sendall(f"{code} {text}\r\n".encode("ascii", errors="replace")) + + +def _send_multi(sock: socket.socket, code: int, lines: list) -> None: + """Send a multi-line SMTP reply (all lines except last prefixed '-').""" + last = len(lines) - 1 + out = [] + for i, line in enumerate(lines): + sep = " " if i == last else "-" + out.append(f"{code}{sep}{line}") + sock.sendall(("\r\n".join(out) + "\r\n").encode("ascii", errors="replace")) + + +def _handle_session(conn: socket.socket, peer) -> None: + try: + reader = _LineReader(conn) + _send(conn, 220, "localhost fake SMTP ready") + + mailfrom = None + rcpttos: list = [] + + while True: + raw = reader.readline() + if not raw: + return # client hung up + + try: + line = raw.rstrip(b"\r\n").decode("utf-8", errors="replace") + except Exception: # noqa: BLE001 + _send(conn, 500, "bad line") + continue + + cmd, _, arg = line.partition(" ") + cmd_up = cmd.upper() + + if cmd_up == "HELO": + _send(conn, 250, "localhost") + elif cmd_up == "EHLO": + _send_multi(conn, 250, [ + "localhost", + "SIZE 52428800", + "8BITMIME", + "SMTPUTF8", + "HELP", + ]) + elif cmd_up == "MAIL": + # "MAIL FROM:" possibly with SIZE=... etc. + addr = _extract_addr(arg) + mailfrom = addr or "" + rcpttos = [] + _send(conn, 250, "OK") + elif cmd_up == "RCPT": + addr = _extract_addr(arg) + if addr is None: + _send(conn, 501, "bad RCPT") + else: + rcpttos.append(addr) + _send(conn, 250, "OK") + elif cmd_up == "DATA": + if mailfrom is None or not rcpttos: + _send(conn, 503, "need MAIL + RCPT first") + continue + _send(conn, 354, "end data with .") + try: + payload = reader.read_until_dot() + except Exception as e: # noqa: BLE001 + _send(conn, 552, f"read error: {e}") + continue + try: + path = _save_mail(mailfrom, rcpttos, payload) + sys.stderr.write(f"[fake_smtpd] saved {path}\n") + sys.stderr.flush() + except Exception as e: # noqa: BLE001 + sys.stderr.write(f"[fake_smtpd] save failed: {e}\n") + _send(conn, 451, "local error storing message") + mailfrom, rcpttos = None, [] + continue + _send(conn, 250, "OK message accepted") + mailfrom, rcpttos = None, [] + elif cmd_up == "RSET": + mailfrom, rcpttos = None, [] + _send(conn, 250, "OK") + elif cmd_up == "NOOP": + _send(conn, 250, "OK") + elif cmd_up == "QUIT": + _send(conn, 221, "bye") + return + elif cmd_up == "VRFY": + _send(conn, 252, "cannot verify") + elif cmd_up == "HELP": + _send(conn, 214, "HELO EHLO MAIL RCPT DATA RSET NOOP QUIT") + else: + _send(conn, 502, f"command not implemented: {cmd_up}") + except (ConnectionResetError, BrokenPipeError, OSError): + pass + except Exception as e: # noqa: BLE001 + sys.stderr.write(f"[fake_smtpd] session {peer} error: {e}\n") + finally: + try: + conn.close() + except Exception: # noqa: BLE001 + pass + + +def _extract_addr(arg: str): + """Parse '' or 'FROM:' / 'TO:' (with optional params). + + Returns the address string, possibly empty (empty return-path is legal + for bounces), or None on parse failure. + """ + if not arg: + return None + # Strip optional 'FROM:' / 'TO:' prefix (case-insensitive), plus spaces + colon = arg.find(":") + if colon != -1 and arg[:colon].upper() in ("FROM", "TO"): + arg = arg[colon + 1 :].lstrip() + # Now expect [params...] + if not arg.startswith("<"): + # tolerate bare address + return arg.split()[0] + end = arg.find(">") + if end == -1: + return None + return arg[1:end] + + +# ----------------------------------------------------------------------------- +# Main loop +# ----------------------------------------------------------------------------- + +def main() -> None: + os.makedirs(MAIL_DIR, exist_ok=True) + + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + srv.bind((HOST, PORT)) + except OSError as e: + sys.stderr.write(f"[fake_smtpd] cannot bind {HOST}:{PORT}: {e}\n") + sys.exit(1) + srv.listen(16) + + sys.stderr.write( + f"[fake_smtpd] listening on {HOST}:{PORT}, mails -> {MAIL_DIR}\n" + ) + sys.stderr.flush() + + try: + while True: + try: + conn, peer = srv.accept() + except KeyboardInterrupt: + break + except OSError as e: + sys.stderr.write(f"[fake_smtpd] accept error: {e}\n") + continue + t = threading.Thread( + target=_handle_session, args=(conn, peer), daemon=True + ) + t.start() + finally: + try: + srv.close() + except Exception: # noqa: BLE001 + pass + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ops_grade_report_011__long/df91db45-221a-5476-9b39-947185cc055f_grades.xlsx b/ops_grade_report_011__long/df91db45-221a-5476-9b39-947185cc055f_grades.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..5cab583b36743083eca03ef70b6fb8c433be7949 Binary files /dev/null and b/ops_grade_report_011__long/df91db45-221a-5476-9b39-947185cc055f_grades.xlsx differ diff --git a/ops_meeting_schedule_004__long/_cua_gym_vm_bridge.sh b/ops_meeting_schedule_004__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_meeting_schedule_004__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ops_meeting_schedule_004__long/initial_setup.py b/ops_meeting_schedule_004__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e92060dba43a63ae645f7fe6832b98458d714b5a --- /dev/null +++ b/ops_meeting_schedule_004__long/initial_setup.py @@ -0,0 +1,566 @@ +""" +Initial Setup: V4 — Email requests to calendar events +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_v4.py +Variant: eval +Mocks: gmail_mock,google_calendar_mock,slack_mock +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +APP_STATES = [('http://28.7.184.198:8138', + {'emails': [{'id': 'm0', + 'threadId': 'thread_m0', + 'from': {'name': 'Scheduler Bot', 'email': 'scheduler@company.com', 'avatar': ''}, + 'to': [{'name': 'John Smith', 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': 'Meeting request', + 'body': 'Tue March 12 at 3pm for 30 minutes with Bob', + 'snippet': 'Tue March 12 at 3pm for 30 minutes with Bob', + 'timestamp': '2024-03-11T09:00:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + 'meeting': {'start': '2024-03-12T15:00', 'end': '2024-03-12T15:30', 'attendees': ['Bob']}}, + {'id': 'm1', + 'threadId': 'thread_m1', + 'from': {'name': 'Scheduler Bot', 'email': 'scheduler@company.com', 'avatar': ''}, + 'to': [{'name': 'John Smith', 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': 'Meeting request', + 'body': 'next Monday morning 9am with Cara, 1 hour', + 'snippet': 'next Monday morning 9am with Cara, 1 hour', + 'timestamp': '2024-03-11T09:01:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + 'meeting': {'start': '2024-03-18T09:00', 'end': '2024-03-18T10:00', 'attendees': ['Cara']}}, + {'id': 'm2', + 'threadId': 'thread_m2', + 'from': {'name': 'Scheduler Bot', 'email': 'scheduler@company.com', 'avatar': ''}, + 'to': [{'name': 'John Smith', 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': 'Meeting request', + 'body': 'Thursday 2-3:30 with Dan and Eve', + 'snippet': 'Thursday 2-3:30 with Dan and Eve', + 'timestamp': '2024-03-11T09:02:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + 'meeting': {'start': '2024-03-14T14:00', 'end': '2024-03-14T15:30', 'attendees': ['Dan', 'Eve']}}, + {'id': 'm3', + 'threadId': 'thread_m3', + 'from': {'name': 'Scheduler Bot', 'email': 'scheduler@company.com', 'avatar': ''}, + 'to': [{'name': 'John Smith', 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': 'Meeting request', + 'body': 'lunch next week Wednesday with Finn', + 'snippet': 'lunch next week Wednesday with Finn', + 'timestamp': '2024-03-11T09:03:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + 'meeting': {'start': '2024-03-20T12:00', 'end': '2024-03-20T13:00', 'attendees': ['Finn']}}, + {'id': 'm4', + 'threadId': 'thread_m4', + 'from': {'name': 'Scheduler Bot', 'email': 'scheduler@company.com', 'avatar': ''}, + 'to': [{'name': 'John Smith', 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': 'Meeting request', + 'body': 'this Friday 4pm for 45 minutes with Gus', + 'snippet': 'this Friday 4pm for 45 minutes with Gus', + 'timestamp': '2024-03-11T09:04:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + 'meeting': {'start': '2024-03-15T16:00', 'end': '2024-03-15T16:45', 'attendees': ['Gus']}}, + {'id': 'm5', + 'threadId': 'thread_m5', + 'from': {'name': 'Scheduler Bot', 'email': 'scheduler@company.com', 'avatar': ''}, + 'to': [{'name': 'John Smith', 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': 'Meeting request', + 'body': 'Monday 10am, 30 min, with Hana and Ivy', + 'snippet': 'Monday 10am, 30 min, with Hana and Ivy', + 'timestamp': '2024-03-11T09:05:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + 'meeting': {'start': '2024-03-11T10:00', 'end': '2024-03-11T10:30', 'attendees': ['Hana', 'Ivy']}}], + 'user': {'userId': 'u1', + 'username': 'John Smith', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1'}, + 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}], + 'drafts': [], + 'settings': {'density': 'default', + 'undoSend': 10, + 'categoryTabs': {'primary': True, + 'social': True, + 'promotions': True, + 'updates': False, + 'forums': False}}, + 'today': '2024-03-11'}), + ('http://28.7.184.198:8141', {'events': [], 'today': '2024-03-11'}), + ('http://28.7.184.198:8178', + # Slack workspace. + # Task channel is #team -- the agent must post the + # "Scheduled {n} meetings" line there. The other channels + # (#general / #announcements / #random) plus the prior chatter are + # purely watermark decoration so the workspace doesn't look freshly-empty; + # reward.py only inspects #team, so these extras do not affect scoring. + # IMPORTANT: #team MUST start with NO messages -- the reward awards full + # slack credit for any message in #team, so we never pre-seed it. + {'channels': [{'channelId': 'general', + 'name': 'general', + 'description': 'Company-wide announcements and work-based matters', + 'topic': 'Welcome to Acme Corp!', + 'isPrivate': False, + 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_2', + 'createdAt': '2024-02-01T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + {'channelId': 'announcements', + 'name': 'announcements', + 'description': 'Important company updates', + 'topic': 'Read-mostly. Big news only.', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_2', + 'createdAt': '2024-02-01T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + {'channelId': 'random', + 'name': 'random', + 'description': 'Non-work banter and watercooler chat', + 'topic': 'Coffee, memes, weekend plans', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_3', + 'createdAt': '2024-02-01T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + {'channelId': 'team', + 'name': 'team', + 'description': '', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1'], + 'createdBy': 'user_1', + 'createdAt': '2026-06-06T08:54:59Z', + 'pinnedMessages': [], + 'unreadCount': 0}], + 'currentUser': {'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'users': [{'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_2', + 'fullName': 'Maya Lindqvist', + 'displayName': 'Maya', + 'email': 'maya.lindqvist@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'People Ops', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'Europe/Stockholm'}, + {'userId': 'user_3', + 'fullName': 'Hiroshi Tanabe', + 'displayName': 'Hiroshi', + 'email': 'hiroshi.tanabe@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Engineering', + 'status': 'away', + 'statusMessage': 'In a meeting', + 'statusEmoji': ':calendar:', + 'timeZone': 'Asia/Tokyo'}, + {'userId': 'user_4', + 'fullName': 'Olivia Becker', + 'displayName': 'Olivia', + 'email': 'olivia.becker@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': 'Marketing', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/Los_Angeles'}], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'messages': {'general': [{'messageId': 'm_g_1', + 'senderId': 'user_2', + 'content': 'Morning everyone -- reminder the all-hands deck is due Wednesday EOD.', + 'timestamp': '2024-03-08T13:02:00Z', + 'reactions': [], + 'isEdited': False, + 'threadId': None, + 'attachments': []}, + {'messageId': 'm_g_2', + 'senderId': 'user_4', + 'content': 'Thanks Maya! Will share the Q1 marketing slides today.', + 'timestamp': '2024-03-08T13:05:00Z', + 'reactions': [{'emoji': '\U0001F44D', 'users': ['user_1', 'user_3']}], + 'isEdited': False, + 'threadId': None, + 'attachments': []}], + 'announcements': [], + 'random': [{'messageId': 'm_r_1', + 'senderId': 'user_4', + 'content': 'Anyone tried the new ramen place on 3rd? Verdict?', + 'timestamp': '2024-03-09T18:50:00Z', + 'reactions': [{'emoji': '\U0001F35C', 'users': ['user_3']}], + 'isEdited': False, + 'threadId': None, + 'attachments': []}, + {'messageId': 'm_r_2', + 'senderId': 'user_3', + 'content': "10/10, get the spicy miso. Bring tissues though, it's no joke.", + 'timestamp': '2024-03-09T18:55:00Z', + 'reactions': [{'emoji': '\U0001F605', 'users': ['user_1', 'user_4']}], + 'isEdited': False, + 'threadId': None, + 'attachments': []}], + # IMPORTANT: leave #team empty; reward awards full slack + # credit for any message in #team. + 'team': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + '_task_adapter': {'task_id': 'lc_v4', 'variant': 'eval'}})] + + +for app_url, state in APP_STATES: + resp = requests.post( + f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {app_url}: {resp.text}' + ) + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}' + ) + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/ops_meeting_schedule_004__long/reward.py b/ops_meeting_schedule_004__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..561dbb4c4a75f643a91d29de6ced2c8ea8bacf6d --- /dev/null +++ b/ops_meeting_schedule_004__long/reward.py @@ -0,0 +1,422 @@ +""" +Reward Script: V4 — Email requests to calendar events +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_v4.py +Variant: eval +Mocks: gmail_mock,google_calendar_mock,slack_mock +""" +import copy +import re +import sys + +import requests + +from datetime import datetime, timezone, timedelta + +TZ_PLUS_8 = timezone(timedelta(hours=8)) + +def parse_as_utc(s, default_tz=TZ_PLUS_8): + """ + Parse an ISO datetime string and convert it to UTC. + + Assumption: + - If the string has Z or +00:00, it is already timezone-aware. + - If the string has no timezone, treat it as UTC+8. + """ + if not s: + return None + + s = str(s).strip() + + # Python's fromisoformat prefers +00:00 over Z + if s.endswith("Z"): + s = s[:-1] + "+00:00" + + dt = datetime.fromisoformat(s) + + # Example: "2024-03-18T09:00" has no timezone. + # Treat it as UTC+8. + if dt.tzinfo is None: + dt = dt.replace(tzinfo=default_tz) + + return dt.astimezone(timezone.utc) + + +def norm_dt(s): + dt = parse_as_utc(s) + if dt is None: + return "" + return dt.isoformat(timespec="seconds") + + +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +APP_URLS = {'gmail': 'http://28.7.184.198:8138', 'google_calendar': 'http://28.7.184.198:8141', 'slack': 'http://28.7.184.198:8178'} +_GO_CACHE = {} + + +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def f1(true_set, pred_set): + if not true_set and not pred_set: + return 1.0 + tp = len(true_set & pred_set) + if tp == 0: + return 0.0 + prec = tp / len(pred_set) + rec = tp / len(true_set) + return 2 * prec * rec / (prec + rec) + + +def by_id(items, key='id'): + return {it.get(key): it for it in (items or []) if isinstance(it, dict)} + + +def has_text(haystack, *needles): + s = (haystack or '').lower() + return any(n.lower() in s for n in needles) + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _parse_cell_id(cell_id): + if not isinstance(cell_id, str) or not cell_id: + return None + idx = 0 + while idx < len(cell_id) and cell_id[idx].isalpha(): + idx += 1 + if idx == 0 or idx >= len(cell_id): + return None + col = 0 + for ch in cell_id[:idx].upper(): + col = col * 26 + (ord(ch) - ord('A') + 1) + try: + row = int(cell_id[idx:]) + except ValueError: + return None + return row, col - 1 + + +def _extract_rows_from_workbook(state): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} + + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') or 'Sheet1' + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + + headers = headers_by_sheet.get(name) + if not headers: + cols = [] + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx != 1: + continue + value = '' + if isinstance(cell, dict): + value = cell.get('value', '') + elif cell is not None: + value = str(cell) + if value is not None and str(value) != '': + cols.append((col_idx, str(value))) + headers = [v for _, v in sorted(cols)] + + if not headers: + continue + + by_row = {} + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx <= 1 or col_idx >= len(headers): + continue + if isinstance(cell, dict): + value = cell.get('value', '') + else: + value = cell + by_row.setdefault(row_idx, {})[headers[col_idx]] = value + + rows = [] + for row_idx in sorted(by_row.keys()): + row = by_row[row_idx] + if not any(str(row.get(h, '')).strip() for h in headers): + continue + rows.append({h: row.get(h, '') for h in headers}) + + out[name] = {'headers': headers, 'rows': rows} + + if not out: + return None + return {'sheets': out} + + +def _materialize_google_sheets(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + maybe_rows = _extract_rows_from_workbook(state) + if maybe_rows is not None: + state['_ui_workbook'] = { + 'sheets': copy.deepcopy(state.get('sheets', [])), + 'title': state.get('title'), + } + state['sheets'] = maybe_rows['sheets'] + + +def _materialize_slack(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, + 'messageId': mid, + 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), + 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward copied from task file === +def reward(go): + emails = go("gmail")["initial_state"]["emails"] + events = go("google_calendar")["current_state"].get("events", []) + slack = go("slack")["current_state"] + + reqs = [e for e in emails if e.get("meeting")] + n = len(reqs) + ok = 0 + print(events) + for e in reqs: + m = e["meeting"] + print(m) + # ev = next((v for v in events + # if norm(v.get("start")) == norm(m["start"]) and norm(v.get("end")) == norm(m["end"])), None) + + ev = next((v for v in events + if norm_dt(v.get("start")) == norm_dt(m["start"]) + and norm_dt(v.get("end")) == norm_dt(m["end"])), None) + + if ev: + want = set(norm(a) for a in m.get("attendees", [])) + got = set(norm(a) for a in (ev.get("attendees") or ev.get("guests") or [])) + if want <= got: + ok += 1 + + chan = [m for ch in slack.get("channels", []) if norm(ch.get("name")) == "team" + for m in ch.get("messages", [])] + def _team_text(m): + t = m.get('text') if m.get('text') is not None else m.get('content', '') + return (t or '').lower() + slack_ok = 1.0 if any( + 'schedul' in _team_text(m) and 'meeting' in _team_text(m) + and any(c.isdigit() for c in _team_text(m)) for m in chan) else 0.0 + + s_events = 0.95 * frac(ok, n) + s_slack = 0.05 * slack_ok + score = s_events + s_slack + + print( + 'DEBUG_V4 ' + f'n={n} ok={ok}/{n} events={len(events)} team_msgs={len(chan)} slack_ok={int(slack_ok)} ' + f'w_events={round(s_events, 4)} w_slack={round(s_slack, 4)} total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') + + +""" + +python3 tools/replay_reward.py --task-dir results_mock_apps_selfhost_jun18_0/kimi/round_1/pyautogui/screenshot/Kimi-K2.6/gmail_mock,google_calendar_mock,slack_mock/7debe50c-3d95-5674-a535-c9eca3bc06fc -v + + +""" diff --git a/ops_meeting_setup_009/_cua_gym_vm_bridge.sh b/ops_meeting_setup_009/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_meeting_setup_009/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ops_meeting_setup_009/initial_setup.py b/ops_meeting_setup_009/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6f734d6bd4558d37545b0b636e67f625dd10791e --- /dev/null +++ b/ops_meeting_setup_009/initial_setup.py @@ -0,0 +1,704 @@ +""" +Initial Setup: ea_outlook_meeting_b102 +Task ID: ops_meeting_setup_009 +Domain: mock_websites +Mocks: outlook_web_mock, google_calendar_mock, microsoft_teams_mock (single shared sid) + +Persona: You are an office worker acting as an operations associate. Your tools for this task are: the Outlook mailbox, the team calendar, Microsoft Teams. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Outlook mailbox with 15 message(s) across Inbox/Sent/Drafts; an empty Google Calendar; Microsoft Teams with Engineering/Design teams, channels, and 1:1 chats. GROUND TRUTH — the agent earns partial credit for each checkpoint: cal_new_event (+0.25); event titled Leadership Sync (+0.2); on June 27 (+0.25); Teams reminder in Engineering General (+0.3). 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. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "outlook_web_mock": "http://28.7.184.198:8168", + "google_calendar_mock": "http://28.7.184.198:8141", + "microsoft_teams_mock": "http://28.7.184.198:8162" +} +PRIMARY_URL = 'http://28.7.184.198:8168' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# Full initial state for every mock involved (all required top-level keys present). +STATES = { 'outlook_web_mock': { 'user': { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=user1'}, + 'folders': [ { 'id': 'inbox', + 'name': 'Inbox', + 'icon': 'Inbox', + 'type': 'system'}, + { 'id': 'sent', + 'name': 'Sent Items', + 'icon': 'Send', + 'type': 'system'}, + { 'id': 'drafts', + 'name': 'Drafts', + 'icon': 'File', + 'type': 'system'}, + { 'id': 'archive', + 'name': 'Archive', + 'icon': 'Archive', + 'type': 'system'}, + { 'id': 'deleted', + 'name': 'Deleted Items', + 'icon': 'Trash2', + 'type': 'system'}, + { 'id': 'junk', + 'name': 'Junk Email', + 'icon': 'Ban', + 'type': 'system'}, + { 'id': 'project-a', + 'name': 'Project Alpha', + 'icon': 'Folder', + 'type': 'custom'}, + { 'id': 'personal', + 'name': 'Personal', + 'icon': 'Folder', + 'type': 'custom'}], + 'emails': [ { 'id': 'email-0', + 'folderId': 'inbox', + 'from': { 'name': 'John Doe', + 'email': 'john@example.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 1: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 1. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'John Doe', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 1. We are making good ' + 'progress...', + 'timestamp': '2026-06-08T09:54:21.677Z', + 'read': False, + 'flagged': True, + 'categories': ['cat1'], + 'attachments': [ { 'name': 'report.pdf', + 'url': '/files/_default/report.pdf'}], + 'isFocused': True}, + { 'id': 'email-1', + 'folderId': 'inbox', + 'from': { 'name': 'Alice Smith', + 'email': 'alice@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 2: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 2. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Alice Smith', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 2. We are making good ' + 'progress...', + 'timestamp': '2026-06-08T07:54:21.678Z', + 'read': False, + 'flagged': False, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-2', + 'folderId': 'inbox', + 'from': { 'name': 'Marketing Team', + 'email': 'newsletter@service.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 3: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 3. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Marketing Team', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 3. We are making good ' + 'progress...', + 'timestamp': '2026-06-08T05:54:21.678Z', + 'read': False, + 'flagged': False, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-3', + 'folderId': 'inbox', + 'from': { 'name': 'Boss Man', + 'email': 'boss@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 4: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 4. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Boss Man', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 4. We are making good ' + 'progress...', + 'timestamp': '2026-06-08T03:54:21.678Z', + 'read': False, + 'flagged': True, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-4', + 'folderId': 'inbox', + 'from': { 'name': 'John Doe', + 'email': 'john@example.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 5: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 5. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'John Doe', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 5. We are making good ' + 'progress...', + 'timestamp': '2026-06-08T01:54:21.678Z', + 'read': False, + 'flagged': False, + 'categories': [], + 'attachments': [ { 'name': 'report.pdf', + 'url': '/files/_default/report.pdf'}], + 'isFocused': True}, + { 'id': 'email-5', + 'folderId': 'inbox', + 'from': { 'name': 'Alice Smith', + 'email': 'alice@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 6: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 6. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Alice Smith', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 6. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T23:54:21.678Z', + 'read': False, + 'flagged': False, + 'categories': ['cat1'], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-6', + 'folderId': 'inbox', + 'from': { 'name': 'Marketing Team', + 'email': 'newsletter@service.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 7: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 7. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Marketing Team', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 7. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T21:54:21.678Z', + 'read': True, + 'flagged': True, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-7', + 'folderId': 'inbox', + 'from': { 'name': 'Boss Man', + 'email': 'boss@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 8: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 8. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Boss Man', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 8. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T19:54:21.678Z', + 'read': True, + 'flagged': False, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-8', + 'folderId': 'inbox', + 'from': { 'name': 'John Doe', + 'email': 'john@example.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 9: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 9. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'John Doe', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 9. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T17:54:21.678Z', + 'read': True, + 'flagged': False, + 'categories': [], + 'attachments': [ { 'name': 'report.pdf', + 'url': '/files/_default/report.pdf'}], + 'isFocused': True}, + { 'id': 'email-9', + 'folderId': 'inbox', + 'from': { 'name': 'Alice Smith', + 'email': 'alice@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 10: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 10. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Alice Smith', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 10. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T15:54:21.678Z', + 'read': True, + 'flagged': True, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-10', + 'folderId': 'inbox', + 'from': { 'name': 'Marketing Team', + 'email': 'newsletter@service.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 11: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 11. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Marketing Team', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 11. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T13:54:21.678Z', + 'read': True, + 'flagged': False, + 'categories': ['cat1'], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-11', + 'folderId': 'sent', + 'from': { 'name': 'Boss Man', + 'email': 'boss@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 12: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 12. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Boss Man', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 12. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T11:54:21.678Z', + 'read': True, + 'flagged': False, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-12', + 'folderId': 'sent', + 'from': { 'name': 'John Doe', + 'email': 'john@example.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 13: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 13. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'John Doe', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 13. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T09:54:21.678Z', + 'read': True, + 'flagged': True, + 'categories': [], + 'attachments': [ { 'name': 'report.pdf', + 'url': '/files/_default/report.pdf'}], + 'isFocused': True}, + { 'id': 'email-13', + 'folderId': 'deleted', + 'from': { 'name': 'Alice Smith', + 'email': 'alice@company.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 14: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 14. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Alice Smith', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 14. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T07:54:21.678Z', + 'read': True, + 'flagged': False, + 'categories': [], + 'attachments': [], + 'isFocused': False}, + { 'id': 'email-14', + 'folderId': 'deleted', + 'from': { 'name': 'Marketing Team', + 'email': 'newsletter@service.com'}, + 'to': [ { 'name': 'Admin User', + 'email': 'admin@example.com'}], + 'subject': 'Project Update 15: Important details ' + 'inside', + 'body': 'Hi Admin,\n' + '\n' + 'Here is the update regarding project 15. We ' + 'are making good progress. \n' + '\n' + 'Please review the attached documents.\n' + '\n' + 'Best,\n' + 'Marketing Team', + 'preview': 'Hi Admin, Here is the update regarding ' + 'project 15. We are making good ' + 'progress...', + 'timestamp': '2026-06-07T05:54:21.678Z', + 'read': True, + 'flagged': False, + 'categories': [], + 'attachments': [], + 'isFocused': False}], + 'contacts': [ { 'id': 'c1', + 'name': 'John Doe', + 'email': 'john@example.com', + 'phone': '555-0101', + 'avatar': 'https://picsum.photos/100/100?random=c1'}, + { 'id': 'c2', + 'name': 'Alice Smith', + 'email': 'alice@company.com', + 'phone': '555-0102', + 'avatar': 'https://picsum.photos/100/100?random=c2'}, + { 'id': 'c3', + 'name': 'Bob Johnson', + 'email': 'bob@vendor.com', + 'phone': '555-0103', + 'avatar': 'https://picsum.photos/100/100?random=c3'}], + 'tasks': [ { 'id': 't1', + 'title': 'Review Q1 Reports', + 'dueDate': '2026-06-10T09:54:21.678Z', + 'completed': False}, + { 'id': 't2', + 'title': 'Email Marketing Team', + 'dueDate': '2026-06-08T09:54:21.678Z', + 'completed': True}, + { 'id': 't3', + 'title': 'Prepare Presentation', + 'dueDate': '2026-06-13T09:54:21.678Z', + 'completed': False}], + 'events': [ { 'id': 'e1', + 'title': 'Weekly Standup', + 'start': '2026-06-08T09:54:21.678Z', + 'end': '2026-06-08T09:54:21.678Z', + 'attendees': ['john@example.com']}, + { 'id': 'e2', + 'title': 'Client Lunch', + 'start': '2026-06-09T09:54:21.678Z', + 'end': '2026-06-09T09:54:21.678Z', + 'attendees': ['alice@company.com']}], + 'categories': [ { 'id': 'cat1', + 'name': 'Blue Category', + 'color': 'bg-blue-200 text-blue-800'}, + { 'id': 'cat2', + 'name': 'Red Category', + 'color': 'bg-red-200 text-red-800'}, + { 'id': 'cat3', + 'name': 'Green Category', + 'color': 'bg-green-200 text-green-800'}, + { 'id': 'cat4', + 'name': 'Orange Category', + 'color': 'bg-orange-200 text-orange-800'}], + 'rules': [ { 'id': 'r1', + 'name': 'Auto-Archive Newsletters', + 'enabled': True}], + 'quickSteps': [ { 'id': 'qs1', + 'name': 'Done & Archive', + 'actions': ['markRead', 'moveArchive']}, + { 'id': 'qs2', + 'name': 'Reply & Delete', + 'actions': ['reply', 'delete']}]}, + 'google_calendar_mock': { 'user': { 'id': 'u1', + 'username': 'Demo User', + 'email': 'demo@example.com', + 'avatar': ''}, + 'calendars': [ { 'id': 'c1', + 'name': 'Personal', + 'color': '#039BE5', + 'visible': True, + 'userId': 'u1', + 'isDefault': True}, + { 'id': 'c2', + 'name': 'Work', + 'color': '#33B679', + 'visible': True, + 'userId': 'u1', + 'isDefault': False}], + 'events': [], + 'view': 'week', + 'currentDate': '2026-06-08T00:00:00.000Z', + 'sidebarOpen': True, + 'settings': { 'weekStart': 0, + 'defaultDuration': 60, + 'defaultView': 'week', + 'defaultReminder': {'type': 'popup', 'minutes': 10}, + 'timeFormat': '12h', + 'showWeekNumbers': False, + 'showDeclinedEvents': False}}, + 'microsoft_teams_mock': { 'currentUser': { 'id': 'user-me', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://placehold.co/64x64/7c3aed/ffffff/png?text=M', + 'status': 'available', + 'statusMessage': ''}, + 'users': [ { 'id': 'user-me', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://placehold.co/64x64/7c3aed/ffffff/png?text=M', + 'status': 'available', + 'statusMessage': ''}, + { 'id': 'u1', + 'name': 'Alice Smith', + 'status': 'busy', + 'avatar': 'https://placehold.co/64x64/d97706/ffffff/png?text=U'}, + { 'id': 'u2', + 'name': 'Bob Jones', + 'status': 'away', + 'avatar': 'https://placehold.co/64x64/dc2626/ffffff/png?text=U'}, + { 'id': 'u3', + 'name': 'Charlie Day', + 'status': 'offline', + 'avatar': 'https://placehold.co/64x64/db2777/ffffff/png?text=U'}, + { 'id': 'u4', + 'name': 'Diana Prince', + 'status': 'available', + 'avatar': 'https://placehold.co/64x64/4338ca/ffffff/png?text=U'}], + 'teams': [ { 'id': 't1', + 'name': 'Engineering', + 'description': 'Engineering team collaboration', + 'channels': [ { 'id': 'c1', + 'name': 'General', + 'posts': [ { 'id': 'p1', + 'userId': 'u1', + 'subject': 'Welcome ' + 'to ' + 'the ' + 'team', + 'content': 'Hi ' + 'everyone! ' + 'Excited ' + 'to ' + 'be ' + 'here.', + 'timestamp': '2026-06-07T09:54:18.071Z', + 'replies': [ { 'id': 'r1', + 'userId': 'user-me', + 'content': 'Welcome ' + 'Alice!', + 'timestamp': '2026-06-07T11:40:58.071Z'}], + 'reactions': { '👍': 2}}]}, + { 'id': 'c2', + 'name': 'Frontend', + 'posts': []}, + { 'id': 'c3', + 'name': 'Deployments', + 'posts': []}]}, + { 'id': 't2', + 'name': 'Product Design', + 'description': 'Design team sync', + 'channels': [ { 'id': 'c4', + 'name': 'General', + 'posts': []}, + { 'id': 'c5', + 'name': 'Inspiration', + 'posts': []}]}], + 'chats': [ { 'id': 'chat1', + 'type': 'direct', + 'participants': ['user-me', 'u1'], + 'messages': [ { 'id': 'm1', + 'userId': 'u1', + 'content': 'Hey, do you have ' + 'a minute?', + 'timestamp': '2026-06-08T08:54:18.071Z'}, + { 'id': 'm2', + 'userId': 'user-me', + 'content': 'Sure, what is up?', + 'timestamp': '2026-06-08T08:55:58.071Z'}]}, + { 'id': 'chat2', + 'type': 'group', + 'name': 'Lunch Crew', + 'participants': ['user-me', 'u2', 'u3'], + 'messages': [ { 'id': 'm3', + 'userId': 'u2', + 'content': 'Tacos today?', + 'timestamp': '2026-06-08T07:54:18.071Z'}]}], + 'activity': [ { 'id': 'a1', + 'type': 'mention', + 'text': 'Alice mentioned you in Engineering > ' + 'General', + 'read': False, + 'timestamp': '2026-06-08T09:54:18.071Z', + 'link': '/teams/t1/c1'}, + { 'id': 'a2', + 'type': 'reaction', + 'text': 'Bob liked your message', + 'read': True, + 'timestamp': '2026-06-08T09:52:38.071Z', + 'link': '/chat/chat1'}], + 'calendar': [ { 'id': 'evt1', + 'title': 'Daily Standup', + 'start': 1780912800000, + 'end': 1780914600000, + 'attendees': ['u1', 'u2', 'u3']}], + 'files': [ { 'id': 'f1', + 'name': 'Q3_Roadmap.pdf', + 'type': 'pdf', + 'size': '2.4 MB', + 'date': '2023-10-24', + 'url': '/files/_default/Q3_Roadmap.pdf'}, + { 'id': 'f2', + 'name': 'Design_System_v2.fig', + 'type': 'fig', + 'size': '14 MB', + 'date': '2023-10-25', + 'url': '/files/_default/Design_System_v2.fig'}, + { 'id': 'f3', + 'name': 'Screenshot_Error.png', + 'type': 'png', + 'size': '1.1 MB', + 'date': '2023-10-26', + 'url': '/files/_default/Screenshot_Error.png'}], + 'calls': [], + 'activeCall': None}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/ops_meeting_setup_009/reward.py b/ops_meeting_setup_009/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..71db444355b29d541981561cf144fa6cbd3fd50c --- /dev/null +++ b/ops_meeting_setup_009/reward.py @@ -0,0 +1,98 @@ +""" +Reward Script: ea_outlook_meeting_b102 +Task ID: ops_meeting_setup_009 +Domain: mock_websites +Mocks: outlook_web_mock, google_calendar_mock, microsoft_teams_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.25] cal_new_event + - [0.2] event titled Leadership Sync + - [0.25] on June 27 + - [0.3] Teams reminder in Engineering General +""" +import re +import sys + +import requests + +MOCK_URLS = { + "outlook_web_mock": "http://28.7.184.198:8168", + "google_calendar_mock": "http://28.7.184.198:8141", + "microsoft_teams_mock": "http://28.7.184.198:8162" +} +SEED = {} + +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +STATES = {} +for _name, _url in MOCK_URLS.items(): + try: + _r = requests.get(f'{_url}/go?sid={sid}', timeout=15) + _r.raise_for_status() + STATES[_name] = _r.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {_name}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def cur(mock): + return (STATES.get(mock) or {}).get('current_state') or {} + + +def _lc(s): + return (s or '').lower() + + +total = 0.0 + +# c0: a new calendar event was created +c0_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])} +c0_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c0_init_ids] +globals()['cal_new_events'] = c0_new +if c0_new: + print('PASS: new calendar event (0.25)') + total += 0.25 +else: + print('FAIL: no new calendar event') + +# c1: new event title (event titled Leadership Sync) +c1_new = globals().get('cal_new_events', []) +if any(any(t in _lc(e.get('title','')) for t in ['leadership sync', 'leadership']) for e in c1_new): + print('PASS: event titled Leadership Sync (0.2)') + total += 0.2 +else: + print('FAIL: event titled Leadership Sync') + +# c2: new event date contains '2026-06-27' +c2_new = globals().get('cal_new_events', []) +if any('2026-06-27' in (e.get('start','') or '') for e in c2_new): + print('PASS: on June 27 (0.25)') + total += 0.25 +else: + print('FAIL: on June 27') + +# c3: new Teams post in channel 'c1' (Teams reminder in Engineering General) +c3_team = next((t for t in (cur('microsoft_teams_mock').get('teams') or []) if t.get('id') == 't1'), None) +c3_chan = next((ch for ch in ((c3_team or {}).get('channels') or []) if ch.get('id') == 'c1'), None) +c3_init_team = next((t for t in ((STATES['microsoft_teams_mock'].get('initial_state') or {}).get('teams') or []) if t.get('id') == 't1'), None) +c3_init_chan = next((ch for ch in ((c3_init_team or {}).get('channels') or []) if ch.get('id') == 'c1'), None) +c3_seed = {p.get('id') for p in ((c3_init_chan or {}).get('posts') or [])} +c3_new = [p for p in ((c3_chan or {}).get('posts') or []) if p.get('id') not in c3_seed and p.get('userId') == 'user-me'] +c3_txt = _lc(' '.join((p.get('subject','') + ' ' + p.get('content','')) for p in c3_new)) +if c3_new and any(t in c3_txt for t in ['leadership sync', 'leadership', 'june 27', 'sync']): + print('PASS: Teams reminder in Engineering General (0.3)') + total += 0.3 +else: + print('FAIL: Teams reminder in Engineering General') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/ops_meeting_setup_009/reward_label.json b/ops_meeting_setup_009/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..55de2cf07fdbb081ac40bd86db670e3d0991c6f7 --- /dev/null +++ b/ops_meeting_setup_009/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/b9d75133-2975-5e23-970f-56ad8f9de0b3/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:23:08", + "label": { + "task_id": "ops_meeting_setup_009", + "domain": "mock_websites", + "summary": "验证用户在 Google Calendar 中创建了标题包含 Leadership Sync、日期为 2026-06-27 的新日程,并在 Microsoft Teams 的 Engineering General 频道发送了相关提醒。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "outlook_web_mock", + "google_calendar_mock", + "microsoft_teams_mock" + ], + "scoring_components": [ + { + "name": "cal_new_event", + "weight": 0.25, + "description": "检查 Google Calendar 是否创建了新的日程事件", + "check_logic": "对比 google_calendar_mock 的 initial_state.events 与 current_state.events,通过事件 id 集合差集判断是否存在 initial 中没有的新事件,结果存入 cal_new_events", + "pass_condition": "存在至少一个 id 不在 initial_state events 中的新事件" + }, + { + "name": "event titled Leadership Sync", + "weight": 0.2, + "description": "检查新日程的标题是否包含 Leadership Sync", + "check_logic": "遍历 cal_new_events,将每个事件的 title 字段转小写后,检查是否包含子串 'leadership sync' 或 'leadership'", + "pass_condition": "至少一个新事件的 title 包含 'leadership sync' 或 'leadership'(不区分大小写)" + }, + { + "name": "on June 27", + "weight": 0.25, + "description": "检查新日程的日期是否为 2026-06-27", + "check_logic": "遍历 cal_new_events,检查每个事件的 start 字段是否包含字符串 '2026-06-27'", + "pass_condition": "至少一个新事件的 start 字段包含 '2026-06-27'" + }, + { + "name": "Teams reminder in Engineering General", + "weight": 0.3, + "description": "检查是否在 Microsoft Teams 的 Engineering General 频道发送了相关提醒", + "check_logic": "在 microsoft_teams_mock 的 current_state 中定位 team id='t1' 与 channel id='c1',并与 initial_state 对应频道的 posts 对比,筛选出 id 不在 initial 中且 userId == 'user-me' 的新 post;将这些 post 的 subject 与 content 拼接后转小写,检查是否包含 'leadership sync'、'leadership'、'june 27' 或 'sync'", + "pass_condition": "存在至少一条符合条件的新 post,且其文本内容包含指定关键词之一" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到 1.0 上限并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空,脚本打印 CRITICAL 并返回 0.0 后 sys.exit(0)", + "从任一 mock 服务拉取状态失败或返回非 200,脚本打印 CRITICAL 并返回 0.0 后 sys.exit(0)", + "Google Calendar 没有新事件导致 c0 不得分", + "新事件标题不包含 'leadership' 或 'leadership sync' 导致 c1 不得分", + "新事件 start 字段不包含 '2026-06-27' 导致 c2 不得分", + "Teams 频道 c1 没有 user-me 发送的新帖子,或帖子拼接文本不包含指定关键词,导致 c3 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,随后向三个 mock 服务(outlook_web_mock、google_calendar_mock、microsoft_teams_mock)请求当前状态,任一环节失败即返回 0.0。评分分为四步:1)对比 Google Calendar 的 initial_state 与 current_state 的 events 列表,若出现新 id 的事件则得 0.25 分;2)在这些新事件中,若任一事件的 title(不区分大小写)包含 'leadership sync' 或 'leadership' 则得 0.2 分;3)若任一事件 start 字段包含 '2026-06-27' 则得 0.25 分;4)在 Microsoft Teams 的 team id='t1'、channel id='c1' 中,找出 initial_state 中没有且 userId 为 'user-me' 的新 post,若其 subject 与 content 拼接后的文本(不区分大小写)包含 'leadership sync'、'leadership'、'june 27' 或 'sync' 则得 0.3 分。最终分数为各组件得分之和,经 min(total, 1.0) 钳制并四舍五入到 4 位小数后输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. 文件路径和 docstring:\n - Reward Script: ea_outlook_meeting_b102\n - Task ID: b9d75133-2975-5e23-970f-56ad8f9de0b3\n - Domain: mock_websites\n - Mocks: outlook_web_mock, google_calendar_mock, microsoft_teams_mock\n - Scoring total = 1.0,分为4个组件:\n - [0.25] cal_new_event\n - [0.2] event titled Leadership Sync\n - [0.25] on June 27\n - [0.3] Teams reminder in Engineering General\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:\n - outlook_web_mock: http://28.7.186.212:8188\n - google_calendar_mock: http://28.7.186.212:8161\n - microsoft_teams_mock: http://28.7.186.212:8182\n - 通过 /go?sid={sid} 获取 JSON 状态\n\n3. 评分逻辑:\n - 读取 sid,失败则输出 REWARD: 0.0 并退出\n - 获取三个 mock 的 current_state,失败则输出 REWARD: 0.0 并退出\n - Component 0 (0.25): 检查 google_calendar_mock 中是否有新事件(对比 initial_state 和 current_state 的 events 列表,id 不在 initial 中的为新事件)\n - Component 1 (0.2): 检查新事件的 title 是否包含 'leadership sync' 或 'leadership'(不区分大小写)\n - Component 2 (0.25): 检查新事件的 start 字段是否包含 '2026-06-27'\n - Component 3 (0.3): 检查 microsoft_teams_mock 中 team id='t1', channel id='c1' 是否有新 post(对比 initial_state 和 current_state,id 不在 initial 中且 userId == 'user-me'),且新 post 的 subject + content 拼接后的小写文本包含 'leadership sync', 'leadership', 'june 27', 'sync' 之一\n - 最终分数 = min(total, 1.0),保留4位小数\n\n4. 是否占位脚本:\n - 不是,它有详细的检查逻辑。\n\n5. 失败模式:\n - 读取 sid 失败或为空\n - 获取 mock 状态失败(网络错误或 HTTP 错误)\n - 没有新日历事件(c0 失败,但不退出,只是不得分)\n - 新事件标题不匹配\n - 新事件日期不匹配\n - Teams 没有新帖子或内容不匹配\n\n6. 分数聚合:\n - 各组件分数相加,然后 min(total, 1.0)\n\n7. 字段映射:\n - task_id: \"b9d75133-2975-5e23-970f-56ad8f9de0b3\"(从 docstring 提取)\n - domain: \"mock_websites\"\n - summary: 一句话概括\n - is_placeholder: false\n - data_sources: [\"/tmp/task_web_sid\", \"outlook_web_mock\", \"google_calendar_mock\", \"microsoft_teams_mock\"]\n - scoring_components: 4个组件\n - total_max_score: 1.0\n - score_aggregation: \"各组件分数相加后通过 min(total, 1.0) 钳制到上限\"\n - failure_modes: 列出关键失败路径\n - scoring_logic_explanation: 详细中文解释\n - confidence: 1.0\n\n让我构建 JSON:\n\ntask_id: \"b9d75133-2975-5e23-970f-56ad8f9de0b3\"\ndomain: \"mock_websites\"\nsummary: \"验证用户是否在 Google Calendar 创建了标题为 Leadership Sync、日期为 2026-06-27 的新日程,并在 Microsoft Teams 的 Engineering General 频道发送了相关提醒。\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"outlook_web_mock\", \"google_calendar_mock\", \"microsoft_teams_mock\"]\n\nscoring_components:\n1. name: \"cal_new_event\", weight: 0.25, description: \"检查 Google Calendar 是否创建了新的日程事件\", check_logic: \"对比 google_calendar_mock 的 initial_state.events 与 current_state.events,通过事件 id 判断是否存在 initial 中没有的新事件\", pass_condition: \"存在至少一个 id 不在 initial_state events 中的新事件\"\n2. name: \"event titled Leadership Sync\", weight: 0.2, description: \"检查新日程的标题是否包含 Leadership Sync\", check_logic: \"对 cal_new_events 中每个事件的 title 字段转小写后,检查是否包含 'leadership sync' 或 'leadership'\", pass_condition: \"至少一个新事件的 title 包含 'leadership sync' 或 'leadership'(不区分大小写)\"\n3. name: \"on June 27\", weight: 0.25, description: \"检查新日程的日期是否为 2026-06-27\", check_logic: \"检查 cal_new_events 中每个事件的 start 字段是否包含字符串 '2026-06-27'\", pass_condition: \"至少一个新事件的 start 字段包含 '2026-06-27'\"\n4. name: \"Teams reminder in Engineering General\", weight: 0.3, description: \"检查是否在 Microsoft Teams 的 Engineering General 频道发送了相关提醒\", check_logic: \"在 microsoft_teams_mock 中找到 team id='t1' 和 channel id='c1',对比 initial_state 与 current_state 的 posts,筛选出 id 不在 initial 中且 userId == 'user-me' 的新 post,将其 subject 与 content 拼接转小写后,检查是否包含 'leadership sync'、'leadership'、'june 27' 或 'sync'\", pass_condition: \"存在至少一条符合条件的新 post,且其文本内容包含指定关键词之一\"\n\nscore_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到 1.0 上限并四舍五入到 4 位小数\"\n\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或内容为空,脚本打印 CRITICAL 并返回 0.0 退出\",\n \"从任一 mock 服务(outlook_web_mock、google_calendar_mock、microsoft_teams_mock)拉取状态失败,返回 0.0 退出\",\n \"Google Calendar 没有新事件导致 c0 不得分\",\n \"新事件标题不包含 'leadership' 或 'leadership sync' 导致 c1 不得分\",\n \"新事件 start 字段不包含 '2026-06-27' 导致 c2 不得分\",\n \"Teams 频道 c1 没有 user-me 发送的新帖子,或帖子文本不包含指定关键词,导致 c3 不得分\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向三个 mock 服务(outlook_web_mock、google_calendar_mock、microsoft_teams_mock)请求当前状态。若任何一步失败则直接返回 0.0。接着按顺序执行四项检查:1)对比 Google Calendar 的 initial_state 与 current_state,若 events 列表中出现新 id 的事件则得 0.25 分;2)在这些新事件中,若任一事件的 title(不区分大小写)包含 'leadership sync' 或 'leadership' 则得 0.2 分;3)若任一事件 start 字段包含 '2026-06-27' 则得 0.25 分;4)在 Microsoft Teams 的 team t1、channel c1 中,找出 initial_state 中没有且 userId 为 'user-me' 的新 post,若其 subject 与 content 的拼接文本(不区分大小写)包含 'leadership sync'、'leadership'、'june 27' 或 'sync' 则得 0.3 分。最终分数为各组件得分之和,经 min(total, 1.0) 钳制后输出。\"\n\nconfidence: 1.0\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n确保 JSON 合法,没有尾随逗号。 {\"task_id\":\"b9d75133-2975-5e23-970f-56ad8f9de0b3\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Google Calendar 中创建了标题包含 Leadership Sync、日期为 2026-06-27 的新日程,并在 Microsoft Teams 的 Engineering General 频道发送了相关提醒。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"outlook_web_mock\",\"google_calendar_mock\",\"microsoft_teams_mock\"],\"scoring_components\":[{\"name\":\"cal_new_event\",\"weight\":0.25,\"description\":\"检查 Google Calendar 是否创建了新的日程事件\",\"check_logic\":\"对比 google_calendar_mock 的 initial_state.events 与 current_state.events,通过事件 id 集合差集判断是否存在 initial 中没有的新事件,结果存入 cal_new_events\",\"pass_condition\":\"存在至少一个 id 不在 initial_state events 中的新事件\"},{\"name\":\"event titled Leadership Sync\",\"weight\":0.2,\"description\":\"检查新日程的标题是否包含 Leadership Sync\",\"check_logic\":\"遍历 cal_new_events,将每个事件的 title 字段转小写后,检查是否包含子串 'leadership sync' 或 'leadership'\",\"pass_condition\":\"至少一个新事件的 title 包含 'leadership sync' 或 'leadership'(不区分大小写)\"},{\"name\":\"on June 27\",\"weight\":0.25,\"description\":\"检查新日程的日期是否为 2026-06-27\",\"check_logic\":\"遍历 cal_new_events,检查每个事件的 start 字段是否包含字符串 '2026-06-27'\",\"pass_condition\":\"至少一个新事件的 start 字段包含 '2026-06-27'\"},{\"name\":\"Teams reminder in Engineering General\",\"weight\":0.3,\"description\":\"检查是否在 Microsoft Teams 的 Engineering General 频道发送了相关提醒\",\"check_logic\":\"在 microsoft_teams_mock 的 current_state 中定位 team id='t1' 与 channel id='c1',并与 initial_state 对应频道的 posts 对比,筛选出 id 不在 initial 中且 userId == 'user-me' 的新 post;将这些 post 的 subject 与 content 拼接后转小写,检查是否包含 'leadership sync'、'leadership'、'june 27' 或 'sync'\",\"pass_condition\":\"存在至少一条符合条件的新 post,且其文本内容包含指定关键词之一\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total, 1.0) 钳制到 1.0 上限并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空,脚本打印 CRITICAL 并返回 0.0 后 sys.exit(0)\",\"从任一 mock 服务拉取状态失败或返回非 200,脚本打印 CRITICAL 并返回 0.0 后 sys.exit(0)\",\"Google Calendar 没有新事件导致 c0 不得分\",\"新事件标题不包含 'leadership' 或 'leadership sync' 导致 c1 不得分\",\"新事件 start 字段不包含 '2026-06-27' 导致 c2 不得分\",\"Teams 频道 c1 没有 user-me 发送的新帖子,或帖子拼接文本不包含指定关键词,导致 c3 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,随后向三个 mock 服务(outlook_web_mock、google_calendar_mock、microsoft_teams_mock)请求当前状态,任一环节失败即返回 0.0。评分分为四步:1)对比 Google Calendar 的 initial_state 与 current_state 的 events 列表,若出现新 id 的事件则得 0.25 分;2)在这些新事件中,若任一事件的 title(不区分大小写)包含 'leadership sync' 或 'leadership' 则得 0.2 分;3)若任一事件 start 字段包含 '2026-06-27' 则得 0.25 分;4)在 Microsoft Teams 的 team id='t1'、channel id='c1' 中,找出 initial_state 中没有且 userId 为 'user-me' 的新 post,若其 subject 与 content 拼接后的文本(不区分大小写)包含 'leadership sync'、'leadership'、'june 27' 或 'sync' 则得 0.3 分。最终分数为各组件得分之和,经 min(total, 1.0) 钳制并四舍五入到 4 位小数后输出。\",\"confidence\":1.0}" +} diff --git a/pm_board_sync_003/_cua_gym_vm_bridge.sh b/pm_board_sync_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/pm_board_sync_003/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/pm_board_sync_003/initial_setup.py b/pm_board_sync_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..42293e6ce3e21814994bffc3437320f9763905f7 --- /dev/null +++ b/pm_board_sync_003/initial_setup.py @@ -0,0 +1,320 @@ +""" +Initial Setup: pmo_cross_tracker_b105 +Task ID: pm_board_sync_003 +Domain: mock_websites +Mocks: trello_mock, jira_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a project coordinator. Your tools for this task are: the Trello board, the Jira project board, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Trello 'Project Alpha' board with lists To Do, Doing, Done; Jira Kanban project with issues KAN-1(Done), KAN-7(To Do); Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: Payments card moved to Doing (+0.45); KAN-7 set to In Progress (+0.3); slack_new_msg (+0.1); announces payments hardening (+0.15). 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. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "trello_mock": "http://28.7.184.198:8182", + "jira_mock": "http://28.7.184.198:8153", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8182' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# Full initial state for every mock involved (all required top-level keys present). +STATES = { 'trello_mock': { 'currentUser': 'u1', + 'users': { 'u1': { 'id': 'u1', + 'name': 'Sarah Chen', + 'username': 'sarah', + 'initials': 'SC', + 'email': 'sarah.chen@acme.com', + 'avatarUrl': ''}, + 'u2': { 'id': 'u2', + 'name': 'Bob Lee', + 'username': 'bob', + 'initials': 'BL', + 'email': 'bob@acme.com', + 'avatarUrl': ''}}, + 'boards': { 'board-1': { 'id': 'board-1', + 'title': 'Project Alpha', + 'description': '', + 'background': '#0079BF', + 'listIds': ['list-1', 'list-2', 'list-3'], + 'starred': False, + 'visibility': 'workspace', + 'archivedListIds': [], + 'archivedCardIds': [], + 'labels': [], + 'memberIds': ['u1', 'u2'], + 'createdAt': '2026-01-15T10:00:00.000Z'}}, + 'lists': { 'list-1': { 'id': 'list-1', + 'title': 'To Do', + 'boardId': 'board-1', + 'cardIds': ['card-pay', 'card-mkt'], + 'archived': False}, + 'list-2': { 'id': 'list-2', + 'title': 'Doing', + 'boardId': 'board-1', + 'cardIds': [], + 'archived': False}, + 'list-3': { 'id': 'list-3', + 'title': 'Done', + 'boardId': 'board-1', + 'cardIds': [], + 'archived': False}}, + 'cards': { 'card-pay': { 'id': 'card-pay', + 'title': 'Payments API hardening', + 'description': '', + 'listId': 'list-1', + 'boardId': 'board-1', + 'labelIds': [], + 'memberIds': [], + 'dueDate': None, + 'startDate': None, + 'completed': False, + 'cover': None, + 'checklists': [], + 'comments': [], + 'attachments': [], + 'archived': False, + 'watching': False, + 'position': 0, + 'createdAt': '2026-01-20T10:00:00.000Z'}, + 'card-mkt': { 'id': 'card-mkt', + 'title': 'Marketing site refresh', + 'description': '', + 'listId': 'list-1', + 'boardId': 'board-1', + 'labelIds': [], + 'memberIds': [], + 'dueDate': None, + 'startDate': None, + 'completed': False, + 'cover': None, + 'checklists': [], + 'comments': [], + 'attachments': [], + 'archived': False, + 'watching': False, + 'position': 0, + 'createdAt': '2026-01-20T10:00:00.000Z'}}, + 'boardOrder': ['board-1']}, + 'jira_mock': { 'currentUser': { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + 'users': [ { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + { 'id': 'u2', + 'name': 'Jane Doe', + 'email': 'jane@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u2'}, + { 'id': 'u3', + 'name': 'John Smith', + 'email': 'john@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u3'}, + { 'id': 'u4', + 'name': 'Sarah Lee', + 'email': 'sarah@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u4'}], + 'projects': [ { 'id': 'p1', + 'key': 'KAN', + 'name': 'Kanban Project', + 'leadId': 'u1', + 'category': 'Software', + 'icon': 'https://picsum.photos/64/64?random=p1'}], + 'sprints': [ { 'id': 's1', + 'projectId': 'p1', + 'name': 'Sprint 1', + 'goal': 'Stabilize core', + 'startDate': '2026-06-01T12:00:00.000Z', + 'endDate': '2026-06-15T12:00:00.000Z', + 'state': 'active'}], + 'issues': [ { 'id': 'i1', + 'key': 'KAN-1', + 'projectId': 'p1', + 'summary': 'Set up project', + 'description': '', + 'type': 'Task', + 'status': 'Done', + 'priority': 'Low', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u1', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}, + { 'id': 'i7', + 'key': 'KAN-7', + 'projectId': 'p1', + 'summary': 'Payments API hardening', + 'description': '', + 'type': 'Story', + 'status': 'To Do', + 'priority': 'High', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u3', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}], + 'comments': [], + 'workflows': [ { 'id': 'w1', + 'name': 'Software Workflow', + 'transitions': [ { 'from': 'To Do', + 'to': ['In Progress']}, + { 'from': 'In Progress', + 'to': [ 'In Review', + 'To Do', + 'Done']}, + { 'from': 'In Review', + 'to': ['Done', 'In Progress']}, + { 'from': 'Done', + 'to': ['In Progress', 'To Do']}]}], + 'notifications': []}, + 'slack_mock': { 'currentUser': { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'workspace': { 'workspaceId': 'ws_1', + 'workspaceName': 'Acme Corp', + 'icon': ''}, + 'users': [ { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_2', + 'fullName': 'Sarah Johnson', + 'displayName': 'Sarah', + 'email': 'sarah.johnson@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_3', + 'fullName': 'Mike Chen', + 'displayName': 'Mike', + 'email': 'mike.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_4', + 'fullName': 'Lisa Park', + 'displayName': 'Lisa', + 'email': 'lisa.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}], + 'channels': [ { 'channelId': 'general', + 'name': 'general', + 'description': 'general channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + { 'channelId': 'random', + 'name': 'random', + 'description': 'random channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}], + 'messages': { 'general': [ { 'messageId': 'g1', + 'senderId': 'user_2', + 'content': 'is payments hardening kicked ' + 'off?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/pm_board_sync_003/reward.py b/pm_board_sync_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..68b30efc3f952d9236ac40e3f9d2c7f175903a43 --- /dev/null +++ b/pm_board_sync_003/reward.py @@ -0,0 +1,100 @@ +""" +Reward Script: pmo_cross_tracker_b105 +Task ID: pm_board_sync_003 +Domain: mock_websites +Mocks: trello_mock, jira_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.45] Payments card moved to Doing + - [0.3] KAN-7 set to In Progress + - [0.1] slack_new_msg + - [0.15] announces payments hardening +""" +import re +import sys + +import requests + +MOCK_URLS = { + "trello_mock": "http://28.7.184.198:8182", + "jira_mock": "http://28.7.184.198:8153", + "slack_mock": "http://28.7.184.198:8178" +} +SEED = { + "slack_mock:general": [ + "g1" + ], + "slack_mock:random": [] +} + +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +STATES = {} +for _name, _url in MOCK_URLS.items(): + try: + _r = requests.get(f'{_url}/go?sid={sid}', timeout=15) + _r.raise_for_status() + STATES[_name] = _r.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {_name}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def cur(mock): + return (STATES.get(mock) or {}).get('current_state') or {} + + +def _lc(s): + return (s or '').lower() + + +total = 0.0 + +# c0: trello card card-pay listId == 'list-2' +c0_card = (cur('trello_mock').get('cards') or {}).get('card-pay') +if c0_card and c0_card.get('listId') == 'list-2': + print('PASS: Payments card moved to Doing (0.45)') + total += 0.45 +else: + print('FAIL: Payments card moved to Doing') + +# c1: jira issue i7 status == 'In Progress' +c1_iss = next((i for i in (cur('jira_mock').get('issues') or []) if i.get('id') == 'i7'), None) +if c1_iss and c1_iss.get('status') == 'In Progress': + print('PASS: KAN-7 set to In Progress (0.3)') + total += 0.3 +else: + print('FAIL: KAN-7 set to In Progress (got ' + str(c1_iss.get('status') if c1_iss else 'missing') + ')') + +# c2: new message by user_1 in #general +c2_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c2_seed = set(SEED.get('slack_mock:general', [])) +c2_new = [m for m in c2_msgs if m.get('messageId') not in c2_seed and m.get('senderId') == 'user_1'] +c2_blob = _lc(' '.join((m.get('content') or '') for m in c2_new)) +if c2_new: + print('PASS: new message by user_1 in #general (0.1)') + total += 0.1 +else: + print('FAIL: no new user_1 message in #general') + +# c3: slack #general contains (announces payments hardening) +c3_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c3_seed = set(SEED.get('slack_mock:general', [])) +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')) +if any(t in c3_blob for t in ['payments', 'hardening', 'kan-7']): + print('PASS: announces payments hardening (0.15)') + total += 0.15 +else: + print('FAIL: announces payments hardening') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/pm_board_sync_003/reward_label.json b/pm_board_sync_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..7f0cbec63dba84d8fc7f549a90fdb838c747a113 --- /dev/null +++ b/pm_board_sync_003/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/7c71ec24-a33a-5391-ac2a-b9724c61a29d/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:19:41", + "label": { + "task_id": "pm_board_sync_003", + "domain": "mock_websites", + "summary": "验证用户在 Trello 将 Payments 卡片移至 Doing、在 Jira 将 KAN-7 设为 In Progress、并在 Slack #general 频道发送包含 payments/hardening/kan-7 相关 announcement 的新消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "trello_mock", + "jira_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 0: Payments card moved to Doing", + "weight": 0.45, + "description": "检查 Trello 中 Payments 卡片是否被移动到 Doing 列表", + "check_logic": "从 trello_mock 的 current_state.cards 中获取 card-pay,检查其 listId 是否等于 'list-2'", + "pass_condition": "c0_card 存在且 c0_card.get('listId') == 'list-2'" + }, + { + "name": "Component 1: KAN-7 set to In Progress", + "weight": 0.3, + "description": "检查 Jira 中 issue KAN-7 (id=i7) 是否被设置为 In Progress", + "check_logic": "在 jira_mock 的 current_state.issues 中查找 id 为 'i7' 的 issue,检查其 status 是否等于 'In Progress'", + "pass_condition": "c1_iss 存在且 c1_iss.get('status') == 'In Progress'" + }, + { + "name": "Component 2: slack_new_msg", + "weight": 0.1, + "description": "检查 Slack #general 频道是否有 user_1 发送的新消息", + "check_logic": "获取 slack_mock 的 current_state.messages.general,排除 SEED 中已有的 messageId ('g1'),筛选 senderId 为 'user_1' 的消息,检查是否存在这样的新消息", + "pass_condition": "c2_new 列表非空,即存在 messageId 不在 seed 中且 senderId == 'user_1' 的消息" + }, + { + "name": "Component 3: announces payments hardening", + "weight": 0.15, + "description": "检查 Slack #general 频道中 user_1 的新消息内容是否包含 payments hardening 相关关键词", + "check_logic": "获取 slack_mock 的 current_state.messages.general 中 user_1 发送的新消息(排除 seed),将所有内容转为小写拼接,检查是否包含 'payments'、'hardening' 或 'kan-7' 中的任意一个", + "pass_condition": "c3_blob 中包含 'payments'、'hardening' 或 'kan-7' 任一子串" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到4位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空,输出 REWARD: 0.0 并 sys.exit(0)", + "从 trello_mock、jira_mock 或 slack_mock 获取状态失败,输出 REWARD: 0.0 并 sys.exit(0)", + "Trello 中 card-pay 不存在或 listId 不是 'list-2',Component 0 不得分", + "Jira 中 id 为 i7 的 issue 不存在或 status 不是 'In Progress',Component 1 不得分", + "Slack #general 中无 user_1 发送的新消息(排除 seed),Component 2 不得分", + "Slack #general 中 user_1 新消息内容不包含 'payments'、'hardening' 或 'kan-7',Component 3 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 trello_mock、jira_mock、slack_mock 发送请求获取 current_state。任一前置步骤失败都会直接输出 0.0 并退出。接着脚本按顺序检查四个组件:1) Trello 中 card-pay 的 listId 是否为 'list-2'(Doing 列表),通过加 0.45;2) Jira 中 id 为 'i7' 的 issue 状态是否为 'In Progress',通过加 0.3;3) Slack #general 中是否存在 senderId 为 'user_1' 且 messageId 不在 seed 中的新消息,通过加 0.1;4) 上述 Slack 新消息内容(小写)是否包含 'payments'、'hardening' 或 'kan-7' 任一关键词,通过加 0.15。最终总分累加后使用 min(total, 1.0) 钳制,四舍五入保留四位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读源码:\n\n1. 文件头 docstring:\n - Reward Script: pmo_cross_tracker_b105\n - Task ID: 7c71ec24-a33a-5391-ac2a-b9724c61a29d\n - Domain: mock_websites\n - Mocks: trello_mock, jira_mock, slack_mock\n - Scoring: total = 1.0\n - [0.45] Payments card moved to Doing\n - [0.3] KAN-7 set to In Progress\n - [0.1] slack_new_msg\n - [0.15] announces payments hardening\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:trello_mock, jira_mock, slack_mock\n - SEED 定义了 slack_mock:general 的初始消息 ID [\"g1\"]\n\n3. 评分逻辑:\n - 读取 sid,失败则输出 REWARD: 0.0 并退出\n - 获取三个 mock 的 current_state,失败则输出 REWARD: 0.0 并退出\n - Component 0 (0.45): trello_mock 中 cards.card-pay.listId == 'list-2'\n - Component 1 (0.3): jira_mock 中 issues 里 id 为 'i7' 的 issue status == 'In Progress'\n - Component 2 (0.1): slack_mock 中 messages.general 里有 messageId 不在 seed 中且 senderId == 'user_1' 的新消息\n - Component 3 (0.15): slack_mock 中 messages.general 里 user_1 发送的新消息内容(小写)包含 'payments'、'hardening' 或 'kan-7' 任一\n - 总分累加,最后 min(total, 1.0) 并四舍五入到4位小数\n\n4. 失败模式:\n - 读取 sid 失败\n - 获取 mock 状态失败\n - 各组件检查失败(只是不加分,不会提前退出)\n\n5. 不是占位脚本,有实际检查逻辑。\n\n现在构建 JSON:\n\n- task_id: \"7c71ec24-a33a-5391-ac2a-b9724c61a29d\"(从 docstring 提取)\n- domain: \"mock_websites\"(从 docstring 提取)\n- summary: \"验证用户在 Trello 将 Payments 卡片移至 Doing、在 Jira 将 KAN-7 设为 In Progress、并在 Slack #general 频道发送包含 payments/hardening/kan-7 相关 announcement 的新消息\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"trello_mock\", \"jira_mock\", \"slack_mock\"]\n- scoring_components:\n - name: \"Component 0\" 或 \"Payments card moved to Doing\"\n weight: 0.45\n description: \"检查 Trello 中 Payments 卡片是否被移动到 Doing 列表\"\n check_logic: \"从 trello_mock 的 current_state.cards 中获取 card-pay,检查其 listId 是否等于 'list-2'\"\n pass_condition: \"c0_card 存在且 c0_card.get('listId') == 'list-2'\"\n - name: \"Component 1\" 或 \"KAN-7 set to In Progress\"\n weight: 0.3\n description: \"检查 Jira 中 issue KAN-7 (id=i7) 是否被设置为 In Progress\"\n check_logic: \"在 jira_mock 的 current_state.issues 中查找 id 为 'i7' 的 issue,检查其 status 是否等于 'In Progress'\"\n pass_condition: \"c1_iss 存在且 c1_iss.get('status') == 'In Progress'\"\n - name: \"Component 2\" 或 \"slack_new_msg\"\n weight: 0.1\n description: \"检查 Slack #general 频道是否有 user_1 发送的新消息\"\n check_logic: \"获取 slack_mock 的 current_state.messages.general,排除 SEED 中已有的 messageId ('g1'),筛选 senderId 为 'user_1' 的消息,检查是否存在这样的新消息\"\n pass_condition: \"c2_new 列表非空,即存在 messageId 不在 seed 中且 senderId == 'user_1' 的消息\"\n - name: \"Component 3\" 或 \"announces payments hardening\"\n weight: 0.15\n description: \"检查 Slack #general 频道中 user_1 的新消息内容是否包含 payments hardening 相关关键词\"\n check_logic: \"获取 slack_mock 的 current_state.messages.general 中 user_1 发送的新消息(排除 seed),将所有内容转为小写拼接,检查是否包含 'payments'、'hardening' 或 'kan-7' 中的任意一个\"\n pass_condition: \"c3_blob 中包含 'payments'、'hardening' 或 'kan-7' 任一子串\"\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到4位小数\"\n- failure_modes: [\n \"读取 /tmp/task_web_sid 失败或为空,输出 REWARD: 0.0 并 sys.exit(0)\",\n \"从 trello_mock、jira_mock 或 slack_mock 获取状态失败,输出 REWARD: 0.0 并 sys.exit(0)\",\n \"Trello 中 card-pay 不存在或 listId 不是 'list-2',Component 0 不得分\",\n \"Jira 中 id 为 i7 的 issue 不存在或 status 不是 'In Progress',Component 1 不得分\",\n \"Slack #general 中无 user_1 发送的新消息(排除 seed),Component 2 不得分\",\n \"Slack #general 中 user_1 新消息内容不包含 'payments'、'hardening' 或 'kan-7',Component 3 不得分\"\n ]\n- scoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 trello_mock、jira_mock、slack_mock 发送请求获取 current_state。任一前置步骤失败都会直接输出 0.0 并退出。接着脚本按顺序检查四个组件:1) Trello 中 card-pay 的 listId 是否为 'list-2'(Doing 列表),通过加 0.45;2) Jira 中 id 为 'i7' 的 issue 状态是否为 'In Progress',通过加 0.3;3) Slack #general 中是否存在 senderId 为 'user_1' 且 messageId 不在 seed 中的新消息,通过加 0.1;4) 上述 Slack 新消息内容(小写)是否包含 'payments'、'hardening' 或 'kan-7' 任一关键词,通过加 0.15。最终总分累加后使用 min(total, 1.0) 钳制,四舍五入保留四位小数输出。\"\n- confidence: 1.0\n\n检查要求:\n- 只输出 JSON 对象,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名、代码标识符保留原样\n- weight 填写显式分值\n\n确认 task_id:docstring 中 Task ID: 7c71ec24-a33a-5391-ac2a-b9724c61a29d,这是 UUID 格式的任务 ID。用户示例说 \"如 se_review_006\",但这里明确给了 UUID,应该用这个。\n\n确认 domain: mock_websites\n\n确认 is_placeholder: false\n\n确认 data_sources: 包含 /tmp/task_web_sid 和三个 mock\n\n一切看起来都正确。 {\"task_id\":\"7c71ec24-a33a-5391-ac2a-b9724c61a29d\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Trello 将 Payments 卡片移至 Doing、在 Jira 将 KAN-7 设为 In Progress、并在 Slack #general 频道发送包含 payments/hardening/kan-7 相关 announcement 的新消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"trello_mock\",\"jira_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 0: Payments card moved to Doing\",\"weight\":0.45,\"description\":\"检查 Trello 中 Payments 卡片是否被移动到 Doing 列表\",\"check_logic\":\"从 trello_mock 的 current_state.cards 中获取 card-pay,检查其 listId 是否等于 'list-2'\",\"pass_condition\":\"c0_card 存在且 c0_card.get('listId') == 'list-2'\"},{\"name\":\"Component 1: KAN-7 set to In Progress\",\"weight\":0.3,\"description\":\"检查 Jira 中 issue KAN-7 (id=i7) 是否被设置为 In Progress\",\"check_logic\":\"在 jira_mock 的 current_state.issues 中查找 id 为 'i7' 的 issue,检查其 status 是否等于 'In Progress'\",\"pass_condition\":\"c1_iss 存在且 c1_iss.get('status') == 'In Progress'\"},{\"name\":\"Component 2: slack_new_msg\",\"weight\":0.1,\"description\":\"检查 Slack #general 频道是否有 user_1 发送的新消息\",\"check_logic\":\"获取 slack_mock 的 current_state.messages.general,排除 SEED 中已有的 messageId ('g1'),筛选 senderId 为 'user_1' 的消息,检查是否存在这样的新消息\",\"pass_condition\":\"c2_new 列表非空,即存在 messageId 不在 seed 中且 senderId == 'user_1' 的消息\"},{\"name\":\"Component 3: announces payments hardening\",\"weight\":0.15,\"description\":\"检查 Slack #general 频道中 user_1 的新消息内容是否包含 payments hardening 相关关键词\",\"check_logic\":\"获取 slack_mock 的 current_state.messages.general 中 user_1 发送的新消息(排除 seed),将所有内容转为小写拼接,检查是否包含 'payments'、'hardening' 或 'kan-7' 中的任意一个\",\"pass_condition\":\"c3_blob 中包含 'payments'、'hardening' 或 'kan-7' 任一子串\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到4位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空,输出 REWARD: 0.0 并 sys.exit(0)\",\"从 trello_mock、jira_mock 或 slack_mock 获取状态失败,输出 REWARD: 0.0 并 sys.exit(0)\",\"Trello 中 card-pay 不存在或 listId 不是 'list-2',Component 0 不得分\",\"Jira 中 id 为 i7 的 issue 不存在或 status 不是 'In Progress',Component 1 不得分\",\"Slack #general 中无 user_1 发送的新消息(排除 seed),Component 2 不得分\",\"Slack #general 中 user_1 新消息内容不包含 'payments'、'hardening' 或 'kan-7',Component 3 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 trello_mock、jira_mock、slack_mock 发送请求获取 current_state。任一前置步骤失败都会直接输出 0.0 并退出。接着脚本按顺序检查四个组件:1) Trello 中 card-pay 的 listId 是否为 'list-2'(Doing 列表),通过加 0.45;2) Jira 中 id 为 'i7' 的 issue 状态是否为 'In Progress',通过加 0.3;3) Slack #general 中是否存在 senderId 为 'user_1' 且 messageId 不在 seed 中的新消息,通过加 0.1;4) 上述 Slack 新消息内容(小写)是否包含 'payments'、'hardening' 或 'kan-7' 任一关键词,通过加 0.15。最终总分累加后使用 min(total, 1.0) 钳制,四舍五入保留四位小数输出。\",\"confidence\":1.0}" +} diff --git a/pm_sprint_closeout_002__long/_cua_gym_vm_bridge.sh b/pm_sprint_closeout_002__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/pm_sprint_closeout_002__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/pm_sprint_closeout_002__long/initial_setup.py b/pm_sprint_closeout_002__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8783345bdea6916a59e501ef7bec992efd935f02 --- /dev/null +++ b/pm_sprint_closeout_002__long/initial_setup.py @@ -0,0 +1,816 @@ +""" +Initial Setup: W04 — Agile PM × Sprint closeout +Task ID: pm_sprint_closeout_002__long +Persona: Agile PM Lena +Mocks: jira_mock,asana_mock,discord_mock,google_sheets_mock + +Ground-truth embedding (read by reward.py from initial_state): + - Jira sprints[*]._expected_state on the ACTIVE sprint ('closed') — the + sprint must be closed out. + - Jira issues[*]._expected_sprintId on every issue in the active sprint — + this is the TRIAGE answer key and the core judgement of the task: + * 'Done' issues keep the active-sprint id (they stay recorded against + the sprint). + * incomplete issues the TEAM decided to CARRY must be moved to the NEXT + sprint (Sprint 15, id 's-next') — the agent has to MOVE them there + BEFORE closing the sprint, because "Complete Sprint" only sweeps + issues still in the active sprint. + * incomplete issues the team decided to DROP return to the backlog + (sprintId null) — these are the ones "Complete Sprint" sweeps. + The carry/drop decision is NOT written on the Jira issue anymore (no + 'carry-next' label). It lives ONLY in the Discord #standup retro + discussion, phrased by FEATURE NAME (never by issue key). So the agent + must: read the discussion, semantically join each decision to the matching + Jira issue by its summary, and triage per-issue. Crucially, issue STATUS + does NOT predict the decision (a To-Do item may be carried; an In-Progress + item may be dropped) — a status heuristic fails, and a one-click closeout + scores only the drop-to-backlog subset. + - Jira issues[*]._expected_disposition on every active-sprint issue + ('Completed' for Done, 'Carried Over' for any incomplete one) — the value + to log in the sprint report. + - Asana tasks[*]._expected_section on each carry-over card — the section + (by priority rule: High->Critical, Medium->Standard, Low->Backlog). The + priority is NOT shown on the Asana card; the agent must open the matching + Jira issue and read the priority Jira has on record for that item. A second + cross-app join. + +Observable outputs kept ABSENT at injection (Rule 3): + - the active sprint is still state=='active' (NOT closed) and ALL its + issues still carry sprintId==s-active (none triaged to Sprint 15 / backlog + yet). + - every Asana carry-over card still sits in the 'Triage' section (none in + its expected target section yet). + - Google Sheet 'Sprint Report' Disposition column is blank on the issue rows. + - Discord #standup channel has ONLY the seeded retro discussion (the + decision source) — Lena's wrap-up summary is absent; reward diffs new + messages against the seeded ids so the seeded retro earns no credit. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# =========================================================================== +# JIRA — Apollo Platform scrum project. One ACTIVE sprint (the target) with +# 14 issues: 6 Done + 8 incomplete. The 8 incomplete ones are TRIAGED two +# ways by the TEAM'S DECISION recorded in the Discord #standup retro: +# - team decided to CARRY -> must be moved to the NEXT sprint (Sprint 15). +# - team decided to DROP -> return to the backlog at closeout. +# There is NO label on the issue signalling the decision. Status does NOT +# predict it either. The only source is the #standup discussion (by feature +# name). Plus a closed sprint and backlog/next-sprint issues as noise. +# =========================================================================== +ACTIVE_SPRINT_ID = 's-active' +NEXT_SPRINT_ID = 's-next' # Sprint 15 (future) — carry target + + +def jira_user(uid, name): + return {'id': uid, 'name': name, 'email': f'{name.lower().replace(" ", ".")}@apollo.io', + 'avatar': f'https://picsum.photos/100/100?random={uid}'} + + +LENA = jira_user('u1', 'Lena Ortiz') +J_USERS = [ + LENA, + jira_user('u2', 'Raj Patel'), + jira_user('u3', 'Mina Cho'), + jira_user('u4', 'Tom Vance'), +] + + +def jira_issue(iid, key, summary, status, sprint_id, points, assignee, + issue_type='Story', priority='Medium', labels=None, + expected_sprint_id=None, expected_disposition=None): + """Issue builder. expected_* are hidden answer keys (ignored by the UI, + stripped from current_state by normalizeIssue, but preserved verbatim in + the server-side initial_state where reward.py reads them).""" + rec = { + 'id': iid, 'key': key, 'projectId': 'p1', 'summary': summary, + 'description': '', 'type': issue_type, 'status': status, + 'priority': priority, 'storyPoints': points, + 'reporterId': 'u1', 'assigneeId': assignee, 'sprintId': sprint_id, + 'epicId': None, + 'createdAt': '2026-06-08T09:00:00.000Z', + 'updatedAt': '2026-06-22T09:00:00.000Z', + 'labels': list(labels) if labels else [], 'subtasks': [], 'linkedIssueIds': [], + } + if expected_sprint_id is not None or expected_disposition is not None: + # sentinel objects so we can carry null explicitly + rec['_expected_sprintId'] = expected_sprint_id + rec['_expected_disposition'] = expected_disposition + return rec + + +def active_issue(iid, key, summary, status, points, assignee, + issue_type='Story', priority='Medium', carry=None): + """An issue in the active sprint. Triage rule keyed off the TEAM DECISION + (the #standup retro), NOT any field on the issue: + - Done (carry is None) -> stays in the active sprint (Completed). + - incomplete + carry=True -> carried to Sprint 15 (Carried Over). + - incomplete + carry=False -> dropped to backlog (Carried Over). + NOTE: no 'carry-next' label is set — the decision is invisible on the + issue. `priority` is the value the Asana step must recover cross-app.""" + is_done = status == 'Done' + if is_done: + exp_sprint = ACTIVE_SPRINT_ID + exp_disp = 'Completed' + elif carry: + exp_sprint = NEXT_SPRINT_ID + exp_disp = 'Carried Over' + else: + exp_sprint = None + exp_disp = 'Carried Over' + return jira_issue( + iid, key, summary, status, ACTIVE_SPRINT_ID, points, assignee, + issue_type=issue_type, priority=priority, labels=None, + expected_sprint_id=exp_sprint, expected_disposition=exp_disp) + + +# 14 issues in the active sprint: 6 Done (stay) + 8 incomplete split by the +# TEAM'S DECISION (from #standup) -> 4 carried to Sprint 15, 4 dropped to +# backlog. Status is deliberately DECORRELATED from the decision: +# - AGL-105 is only 'To Do' yet the team decided to CARRY it (still wanted). +# - AGL-103 is 'In Progress' yet the team decided to DROP it (descoped). +# So a "status heuristic" (in-progress=carry, to-do=drop) gets several wrong. +ACTIVE_ISSUES = [ + # ---- 6 Done -> stay, Completed ---- + active_issue('i101', 'AGL-101', 'Add OAuth2 login flow', 'Done', 5, 'u2'), + active_issue('i102', 'AGL-102', 'Migrate user table to Postgres 16', 'Done', 8, 'u3', issue_type='Task'), + active_issue('i104', 'AGL-104', 'Fix avatar upload crash on Safari', 'Done', 3, 'u4', issue_type='Bug', priority='High'), + active_issue('i107', 'AGL-107', 'Rate-limit the public search API', 'Done', 5, 'u4'), + active_issue('i109', 'AGL-109', 'Ship dark-mode theme tokens', 'Done', 3, 'u4'), + active_issue('i111', 'AGL-111', 'Add CSV export to reports', 'Done', 2, 'u3', issue_type='Task'), + # ---- 4 incomplete the team decided to CARRY -> Sprint 15 ---- + active_issue('i103', 'AGL-103', 'Build billing webhook retries', 'In Progress', 5, 'u2', priority='High', carry=True), + active_issue('i105', 'AGL-105', 'Design notification preferences page', 'To Do', 3, 'u3', priority='Medium', carry=True), + active_issue('i108', 'AGL-108', 'Refactor session middleware', 'In Progress', 8, 'u3', issue_type='Task', priority='Medium', carry=True), + active_issue('i112', 'AGL-112', 'Add SAML group-to-role mapping', 'In Review', 5, 'u2', issue_type='Task', priority='High', carry=True), + # ---- 4 incomplete the team decided to DROP -> backlog ---- + active_issue('i106', 'AGL-106', 'Add audit log export endpoint', 'In Review', 5, 'u2', issue_type='Task', priority='High', carry=False), + active_issue('i110', 'AGL-110', 'Investigate flaky checkout e2e', 'To Do', 2, 'u2', issue_type='Bug', priority='Medium', carry=False), + active_issue('i113', 'AGL-113', 'Prototype in-app onboarding tour', 'In Progress', 3, 'u4', priority='Low', carry=False), + active_issue('i114', 'AGL-114', 'Tune search relevance weights', 'To Do', 5, 'u3', priority='Low', carry=False), +] + +# ---- NOISE: backlog issues (already unscheduled) and closed-sprint issues. +# No answer key; not scored. ---- +NOISE_ISSUES = [ + jira_issue('i201', 'AGL-201', 'Spike: evaluate feature-flag vendors', 'To Do', None, 5, 'u3'), + jira_issue('i202', 'AGL-202', 'Tech debt: drop legacy v1 API', 'To Do', None, 8, 'u2', issue_type='Task'), + jira_issue('i203', 'AGL-203', 'Write onboarding runbook', 'To Do', None, 3, 'u4'), + # closed-sprint issues (last sprint, already delivered) — do not touch + jira_issue('i301', 'AGL-091', 'Add SSO metadata endpoint', 'Done', 's-closed', 5, 'u2'), + jira_issue('i302', 'AGL-092', 'Cache product catalog reads', 'Done', 's-closed', 5, 'u3', issue_type='Task'), + # next-sprint issue (already planned ahead) — do not touch. It pre-seeds + # Sprint 15 so the future sprint is non-empty and visibly a real target. + jira_issue('i401', 'AGL-301', 'Plan Q3 mobile rewrite', 'To Do', NEXT_SPRINT_ID, 8, 'u4'), +] + +JIRA_SPRINTS = [ + {'id': ACTIVE_SPRINT_ID, 'projectId': 'p1', 'name': 'Sprint 14', + 'goal': 'Harden auth, billing and search for GA.', + 'startDate': '2026-06-15T09:00:00.000Z', 'endDate': '2026-06-29T09:00:00.000Z', + 'state': 'active', '_expected_state': 'closed'}, + {'id': 's-closed', 'projectId': 'p1', 'name': 'Sprint 13', + 'goal': 'SSO + catalog performance.', + 'startDate': '2026-06-01T09:00:00.000Z', 'endDate': '2026-06-14T09:00:00.000Z', + 'state': 'closed'}, + {'id': NEXT_SPRINT_ID, 'projectId': 'p1', 'name': 'Sprint 15', + 'goal': 'Carry-over work + mobile rewrite kickoff.', + 'startDate': '2026-06-30T09:00:00.000Z', 'endDate': '2026-07-13T09:00:00.000Z', + 'state': 'future'}, +] + +JIRA_STATE = { + 'currentUser': LENA, + 'users': J_USERS, + 'projects': [ + {'id': 'p1', 'key': 'AGL', 'name': 'Apollo Platform', 'leadId': 'u1', + 'category': 'Software', 'icon': 'https://picsum.photos/64/64?random=p1'}, + ], + 'sprints': JIRA_SPRINTS, + 'issues': ACTIVE_ISSUES + NOISE_ISSUES, + 'comments': [], + 'workflows': [{'id': 'w1', 'name': 'Software Workflow', 'transitions': [ + {'from': 'To Do', 'to': ['In Progress']}, + {'from': 'In Progress', 'to': ['In Review', 'To Do', 'Done']}, + {'from': 'In Review', 'to': ['Done', 'In Progress']}, + {'from': 'Done', 'to': ['In Progress', 'To Do']}, + ]}], + 'notifications': [ + {'id': 'n1', 'type': 'mention', 'issueId': 'i103', 'actorId': 'u2', + 'message': 'Raj mentioned you on AGL-103', 'read': False, + 'createdAt': '2026-06-28T15:00:00.000Z'}, + ], +} + + +# =========================================================================== +# ASANA — "Sprint Carryover" tracking project. One card per incomplete +# active-sprint issue, all starting in the 'Triage' section. Each must be +# moved into the section matching the priority JIRA has on record for that +# issue (High->Critical, Medium->Standard, Low->Backlog). The Asana card does +# NOT show the priority (its Priority field is blank) — the agent has to open +# the matching Jira issue and read the priority there. A cross-app join. +# =========================================================================== +SEC_TRIAGE = 'sec-triage' +SEC_CRIT = 'sec-crit' +SEC_STD = 'sec-std' +SEC_LOW = 'sec-low' + +PRIORITY_TO_SECTION = {'High': SEC_CRIT, 'Medium': SEC_STD, 'Low': SEC_LOW} + + +def asana_user(uid, name, title, dept): + return {'userId': uid, 'name': name, 'email': f'{name.lower().replace(" ", ".")}@apollo.io', + 'avatar': f'https://picsum.photos/100/100?random={uid}', 'title': title, + 'department': dept, 'location': 'Remote', 'timezone': 'PST', 'theme': 'light'} + + +A_LENA = asana_user('user-0', 'Lena Ortiz', 'Agile Program Manager', 'Product') +A_USERS = [ + A_LENA, + asana_user('user-1', 'Raj Patel', 'Backend Engineer', 'Engineering'), + asana_user('user-2', 'Mina Cho', 'Full-stack Engineer', 'Engineering'), + asana_user('user-3', 'Tom Vance', 'QA Engineer', 'Engineering'), +] + + +def asana_task(tid, name, priority, expected_section=None, section=SEC_TRIAGE, + assignee='user-1'): + """Task builder. `priority` is written to customFieldValues['field-1']. + For the carry-over cards we pass '' (blank) so the priority is NOT visible + on the card — the agent must recover it from Jira. _expected_section is the + hidden answer key (stripped from current_state by normalizeTask, preserved + in server-side initial_state for reward.py).""" + rec = { + 'taskId': tid, 'name': name, 'projectId': 'project-1', 'sectionId': section, + 'description': '', 'assigneeId': assignee, 'creatorId': 'user-0', + 'completed': False, 'dependencies': [], 'tags': [], 'attachmentIds': [], + 'customFieldValues': {'field-1': priority}, 'likeCount': 0, + 'createdDate': '2026-06-22T09:00:00.000Z', + 'modifiedDate': '2026-06-28T09:00:00.000Z', + } + if expected_section is not None: + rec['_expected_section'] = expected_section + return rec + + +# Build one carry-over card per incomplete Jira issue. The card's Priority +# field is left BLANK; the expected section is derived from the JIRA issue's +# priority (the cross-app answer key). Card name echoes the feature so the +# agent can locate the matching Jira issue. +_INCOMPLETE = [i for i in ACTIVE_ISSUES if '_expected_disposition' in i + and i['_expected_disposition'] == 'Carried Over'] +_ASANA_ASSIGNEE = {'u2': 'user-1', 'u3': 'user-2', 'u4': 'user-3'} +_CARD_NAME = { + 'i103': 'Carry over: billing webhook retries', + 'i105': 'Carry over: notification preferences page', + 'i108': 'Carry over: session middleware refactor', + 'i112': 'Carry over: SAML group-to-role mapping', + 'i106': 'Carry over: audit log export endpoint', + 'i110': 'Carry over: flaky checkout e2e investigation', + 'i113': 'Carry over: in-app onboarding tour prototype', + 'i114': 'Carry over: search relevance weight tuning', +} +ASANA_TASKS = [] +for _idx, _iss in enumerate(_INCOMPLETE, start=1): + ASANA_TASKS.append(asana_task( + f'task-c{_idx}', + _CARD_NAME.get(_iss['id'], f"Carry over: {_iss['summary']}"), + priority='', # blank on the card — force the Jira lookup + expected_section=PRIORITY_TO_SECTION[_iss['priority']], + section=SEC_TRIAGE, + assignee=_ASANA_ASSIGNEE.get(_iss['assigneeId'], 'user-1'))) + +# ---- NOISE: cards already filed in correct sections — no answer key, not +# scored, must not be touched. These DO carry a priority (they are +# already triaged), which also shows the blank carry-over cards are +# deliberately un-prioritised. ---- +ASANA_TASKS += [ + asana_task('task-n1', 'Triage backlog grooming', 'Medium', section=SEC_STD, assignee='user-0'), + asana_task('task-n2', 'Critical: prod incident postmortem', 'High', section=SEC_CRIT, assignee='user-1'), + asana_task('task-n3', 'Backlog: nice-to-have CSV import', 'Low', section=SEC_LOW, assignee='user-2'), +] + +ASANA_STATE = { + 'currentUser': A_LENA, + 'users': A_USERS, + 'teams': [ + {'teamId': 'team-1', 'name': 'Apollo Product', 'description': 'Product & delivery', + 'memberIds': ['user-0', 'user-1', 'user-2', 'user-3'], 'ownerId': 'user-0', + 'privacy': 'public', 'createdDate': '2026-01-01T00:00:00Z'}, + ], + 'projects': [ + {'projectId': 'project-1', 'name': 'Sprint Carryover', 'teamId': 'team-1', + 'description': 'Cross-team tracking of work carried over from closed sprints.', + 'color': '#4186E0', 'icon': 'https://picsum.photos/64/64?random=ap1', + 'ownerId': 'user-0', 'memberIds': ['user-0', 'user-1', 'user-2', 'user-3'], + 'sections': [ + {'sectionId': SEC_TRIAGE, 'name': 'Triage', 'collapsed': False}, + {'sectionId': SEC_CRIT, 'name': 'Critical', 'collapsed': False}, + {'sectionId': SEC_STD, 'name': 'Standard', 'collapsed': False}, + {'sectionId': SEC_LOW, 'name': 'Backlog', 'collapsed': False}, + ], + 'customFields': [ + {'fieldId': 'field-1', 'name': 'Priority', 'type': 'dropdown', + 'options': ['High', 'Medium', 'Low']}, + ], + 'privacy': 'public', 'startDate': '2026-06-15', 'dueDate': '2026-07-15', + 'archived': False, 'starred': True, + 'createdDate': '2026-06-15T00:00:00Z', 'modifiedDate': '2026-06-28T00:00:00Z'}, + ], + 'tasks': ASANA_TASKS, + 'comments': [], + 'portfolios': [], + 'goals': [], + 'notifications': [], + 'attachments': [], +} + + +# =========================================================================== +# DISCORD — Apollo Team server. #standup holds the SPRINT RETRO DISCUSSION: +# the team's per-item carry/drop calls, phrased by FEATURE NAME (never by +# issue key), mixed with praise for shipped work (noise). This is the ONLY +# source of the triage decision. Lena's closeout SUMMARY is absent — that is +# the observable output the agent must add (reward diffs new messages against +# these seeded ids, so the retro earns no credit on its own). +# =========================================================================== +def d_user(uid, username, disc, bot=False): + return {'id': uid, 'username': username, 'discriminator': disc, + 'avatar': f'https://picsum.photos/seed/{username}/128/128', + 'status': 'online', 'customStatus': None, 'aboutMe': '', + 'roles': ['role-team'], 'badges': [], 'bannerColor': '#5865F2', + 'joinedAt': '2026-01-15T10:00:00Z', 'isBot': bot} + + +D_LENA = d_user('user-current', 'Lena', '0001') +D_USERS = { + 'user-current': D_LENA, + 'user-2': d_user('user-2', 'Raj', '0002'), + 'user-3': d_user('user-3', 'Mina', '0003'), + 'user-4': d_user('user-4', 'Tom', '0004'), +} + + +def d_msg(mid, channel_id, user_id, content, ts): + return {'id': mid, 'channelId': channel_id, 'userId': user_id, 'content': content, + 'timestamp': ts, 'editedTimestamp': None, 'reactions': {}, 'attachments': [], + 'embeds': [], 'mentions': [], 'pinned': False, 'type': 'default', + 'referencedMessageId': None, 'threadId': None, 'isEdited': False} + + +# The retro thread in #standup. Decisions by FEATURE NAME: +# CARRY to next sprint: billing webhook retries, notification preferences +# page, session middleware, SAML group-to-role mapping. +# DROP to backlog: audit log export endpoint, flaky checkout e2e, +# in-app onboarding tour, search relevance weights. +# Praise for shipped work (OAuth, Postgres migration, dark mode, CSV export) +# is noise — those are Done and are NOT triage decisions. +_STANDUP_RETRO = [ + d_msg('m-s1', 'ch-standup', 'user-current', + "Sprint 14 retro thread — let's lock in what happens to everything " + "still open before I close the sprint. Shout out to Raj for landing " + "OAuth2 login and to Mina on the Postgres 16 migration 🎉", + '2026-06-29T16:00:00Z'), + d_msg('m-s2', 'ch-standup', 'user-2', + "Billing webhook retries is close but not done — I want to keep going " + "on it, please pull it into the next sprint. Same for the SAML " + "group-to-role mapping, it's in review and I'll finish it next week.", + '2026-06-29T16:03:00Z'), + d_msg('m-s3', 'ch-standup', 'user-3', + "Notification preferences page hasn't been started yet but product " + "still wants it, so let's carry it forward too. The session " + "middleware refactor is half-done — keep it for next sprint.", + '2026-06-29T16:05:00Z'), + d_msg('m-s4', 'ch-standup', 'user-2', + "On the flip side, the audit log export endpoint got descoped by " + "compliance this morning — drop it back to the backlog, we're not " + "carrying it.", + '2026-06-29T16:07:00Z'), + d_msg('m-s5', 'ch-standup', 'user-4', + "The in-app onboarding tour prototype was just an experiment and " + "we're parking it — send it to the backlog, not the next sprint. " + "Also nice work whoever shipped dark-mode tokens and the CSV export!", + '2026-06-29T16:09:00Z'), + d_msg('m-s6', 'ch-standup', 'user-3', + "Search relevance weight tuning didn't get picked up and it's low " + "priority — backlog it. And the flaky checkout e2e investigation is " + "stalled with no owner, so that goes back to the backlog as well " + "rather than into next sprint.", + '2026-06-29T16:11:00Z'), + d_msg('m-s7', 'ch-standup', 'user-current', + "Got it, thanks everyone. I'll sort the carryover cards, update the " + "report and post the wrap-up once the sprint is closed.", + '2026-06-29T16:13:00Z'), +] + +DISCORD_STATE = { + 'currentUser': D_LENA, + 'servers': { + 'server-1': { + 'id': 'server-1', 'name': 'Apollo Team', + 'icon': 'https://picsum.photos/seed/apollo-server/64/64', + 'ownerId': 'user-current', + 'channels': ['ch-general', 'ch-standup', 'ch-eng'], + 'roles': ['role-team'], + 'members': ['user-current', 'user-2', 'user-3', 'user-4'], + 'categories': [{'id': 'cat-1', 'name': 'TEXT CHANNELS', + 'channelIds': ['ch-general', 'ch-standup', 'ch-eng']}], + 'description': 'Apollo delivery team', 'boostCount': 0, 'boostTier': 0, + }, + }, + 'channels': { + 'ch-general': {'id': 'ch-general', 'serverId': 'server-1', 'name': 'general', + 'type': 'text', 'category': 'TEXT CHANNELS', 'topic': 'Team chatter', + 'position': 0, 'isNsfw': False, 'slowMode': 0, 'pinnedMessageIds': [], + 'lastMessageId': None, 'unreadCount': 0}, + 'ch-standup': {'id': 'ch-standup', 'serverId': 'server-1', 'name': 'standup', + 'type': 'text', 'category': 'TEXT CHANNELS', + 'topic': 'Daily standup & sprint ceremonies', 'position': 1, + 'isNsfw': False, 'slowMode': 0, 'pinnedMessageIds': [], + 'lastMessageId': 'm-s7', 'unreadCount': 0}, + 'ch-eng': {'id': 'ch-eng', 'serverId': 'server-1', 'name': 'engineering', + 'type': 'text', 'category': 'TEXT CHANNELS', 'topic': 'Eng deep dives', + 'position': 2, 'isNsfw': False, 'slowMode': 0, 'pinnedMessageIds': [], + 'lastMessageId': None, 'unreadCount': 0}, + }, + 'messages': { + 'm-g1': d_msg('m-g1', 'ch-general', 'user-2', + 'Morning! Sprint 14 wraps today — Lena will run the closeout.', + '2026-06-29T15:00:00Z'), + 'm-g2': d_msg('m-g2', 'ch-general', 'user-3', + 'Nice, a few of my tickets slipped though.', '2026-06-29T15:02:00Z'), + 'm-e1': d_msg('m-e1', 'ch-eng', 'user-4', + 'Checkout e2e is still flaky, might just park it.', '2026-06-29T14:30:00Z'), + **{m['id']: m for m in _STANDUP_RETRO}, + }, + 'threads': {}, + 'users': D_USERS, + 'roles': { + 'role-team': {'id': 'role-team', 'serverId': 'server-1', 'name': 'Team', + 'color': '#5865F2', 'position': 1, 'permissions': ['SEND_MESSAGES'], + 'hoist': True, 'mentionable': True}, + }, + 'dmConversations': {}, + 'activeVoiceChannel': None, + 'dms': [], + 'ui': {'memberSidebarVisible': True, 'threadPanelOpen': False, 'activeThreadId': None, + 'searchQuery': '', 'searchResults': [], 'pinnedPanelOpen': False}, +} + + +# =========================================================================== +# GOOGLE SHEETS — 'Sprint Report' ledger. +# Row 1: header (Issue | Disposition) +# Row 2: a worked EXAMPLE (AGL-090 | Completed) — demonstrates format, NOT scored. +# Rows 3..12: the 10 active-sprint issue keys in col A; Disposition (col B) +# BLANK (Rule 3) — agent fills each with Completed / Carried Over. +# =========================================================================== +def cell(v): + return {'value': str(v), 'formula': str(v), 'computed': str(v)} + + +def hcell(v): + return {'value': str(v), 'formula': str(v), 'computed': str(v), + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}} + + +ACTIVE_KEYS = [i['key'] for i in ACTIVE_ISSUES] +_sheet_data = { + 'A1': hcell('Issue'), + 'B1': hcell('Disposition'), + 'A2': cell('AGL-090'), + 'B2': cell('Completed'), # example row — reward ignores it +} +for _i, _key in enumerate(ACTIVE_KEYS): + _r = _i + 3 + _sheet_data[f'A{_r}'] = cell(_key) + _sheet_data[f'B{_r}'] = cell('') # blank — agent fills this + +SHEETS_STATE = { + 'id': 'workbook_sprint_report', 'title': 'Sprint Report', + 'activeSheetId': 'sheet_1', 'selectedCell': 'A1', 'selectionRange': None, + 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [], + 'namedRanges': [], 'conditionalFormats': [], 'charts': [], + 'showGridlines': True, 'showFormulas': False, 'zoom': 100, + 'sheets': [{ + 'id': 'sheet_1', 'name': 'Sprint Report', 'data': _sheet_data, + 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0, + 'tabColor': None, 'isHidden': False, 'columnWidths': {}, 'rowHeights': {}, + 'filterRange': None, 'filterCriteria': {}, 'sortColumn': None, + 'sortDirection': None, + }], +} + + +APP_STATES = [ + ('http://28.7.184.198:8153', JIRA_STATE), # jira_mock (L2 anchor) + ('http://28.7.184.198:8114', ASANA_STATE), # asana_mock + ('http://28.7.184.198:8129', DISCORD_STATE), # discord_mock + ('http://28.7.184.198:8145', SHEETS_STATE), # google_sheets_mock +] + +for placeholder, state in APP_STATES: + resp = requests.post( + f'{placeholder}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {placeholder}: {resp.text}' + ) + print(f'State injected: {placeholder} sid={sid}') + +for placeholder, _ in APP_STATES: + go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state') is not None, ( + f'initial_state is None after injection for {placeholder}' + ) + print(f'Verified initial_state set: {placeholder}') + + +def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8): + """Pure-HTTP readiness: wait for every mock to serve its injected state. + No CDP / 9222 probing (that hangs on local review boxes).""" + import urllib.request as _urlreq + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + deadline = time.time() + timeout + todo = list(urls) + while todo and time.time() < deadline: + rest = [] + for _u in todo: + try: + _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5) + if _r.status == 200: + print(f" {_u}: ready") + continue + except Exception: + pass + rest.append(_u) + todo = rest + if todo: + time.sleep(2) + print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}" + + (f" (pending: {todo})" if todo else "")) + time.sleep(render_buffer) + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/pm_sprint_closeout_002__long/reward.py b/pm_sprint_closeout_002__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..06d4919a5374658334dbaf5e14665ae722feee8e --- /dev/null +++ b/pm_sprint_closeout_002__long/reward.py @@ -0,0 +1,367 @@ +""" +Reward Script: W04 — Agile PM × Sprint closeout +Task ID: pm_sprint_closeout_002__long +Persona: Agile PM Lena +Mocks: jira_mock,asana_mock,discord_mock,google_sheets_mock + +Answer key (embedded in initial_state): + - Jira sprints[*]._expected_state on the active sprint ('closed'). + - Jira issues[*]._expected_sprintId on every active-sprint issue — the + TRIAGE key: Done -> keeps active-sprint id; incomplete the team decided to + CARRY -> next sprint ('s-next'); incomplete the team decided to DROP -> + null / backlog. The decision is NOT on the issue — it comes from the + Discord #standup retro (by feature name); the key is the resolved target. + - Jira issues[*]._expected_disposition ('Completed' | 'Carried Over'). + - Asana tasks[*]._expected_section on each carry-over card (Jira priority + rule: High->Critical, Medium->Standard, Low->Backlog). + +Scoring (sub-weights sum to 1.0): + 0.40 Jira sprint closeout + carry-over triage (L2 anchor). The core is the + per-issue triage decision read from the #standup retro, NOT a button: + 0.33 each INCOMPLETE active-sprint issue's current sprintId matches + its expected target (team CARRY -> Sprint 15; team DROP -> + null/backlog). One-click "Complete Sprint" without first + moving the carried issues scores only the dropped ones; a + status heuristic mis-triages the decorrelated items. + 0.07 the active sprint is 'closed'. + 0.25 Asana section: per carry-over card, current sectionId == expected + section (priority recovered from the matching Jira issue). Moving + wrong / extra moves never penalised. + 0.20 Google Sheet 'Sprint Report': per active-sprint issue row, the + Disposition column == expected disposition (example row ignored). + 0.15 Discord #standup summary: a NEW message (not one of the seeded retro + messages) reporting the closeout with the completed / carried-over + counts (loose match, with partial fallback). +""" +import re +import sys + +import requests + +# --- Read sid (fatal if missing) --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +APP_URLS = { + 'jira': 'http://28.7.184.198:8153', + 'asana': 'http://28.7.184.198:8114', + 'discord': 'http://28.7.184.198:8129', + 'google_sheets': 'http://28.7.184.198:8145', +} +_GO_CACHE = {} + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)') + print('REWARD: 0.0') + sys.exit(0) + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + _GO_CACHE[app_name] = payload + return payload + + +# --- Shared utils --- +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _by_id(records, key): + out = {} + for r in records or []: + if isinstance(r, dict) and r.get(key) is not None: + out[r[key]] = r + return out + + +# --- Google Sheets helpers --- +def _col_to_idx(col): + v = 0 + for ch in col: + v = v * 26 + (ord(ch) - ord('A') + 1) + return v - 1 + + +def _idx_to_col(idx): + idx += 1 + out = [] + while idx > 0: + idx, r = divmod(idx - 1, 26) + out.append(chr(ord('A') + r)) + return ''.join(reversed(out)) + + +def _parse_rows_from_sheet_data(sheet_data): + if not isinstance(sheet_data, dict) or not sheet_data: + return [] + used_cols = set() + max_row = 1 + for cell_id in sheet_data.keys(): + m = re.fullmatch(r'([A-Z]+)(\d+)', str(cell_id)) + if not m: + continue + used_cols.add(_col_to_idx(m.group(1))) + max_row = max(max_row, int(m.group(2))) + if not used_cols: + return [] + headers = [] + for cidx in sorted(used_cols): + cell = sheet_data.get(f'{_idx_to_col(cidx)}1', {}) + h = (cell.get('computed') if isinstance(cell, dict) else None) or (cell.get('value') if isinstance(cell, dict) else None) + h = norm(h) + if h: + headers.append((cidx, h)) + if not headers: + return [] + rows = [] + for r in range(2, max_row + 1): + row = {} + non_empty = False + for cidx, h in headers: + cell = sheet_data.get(f'{_idx_to_col(cidx)}{r}', {}) + val = (cell.get('computed') if isinstance(cell, dict) else None) + if val is None: + val = (cell.get('value') if isinstance(cell, dict) else None) + sval = '' if val is None else str(val) + row[h] = sval + if sval.strip(): + non_empty = True + if non_empty: + rows.append(row) + return rows + + +def _sheet_rows(go_payload, state_key, sheet_name): + state = go_payload.get(state_key, {}) or {} + sheets = state.get('sheets', []) + if isinstance(sheets, list): + for sheet in sheets: + if norm(sheet.get('name')) != norm(sheet_name): + continue + data_rows = _parse_rows_from_sheet_data(sheet.get('data', {})) + if data_rows: + return data_rows + for sheet in sheets: # fall back to first sheet + data_rows = _parse_rows_from_sheet_data(sheet.get('data', {})) + if data_rows: + return data_rows + return [] + + +# --- Discord helper: messages of a channel by name --- +def _discord_channel_messages(discord_state, channel_name): + channels = discord_state.get('channels', {}) or {} + target_id = None + if isinstance(channels, dict): + for cid, ch in channels.items(): + if isinstance(ch, dict) and norm(ch.get('name')) == norm(channel_name): + target_id = ch.get('id') or cid + break + if target_id is None: + return [] + msgs = discord_state.get('messages', {}) or {} + out = [] + if isinstance(msgs, dict): + for _mid, m in msgs.items(): + if isinstance(m, dict) and norm(m.get('channelId')) == norm(target_id): + out.append(m) + elif isinstance(msgs, list): + out = [m for m in msgs if norm(m.get('channelId')) == norm(target_id)] + return out + + +# ============================================================================= +# Task-specific reward +# ============================================================================= +def reward(go): + jira_i = go('jira').get('initial_state', {}) or {} + jira_c = go('jira').get('current_state', {}) or {} + asana_i = go('asana').get('initial_state', {}) or {} + asana_c = go('asana').get('current_state', {}) or {} + discord_i = go('discord').get('initial_state', {}) or {} + discord_c = go('discord').get('current_state', {}) or {} + + issues_i = jira_i.get('issues', []) or [] + issues_c_by_id = _by_id(jira_c.get('issues', []), 'id') + sprints_i = jira_i.get('sprints', []) or [] + sprints_c_by_id = _by_id(jira_c.get('sprints', []), 'id') + + # ---- answer key: active sprint + its issues ---- + active_sprints = [s for s in sprints_i if s.get('_expected_state')] + active_sprint_id = active_sprints[0].get('id') if active_sprints else 's-active' + active_issues = [i for i in issues_i if '_expected_sprintId' in i] + n_issues = len(active_issues) + n_completed = sum(1 for i in active_issues + if norm(i.get('_expected_disposition')) == 'completed') + n_carried = sum(1 for i in active_issues + if norm(i.get('_expected_disposition')) == 'carried over') + + # ---- 1) Jira sprint closeout + carry-over triage (L2 anchor) — 0.40 ---- + # The CORE is the per-issue triage judgement, not the button click: + # - incomplete issues are split by the hidden 'carry-next' label — some + # must be MOVED to Sprint 15 (s-next) before closeout, the rest are + # swept to the backlog. The agent has to decide each one. + # - Done issues stay in the active sprint; the sprint flips to closed. + sprint_score = 0.0 + incomplete_issues = [i for i in active_issues + if i.get('_expected_sprintId') != active_sprint_id] + done_issues = [i for i in active_issues + if i.get('_expected_sprintId') == active_sprint_id] + n_incomplete = len(incomplete_issues) + n_done = len(done_issues) + incomplete_match = 0 + s_state_ok = 0 + try: + # 1a: each incomplete issue triaged to its expected target (0.33) — THE anchor. + # carry-next -> Sprint 15 (s-next); otherwise -> null / backlog. + for i in incomplete_issues: + cur = issues_c_by_id.get(i.get('id'), {}) + if norm(cur.get('sprintId')) == norm(i.get('_expected_sprintId')): + incomplete_match += 1 + incomplete_frac = frac(incomplete_match, n_incomplete) if n_incomplete else 0.0 + + # NOTE: we deliberately do NOT score "Done issues still in the active sprint" + # — Done issues are seeded in the sprint at injection time, so that is a + # precondition (true before the agent acts), not a task-introduced change + # (mock-reward-gen Rule 2). Including it would give free credit at start. + + # 1b: active sprint moved to closed (0.07) — a real Complete-Sprint action. + for s in active_sprints: + cur = sprints_c_by_id.get(s.get('id'), {}) + if norm(cur.get('state')) == norm(s.get('_expected_state')): + s_state_ok += 1 + sprint_state_frac = frac(s_state_ok, len(active_sprints)) if active_sprints else 0.0 + + sprint_score = 0.33 * incomplete_frac + 0.07 * sprint_state_frac + except Exception as e: + print(f'DEBUG_W04 jira component error: {e!r}') + + # ---- 2) Asana section moves — 0.25 ---- + asana_tasks_i = [t for t in (asana_i.get('tasks', []) or []) + if t.get('_expected_section')] + asana_c_by_id = _by_id(asana_c.get('tasks', []), 'taskId') + n_asana = len(asana_tasks_i) + asana_match = 0 + try: + for t in asana_tasks_i: + cur = asana_c_by_id.get(t.get('taskId'), {}) + if norm(cur.get('sectionId')) == norm(t.get('_expected_section')): + asana_match += 1 + except Exception as e: + print(f'DEBUG_W04 asana component error: {e!r}') + asana_score = frac(asana_match, n_asana) + + # ---- 3) Google Sheet 'Sprint Report' — 0.20 ---- + key_to_disp = {norm(i.get('key')): norm(i.get('_expected_disposition')) + for i in active_issues} + sheet_match = 0 + try: + rows_c = _sheet_rows(go('google_sheets'), 'current_state', 'Sprint Report') + + def _row_field(row, *aliases): + for a in aliases: + if a in row: + return row[a] + return '' + + for key, disp in key_to_disp.items(): + for row in rows_c: + if norm(_row_field(row, 'issue', 'issue key', 'key')) == key: + if norm(_row_field(row, 'disposition', 'status', 'outcome')) == disp: + sheet_match += 1 + break + except Exception as e: + print(f'DEBUG_W04 sheet component error: {e!r}') + sheet_score = frac(sheet_match, n_issues) + + # ---- 4) Discord #standup summary (loose) — 0.15 ---- + # #standup is pre-seeded with the retro discussion (the decision source), + # so only NEW messages (ids absent from initial_state) count — the seeded + # retro must not earn credit. + discord_ok = 0.0 + try: + seeded_ids = set() + for m in _discord_channel_messages(discord_i, 'standup'): + mid = m.get('id') + if mid is not None: + seeded_ids.add(mid) + chan = [m for m in _discord_channel_messages(discord_c, 'standup') + if m.get('id') not in seeded_ids] + for m in chan: + txt = norm(m.get('content')) + if not txt: + continue + nums = [int(x) for x in re.findall(r'\d+', txt)] + mentions_completed = ('complet' in txt or 'done' in txt) + mentions_carried = ('carr' in txt or 'backlog' in txt or 'incomplete' in txt + or 'rollover' in txt or 'roll over' in txt) + if (n_completed in nums and n_carried in nums + and mentions_completed and mentions_carried): + discord_ok = 1.0 + break + if discord_ok == 0.0: # partial: any closeout-flavoured NEW non-empty message + for m in chan: + txt = norm(m.get('content')) + if txt and ('sprint' in txt or 'standup' in txt or 'closeout' in txt + or 'complet' in txt or 'carr' in txt): + discord_ok = 0.5 + break + except Exception as e: + print(f'DEBUG_W04 discord component error: {e!r}') + + # ---- Combine ---- + s_jira = sprint_score + s_asana = 0.25 * asana_score + s_sheet = 0.20 * sheet_score + s_discord = 0.15 * discord_ok + score = s_jira + s_asana + s_sheet + s_discord + + print( + 'DEBUG_W04 ' + f'n_issues={n_issues} n_completed={n_completed} n_carried={n_carried} ' + f'incomplete_match={incomplete_match}/{n_incomplete} ' + f'sprint_state_ok={s_state_ok}/{len(active_sprints)} ' + f'asana_match={asana_match}/{n_asana} ' + f'sheet_match={sheet_match}/{n_issues} ' + f'discord_ok={discord_ok} ' + f'w_jira={round(s_jira, 4)} w_asana={round(s_asana, 4)} ' + f'w_sheet={round(s_sheet, 4)} w_discord={round(s_discord, 4)} ' + f'total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/pm_sprint_planning_001__long/_cua_gym_vm_bridge.sh b/pm_sprint_planning_001__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/pm_sprint_planning_001__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/pm_sprint_planning_001__long/initial_setup.py b/pm_sprint_planning_001__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..24b16591bd16c28b34bbae063e4a07c4618f9281 --- /dev/null +++ b/pm_sprint_planning_001__long/initial_setup.py @@ -0,0 +1,685 @@ +""" +Initial Setup: SP01 — Sprint planning kickoff across Asana + Notion + Slack + +Google Calendar +Task ID: pm_sprint_planning_001__long +Persona: Delivery Manager Dana Lee +Mocks: asana_mock, notion_mock, slack_mock, google_calendar_mock + +Owner rule (stated in the instruction): match each committed task to the engineer +whose discipline fits the work — server-side/API work -> the Backend Engineer +(Bob), mobile-app (iOS/Android) work -> the Mobile Engineer (Carol), and +web-frontend/general work -> the Senior Engineer (Alice). Each task's description +states its discipline; the engineers' specialties are shown ONLY on their Slack +profiles (Asana lists everyone as a generic 'Software Engineer'), so the owner +must be resolved by cross-referencing Slack. + +Ground-truth embedding (read by reward.py from asana initial_state, sole source +of truth). Each candidate Asana task carries an inline answer key: + - tasks[*]._band : 'committed' | 'stretch' | 'blocked' — the sprint + band the agent must infer from the description + (ready + no open blocker + not a stretch/optional + item => committed). NOT re-derived in reward. + - tasks[*]._ready : whether the task *looks* ready at a glance + (informational; the blocked-looks-ready trap has + _ready==True but _band=='blocked'). + - tasks[*]._expected_owner_email : owner to assign a committed task to. + - tasks[*]._expected_due : due date ('YYYY-MM-DD') for a committed task. + - tasks[*]._notion_needed : whether a Notion 'Sprint Plan' row is needed. + - tasks[*]._expected_event : {title, date} kickoff event for committed. + +Observable outputs kept ABSENT at injection (Rule 3 — do-nothing scores 0): + - every candidate Asana task is UNASSIGNED (assigneeId None) with NO dueDate. + - the Notion 'Sprint Plan' database has NO rows (items: []). + - the Google Calendar has NO events (events: []). + - the Slack #delivery channel has zero messages (and nothing pinned). +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# --------------------------------------------------------------------------- +# Shared clock + cast. Emails line up across every app so the reward can map an +# owner email to the right Asana assignee. +# --------------------------------------------------------------------------- +TODAY = '2026-06-29' + +PEOPLE = { + 'alice': {'name': 'Alice Nguyen', 'email': 'alice.nguyen@company.com'}, + 'bob': {'name': 'Bob Martin', 'email': 'bob.martin@company.com'}, + 'carol': {'name': 'Carol Diaz', 'email': 'carol.diaz@company.com'}, + 'dana': {'name': 'Dana Lee', 'email': 'dana.lee@company.com'}, +} + + +# =========================================================================== +# ASANA (L1 source of truth: 'Sprint 24' backlog. The agent assigns owners + +# due dates to the committed work; the per-task answer key is embedded here.) +# =========================================================================== +def asana_user(uid, key, title, dept): + p = PEOPLE[key] + return { + 'userId': uid, 'name': p['name'], 'email': p['email'], + 'avatar': f'https://i.pravatar.cc/150?u={uid}', 'title': title, + 'department': dept, 'location': 'San Francisco, CA', + 'timezone': 'PST', 'theme': 'light', + } + + +ASANA_DANA = asana_user('user-0', 'dana', 'Delivery Manager', 'Engineering') +# Asana intentionally HIDES each engineer's specialty (everyone is a generic +# 'Software Engineer'); the distinguishing roles (Senior / Backend / Mobile +# Engineer) live ONLY on the Slack profiles, so the owner must be resolved by +# cross-referencing Slack. +ASANA_USERS = [ + ASANA_DANA, + asana_user('user-1', 'alice', 'Software Engineer', 'Engineering'), + asana_user('user-2', 'bob', 'Software Engineer', 'Engineering'), + asana_user('user-3', 'carol', 'Software Engineer', 'Engineering'), +] + +ASANA_PROJECT = { + 'projectId': 'project-sprint', 'name': 'Sprint 24', 'teamId': 'team-1', + 'description': 'Candidate backlog for the Sprint 24 planning session.', + 'color': '#4186E0', 'icon': 'https://i.pravatar.cc/40?u=sprint', + 'ownerId': 'user-0', 'memberIds': ['user-0', 'user-1', 'user-2', 'user-3'], + 'sections': [ + {'sectionId': 'section-candidates', 'name': 'Sprint 24 Candidates', 'collapsed': False}, + {'sectionId': 'section-done', 'name': 'Done', 'collapsed': False}, + ], + 'customFields': [], + 'privacy': 'public', 'startDate': TODAY, 'dueDate': '2026-07-10', + 'archived': False, 'starred': True, + 'createdDate': '2026-06-20T00:00:00Z', 'modifiedDate': '2026-06-28T00:00:00Z', +} + + +def asana_task(task_id, name, description, band, ready, + section_id='section-candidates', completed=False, + owner_email=None, expected_due=None, + notion_needed=False, expected_event=None): + """A Sprint 24 candidate. Injected UNASSIGNED with NO due date; the inline + answer key (_band etc.) is ignored by the UI and read only by reward.py.""" + rec = { + 'taskId': task_id, 'name': name, 'projectId': 'project-sprint', + 'sectionId': section_id, 'description': description, + 'assigneeId': None, 'creatorId': 'user-0', + 'dueDate': None, 'startDate': None, + 'completed': completed, + 'completedDate': '2026-06-27T00:00:00Z' if completed else None, + 'parentTaskId': None, 'dependencies': [], 'tags': [], + 'attachmentIds': [], 'customFieldValues': {}, 'likeCount': 0, + 'createdDate': '2026-06-20T00:00:00Z', + 'modifiedDate': '2026-06-25T00:00:00Z', + # ---- inline answer key ---- + '_band': band, + '_ready': ready, + } + if owner_email is not None: + rec['_expected_owner_email'] = owner_email + if expected_due is not None: + rec['_expected_due'] = expected_due + rec['_notion_needed'] = notion_needed + if expected_event is not None: + rec['_expected_event'] = expected_event + return rec + + +ASANA_TASKS = [ + # ---- COMMITTED (ready, no blocker, not stretch): assign + due + kickoff + + # notion row. Owner = the specialty match (see the owner rule above). ---- + asana_task( + 'task-1', 'Ship checkout redesign to production', + 'A web frontend redesign of the checkout page — UI work in the web app ' + 'only, with no backend or mobile changes. Design is approved and ' + 'engineering capacity is confirmed; no open dependencies, ready to start ' + 'this sprint.', + band='committed', ready=True, + owner_email=PEOPLE['alice']['email'], expected_due='2026-07-04', + notion_needed=True, + expected_event={'title': 'Kickoff: Ship checkout redesign to production', + 'date': '2026-06-30'}), + asana_task( + 'task-2', 'Migrate auth service to OAuth2', + 'Server-side backend/API work on the authentication service. Spec is ' + 'finalized and there are no external dependencies. Good to go for this ' + 'sprint.', + band='committed', ready=True, + owner_email=PEOPLE['bob']['email'], expected_due='2026-07-07', + notion_needed=True, + expected_event={'title': 'Kickoff: Migrate auth service to OAuth2', + 'date': '2026-07-01'}), + asana_task( + 'task-3', 'Launch mobile push notifications', + 'Mobile-app work to enable push notifications in the iOS and Android ' + 'apps. Assets are ready and the notification API is already in place. ' + 'Nothing blocking — commit it.', + band='committed', ready=True, + owner_email=PEOPLE['carol']['email'], expected_due='2026-07-09', + notion_needed=True, + expected_event={'title': 'Kickoff: Launch mobile push notifications', + 'date': '2026-07-02'}), + + # ---- STRETCH (optional; NOT part of the committed set) ---- + asana_task( + 'task-4', 'Add dark mode to settings page', + 'Stretch goal — a nice-to-have polish item to pick up only if there is ' + 'spare capacity after the committed work.', + band='stretch', ready=True), + asana_task( + 'task-5', 'Refactor analytics event schema', + 'Stretch: a larger refactor. Only start it if the committed work ' + 'finishes early.', + band='stretch', ready=False), + + # ---- BLOCKED (open blocker / external dependency; leave alone) ---- + asana_task( + 'task-6', 'Integrate third-party billing API', + 'Blocked: waiting on the vendor to provision our production API ' + 'credentials before any work can begin.', + band='blocked', ready=False), + # blocked-looks-ready TRAP: everything looks done, but rollout is on hold + # for an external (legal) sign-off, so it must NOT be committed/assigned. + asana_task( + 'task-7', 'Enable SSO for enterprise tenants', + 'All UI and backend work is complete and code-reviewed, and it reads as ' + 'ready — but rollout is on hold pending Legal\'s data-processing ' + 'sign-off, which has not landed. Keep it out of the sprint.', + band='blocked', ready=True), + + # ---- DONE distractor: already shipped last sprint; must be excluded from + # the committed pipeline (completed==True). ---- + asana_task( + 'task-8', 'Fix login redirect bug', + 'Shipped and verified in the previous sprint.', + band='committed', ready=True, section_id='section-done', completed=True, + owner_email=PEOPLE['alice']['email'], expected_due='2026-06-27', + notion_needed=True, + expected_event={'title': 'Kickoff: Fix login redirect bug', + 'date': '2026-06-20'}), +] + +ASANA_STATE = { + 'currentUser': ASANA_DANA, + 'users': ASANA_USERS, + 'teams': [ + {'teamId': 'team-1', 'name': 'Product Engineering', + 'description': 'Core product engineering team', + 'memberIds': ['user-0', 'user-1', 'user-2', 'user-3'], + 'ownerId': 'user-0', 'privacy': 'public', + 'createdDate': '2026-01-01T00:00:00Z'}, + ], + 'projects': [ASANA_PROJECT], + 'tasks': ASANA_TASKS, + 'comments': [], + 'portfolios': [], + 'goals': [], + 'notifications': [], + 'attachments': [], +} + + +# =========================================================================== +# NOTION ('Sprint Plan' database — the committed plan of record. Starts with +# NO rows; the agent adds one row per committed task.) +# =========================================================================== +NOTION_DANA = {'id': 'user-1', 'name': PEOPLE['dana']['name'], + 'email': PEOPLE['dana']['email'], 'avatar': ''} + +SPRINT_DB_ID = 'db-sprint-plan' + +NOTION_PAGES = { + SPRINT_DB_ID: { + 'id': SPRINT_DB_ID, 'title': 'Sprint Plan', 'icon': '\U0001F4CB', + 'cover': None, 'type': 'database', 'viewType': 'table', 'parentId': None, + 'favorite': True, + 'properties': [ + {'id': 'prop-owner', 'name': 'Owner', 'type': 'text'}, + {'id': 'prop-status', 'name': 'Status', 'type': 'select', + 'options': ['Committed', 'In Progress', 'Done']}, + {'id': 'prop-due', 'name': 'Due', 'type': 'date'}, + ], + 'views': [ + {'id': 'sp-view-table', 'name': 'Table View', 'type': 'table', + 'groupBy': None, 'filters': [], 'sorts': [], + 'visibleProperties': ['prop-owner', 'prop-status', 'prop-due']}, + ], + 'items': [], + 'blockIds': [], + 'createdDate': '2026-06-20T00:00:00.000Z', + }, +} + +NOTION_STATE = { + 'user': NOTION_DANA, + 'workspace': {'id': 'ws-1', 'name': 'Product Engineering', + 'icon': '\U0001F4BC', 'members': ['user-1']}, + 'pages': NOTION_PAGES, + 'blocks': {}, + 'trash': [], + 'comments': {}, + 'settings': { + 'appearance': 'light', 'startWeekMonday': False, 'fontSize': 'default', + 'notifDesktop': True, 'notifEmail': False, 'notifMobile': True, + 'teamspaces': [], + }, + 'notifications': [], + 'pageOrder': [SPRINT_DB_ID], + 'focusBlockId': None, +} + + +# =========================================================================== +# GOOGLE CALENDAR (kickoff meetings for the committed work — one per committed +# task. Starts with NO events.) +# =========================================================================== +CALENDAR_STATE = { + 'user': {'id': 'u1', 'username': PEOPLE['dana']['name'], + 'email': PEOPLE['dana']['email'], + 'avatar': 'https://i.pravatar.cc/150?u=dana'}, + 'calendars': [ + {'id': 'c1', 'name': 'Personal', 'color': '#039BE5', 'visible': True, + 'userId': 'u1', 'isDefault': True}, + {'id': 'c2', 'name': 'Work', 'color': '#33B679', 'visible': True, + 'userId': 'u1', 'isDefault': False}, + {'id': 'c3', 'name': 'Family', 'color': '#8E24AA', 'visible': True, + 'userId': 'u1', 'isDefault': False}, + ], + 'otherCalendars': [ + {'id': 'oc1', 'name': 'Holidays in United States', 'color': '#0B8043', + 'visible': True}, + ], + 'events': [], + 'view': 'week', + 'currentDate': f'{TODAY}T00:00:00.000Z', + 'sidebarOpen': True, + 'settings': { + 'weekStart': 0, 'defaultDuration': 60, 'defaultView': 'week', + 'defaultReminder': {'type': 'popup', 'minutes': 10}, + 'timeFormat': '12h', 'showWeekNumbers': False, + 'showDeclinedEvents': False, + }, +} + + +# =========================================================================== +# SLACK (#delivery channel — post a committed-work summary and pin it. Channel +# starts empty with nothing pinned.) +# =========================================================================== +def slack_user(uid, key, title, status='online', tz='America/Los_Angeles', + random_n=1): + p = PEOPLE[key] + first = p['name'].split()[0] + return { + 'userId': uid, 'fullName': p['name'], 'displayName': first, + 'email': p['email'], + 'avatar': f'https://picsum.photos/200/200?random={random_n}', + 'title': title, 'status': status, 'statusMessage': '', 'statusEmoji': '', + 'timeZone': tz, + } + + +SLACK_DANA = slack_user('user_1', 'dana', 'Delivery Manager', random_n=1) +SLACK_USERS = [ + SLACK_DANA, + slack_user('user_2', 'alice', 'Senior Engineer', random_n=2), + slack_user('user_3', 'bob', 'Backend Engineer', random_n=3), + slack_user('user_4', 'carol', 'Mobile Engineer', status='away', random_n=4), +] + +SLACK_STATE = { + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide chatter', + 'topic': 'Welcome!', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', + 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'engineering', 'name': 'engineering', 'description': 'Eng coordination', + 'topic': 'Ship it', 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_1', + 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'delivery', 'name': 'delivery', 'description': 'Sprint delivery updates', + 'topic': 'Post the sprint commitment after planning', 'isPrivate': False, + 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': SLACK_DANA, + 'users': SLACK_USERS, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Product Engineering', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', + 'content': 'Morning! Sprint 24 planning is at 10.', 'timestamp': '2026-06-29T13:02:00Z', + 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'engineering': [ + {'messageId': 'm_e_1', 'senderId': 'user_3', + 'content': 'OAuth2 spec is finalized, ready when planning lands.', + 'timestamp': '2026-06-28T22:10:00Z', 'reactions': [], 'isEdited': False, + 'threadId': None, 'attachments': []}, + ], + 'delivery': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', + 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], +} + + +# =========================================================================== +# Inject (each mock gets its FULL top-level schema; missing keys -> blank page) +# =========================================================================== +APP_STATES = [ + ('http://28.7.184.198:8114', ASANA_STATE), # asana_mock (L1 anchor) + ('http://28.7.184.198:8166', NOTION_STATE), # notion_mock + ('http://28.7.184.198:8178', SLACK_STATE), # slack_mock + ('http://28.7.184.198:8141', CALENDAR_STATE), # google_calendar_mock +] + +for placeholder, state in APP_STATES: + resp = requests.post( + f'{placeholder}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {placeholder}: {resp.text}' + ) + print(f'State injected: {placeholder} sid={sid}') + +for placeholder, _ in APP_STATES: + go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state') is not None, ( + f'initial_state is None after injection for {placeholder}' + ) + print(f'Verified initial_state set: {placeholder}') + + +def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8): + """Pure-HTTP readiness: wait for every mock to serve its injected state. + No CDP / 9222 probing (that hangs on local review boxes).""" + import urllib.request as _urlreq + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + deadline = time.time() + timeout + todo = list(urls) + while todo and time.time() < deadline: + rest = [] + for _u in todo: + try: + _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5) + if _r.status == 200: + print(f" {_u}: ready") + continue + except Exception: + pass + rest.append(_u) + todo = rest + if todo: + time.sleep(2) + print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}" + + (f" (pending: {todo})" if todo else "")) + time.sleep(render_buffer) + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/pm_sprint_planning_001__long/reward.py b/pm_sprint_planning_001__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..48a16374465688748ced6104aa3cd2cbd45145d6 --- /dev/null +++ b/pm_sprint_planning_001__long/reward.py @@ -0,0 +1,302 @@ +""" +Reward Script: SP01 — Sprint planning kickoff across Asana + Notion + Slack + +Google Calendar +Task ID: pm_sprint_planning_001__long +Persona: Delivery Manager Dana Lee +Mocks: asana_mock, notion_mock, slack_mock, google_calendar_mock + +Answer key (sole source of truth): asana.initial_state.tasks[*] inline fields + _band ('committed'|'stretch'|'blocked'), _ready, _expected_owner_email, + _expected_due, _notion_needed, _expected_event. + +The scored "committed pipeline" = tasks with _band=='committed' AND not +completed (the already-shipped done distractor is a committed-band task that is +completed, so it is excluded). The blocked-looks-ready trap is _band=='blocked' +with _ready==True: assigning it never adds points, and dilutes precision. + +Scoring (sub-weights sum to 1.0; every component is frac over +absent-at-injection outputs -> do-nothing == 0; NO penalties). The Monday mirror +component was removed with the monday_mock app; its 0.20 weight was redistributed +proportionally across the remaining components: + 0.3125 Asana assign decision-set : hits / (|committed| + wrongly-assigned-blocked). + hits = committed tasks assigned to the correct owner. Precision leaks + through the denominator when a blocked task is wrongly assigned. + 0.125 Asana due-date (committed) : frac of committed tasks whose current dueDate + matches _expected_due to the day. + 0.25 Calendar kickoff : frac of committed tasks with a kickoff event + titled _expected_event.title on _expected_event.date (compared by local + UTC+8 date). + 0.15 Notion plan-row recall : frac of committed tasks (_notion_needed) with + a 'Sprint Plan' database row whose title matches the task name. + 0.125 Slack post : a non-empty message exists in #delivery. + 0.0375 Slack pin (gated) : that #delivery message is pinned (only counts + if a post exists). +""" +import re +import sys + +import requests + +from datetime import datetime, timezone, timedelta + +TZ_PLUS_8 = timezone(timedelta(hours=8)) + + +def parse_as_utc(s, default_tz=TZ_PLUS_8): + """Parse an ISO datetime string and convert it to UTC. A tz-less value is + treated as UTC+8; Z / explicit offsets are honoured.""" + if not s: + return None + s = str(s).strip() + if s.endswith("Z"): + s = s[:-1] + "+00:00" + try: + dt = datetime.fromisoformat(s) + except ValueError: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=default_tz) + return dt.astimezone(timezone.utc) + + +def date_key(s, local_tz=TZ_PLUS_8): + """Return the calendar date (YYYY-MM-DD) an ISO datetime represents in LOCAL + (UTC+8) terms. Timezone-aware values are converted to local first so a UTC + '...T..Z' round-trips to the same local day as a naive value. Naive values + are taken as-is. Bare 'YYYY-MM-DD' strings fall back to their first 10 chars.""" + if not s: + return None + s = str(s).strip() + if s.endswith("Z"): + s = s[:-1] + "+00:00" + try: + dt = datetime.fromisoformat(s) + except ValueError: + return s[:10] if len(s) >= 10 else None + if dt.tzinfo is not None: + dt = dt.astimezone(local_tz) + return dt.date().isoformat() + + +# --- Read sid (fatal if missing) --- +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +APP_URLS = { + 'asana': 'http://28.7.184.198:8114', + 'notion': 'http://28.7.184.198:8166', + 'slack': 'http://28.7.184.198:8178', + 'google_calendar': 'http://28.7.184.198:8141', +} +_GO_CACHE = {} + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)') + print('REWARD: 0.0') + sys.exit(0) + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + _GO_CACHE[app_name] = payload + return payload + + +# --- Shared utils --- +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _collapse_ws(s): + return re.sub(r'\s+', ' ', norm(s)) + + +def _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) + target = None + for ch in channels: + if norm(ch.get('name')) == norm(channel_name): + target = ch + break + if target is None: + return [] + ch_msgs = target.get('messages') + if isinstance(ch_msgs, list): + return ch_msgs + msg_map = slack_state.get('messages', {}) + if isinstance(msg_map, dict): + return msg_map.get(target.get('channelId'), []) or [] + return [] + + +# ============================================================================= +# Task-specific reward +# ============================================================================= +def reward(go): + asana = go('asana') + a_i = asana.get('initial_state', {}) or {} + a_c = asana.get('current_state', {}) or {} + + tasks_i = a_i.get('tasks', []) or [] + + # asana userId -> email (from stable initial users) + a_users = a_i.get('users', []) or [] + uid_to_email = {u.get('userId'): norm(u.get('email')) + for u in a_users if isinstance(u, dict)} + + # committed pipeline = _band=='committed' and NOT completed + committed = [t for t in tasks_i if isinstance(t, dict) + and norm(t.get('_band')) == 'committed' and not t.get('completed')] + blocked_ids = {t.get('taskId') for t in tasks_i if isinstance(t, dict) + and norm(t.get('_band')) == 'blocked'} + n_committed = len(committed) + + tasks_c_by_id = {t.get('taskId'): t for t in (a_c.get('tasks', []) or []) + if isinstance(t, dict)} + + # ---- 1) Asana assign decision-set — 0.3125 ---- + # hits = committed tasks assigned to the correct owner. + # denom = |committed| + wrongly-assigned-blocked (precision leak). + assign_hits = 0 + for t in committed: + cur = tasks_c_by_id.get(t.get('taskId'), {}) + cur_email = uid_to_email.get(cur.get('assigneeId')) + if cur_email and cur_email == norm(t.get('_expected_owner_email')): + assign_hits += 1 + wrong_blocked = 0 + for tid in blocked_ids: + cur = tasks_c_by_id.get(tid, {}) + if cur.get('assigneeId'): + wrong_blocked += 1 + assign_den = n_committed + wrong_blocked + assign_score = frac(assign_hits, assign_den) + + # ---- 2) Asana due-date (committed) — 0.125 ---- + due_hits = 0 + for t in committed: + cur = tasks_c_by_id.get(t.get('taskId'), {}) + want = date_key(t.get('_expected_due')) + got = date_key(cur.get('dueDate')) + if want and got and want == got: + due_hits += 1 + due_score = frac(due_hits, n_committed) + + # ---- 3) Calendar kickoff (committed) — 0.25 ---- + cal_c = go('google_calendar').get('current_state', {}) or {} + cur_events = cal_c.get('events', []) or [] + cal_hits = 0 + for t in committed: + ev_key = t.get('_expected_event') or {} + want_title = norm(ev_key.get('title')) + want_date = ev_key.get('date') + for ev in cur_events: + if not isinstance(ev, dict): + continue + if (norm(ev.get('title')) == want_title + and date_key(ev.get('start')) == want_date): + cal_hits += 1 + break + cal_score = frac(cal_hits, n_committed) + + # ---- 4) Notion plan-row recall (committed) — 0.15 ---- + notion_c = go('notion').get('current_state', {}) or {} + n_pages = notion_c.get('pages', {}) or {} + # find the Sprint Plan database id + sprint_db_ids = set() + for pid, page in (n_pages.items() if isinstance(n_pages, dict) else []): + if isinstance(page, dict) and norm(page.get('type')) == 'database' \ + and norm(page.get('title')) == 'sprint plan': + sprint_db_ids.add(pid) + # titles of rows currently in the sprint plan database(s) + row_titles = set() + for pid, page in (n_pages.items() if isinstance(n_pages, dict) else []): + if isinstance(page, dict) and page.get('parentId') in sprint_db_ids: + row_titles.add(norm(page.get('title'))) + notion_needed = [t for t in committed if t.get('_notion_needed')] + notion_hits = sum(1 for t in notion_needed if norm(t.get('name')) in row_titles) + notion_score = frac(notion_hits, len(notion_needed)) if notion_needed else 0.0 + + # ---- 5) Slack post + 6) pin (gated) — 0.125 / 0.0375 ---- + slack_c = go('slack').get('current_state', {}) or {} + delivery_msgs = _slack_channel_messages(slack_c, 'delivery') + _delivery_kw = ('sprint', 'commit', 'committed', 'capacity', 'point', 'story', 'velocity') + def _is_delivery_summary(m): + t = (_msg_text(m) or '').lower() + return bool(t.strip()) and any(k in t for k in _delivery_kw) + post_ok = any(_is_delivery_summary(m) + for m in delivery_msgs if isinstance(m, dict)) + delivery_ch = None + for ch in (slack_c.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == 'delivery': + delivery_ch = ch + break + pinned_ids = (delivery_ch.get('pinnedMessages') or []) if isinstance(delivery_ch, dict) else [] + delivery_msg_ids = {(m.get('messageId') or m.get('id')) + for m in delivery_msgs if isinstance(m, dict)} + pin_ok = bool(post_ok and any(pid in delivery_msg_ids for pid in pinned_ids)) + post_score = 1.0 if post_ok else 0.0 + pin_score = 1.0 if pin_ok else 0.0 + + # ---- Combine ---- + s_assign = 0.3125 * assign_score + s_due = 0.125 * due_score + s_cal = 0.25 * cal_score + s_notion = 0.15 * notion_score + s_post = 0.125 * post_score + s_pin = 0.0375 * pin_score + score = s_assign + s_due + s_cal + s_notion + s_post + s_pin + + print( + 'DEBUG_SPRINT ' + f'n_committed={n_committed} ' + f'assign_hits={assign_hits}/{assign_den} (wrong_blocked={wrong_blocked}) ' + f'assign_score={round(assign_score, 4)} ' + f'due_hits={due_hits}/{n_committed} due_score={round(due_score, 4)} ' + f'cal_hits={cal_hits}/{n_committed} cal_score={round(cal_score, 4)} ' + f'notion_hits={notion_hits}/{len(notion_needed)} notion_score={round(notion_score, 4)} ' + f'slack_post={post_ok} slack_pin={pin_ok} ' + f'w_assign={round(s_assign, 4)} w_due={round(s_due, 4)} ' + f'w_cal={round(s_cal, 4)} ' + f'w_notion={round(s_notion, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} ' + f'total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/recruit_screen_002/_cua_gym_vm_bridge.sh b/recruit_screen_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_screen_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/recruit_screen_002/initial_setup.py b/recruit_screen_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..bbec3c90e56b362c19ab51c7922e7674399252ef --- /dev/null +++ b/recruit_screen_002/initial_setup.py @@ -0,0 +1,213 @@ +""" +Initial Setup: Candidate screening advance — Nina Patel to Hiring Manager Interview +Task ID: recruit_screen_002 +Domain: mock_websites (greenhouse + gmail + slack) + +Real mocks used (all live in the registry): + Greenhouse (8146) — ATS pipeline: Nina Patel's application in the 'Recruiter Screen' + stage (NOT yet in 'Hiring Manager Interview'); NO scorecard/note yet. + Gmail (8138) — recruiter mailbox; NO sent email to Nina about next steps. + Slack (8178) — #hiring channel with prior chatter; hiring manager Greg present; + NO message tagging Greg to review Nina. + +Pre-task invariants (so reward scores ONLY task-introduced deltas): + - Greenhouse: 'Software Engineer' job with a 'Hiring Manager Interview' stage. + Nina's application in 'Recruiter Screen'. scorecards=[] , notes=[]. + - Gmail: no sent email to nina.patel@gmail.com. + - Slack: #hiring pre-seeded; no @greg review request. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +GREENHOUSE_URL = 'http://28.7.184.198:8146' +GMAIL_URL = 'http://28.7.184.198:8138' +SLACK_URL = 'http://28.7.184.198:8178' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated session ID: {sid}') + + +# ===================================================================== +# Greenhouse — Nina Patel in Recruiter Screen, no scorecard/note yet. +# ===================================================================== +def build_greenhouse_state(): + users = [ + {"id": "user-1", "firstName": "Taylor", "lastName": "Reed", "name": "Taylor Reed", + "email": "recruiter@company.com", "role": "recruiter", + "department": "People Operations", "title": "Senior Recruiter", "avatarUrl": None}, + {"id": "user-greg", "firstName": "Greg", "lastName": "Hall", "name": "Greg Hall", + "email": "greg.hall@company.com", "role": "hiring_manager", + "department": "Engineering", "title": "Engineering Manager", "avatarUrl": None}, + ] + departments = [{"id": "dept-eng", "name": "Engineering", "parentId": None}] + offices = [{"id": "office-1", "name": "San Francisco HQ", "location": "San Francisco, CA"}] + + jobs = [{ + "id": "job-se", "title": "Software Engineer", "status": "open", + "departmentId": "dept-eng", "officeId": "office-1", + "hiringManagerId": "user-greg", "recruiterId": "user-1", "coordinatorId": None, + "openings": 1, "openDate": "2026-05-15", + }] + + stage_names = ["Application Review", "Recruiter Screen", "Hiring Manager Interview", + "Onsite", "Offer"] + job_stages = [] + for i, nm in enumerate(stage_names): + job_stages.append({ + "id": f"stage-se-{i}", "jobId": "job-se", "name": nm, "orderIndex": i, + "stageType": nm.lower().replace(' ', '_'), + }) + screen_stage_id = "stage-se-1" # Recruiter Screen (Nina starts here) + + candidates = [ + {"id": "cand-nina", "firstName": "Nina", "lastName": "Patel", "name": "Nina Patel", + "email": "nina.patel@gmail.com", "phone": "(415) 555-0180", + "location": "San Francisco, CA", "currentCompany": "Datadog", + "currentTitle": "Software Engineer", "resumeUrl": "#", "linkedinUrl": "#", + "source": "applied", "referrerId": None, "tags": ["backend", "6 years"], + "createdAt": "2026-06-05T10:00:00Z", "updatedAt": "2026-06-24T10:00:00Z"}, + ] + + applications = [ + {"id": "app-nina", "candidateId": "cand-nina", "jobId": "job-se", + "currentStageId": screen_stage_id, "status": "active", + "appliedAt": "2026-06-05T10:00:00Z", "rejectedAt": None, "rejectionReason": None, + "hiredAt": None, "lastActivityAt": "2026-06-24T10:00:00Z", "source": "applied", + "creditedTo": None, "recruiterId": "user-1", "coordinatorId": None, + "actionRequired": None, "daysInCurrentStage": 2}, + ] + + return { + "currentUser": users[0], + "users": users, + "departments": departments, + "offices": offices, + "jobs": jobs, + "jobStages": job_stages, + "candidates": candidates, + "applications": applications, + "scorecards": [], + "interviews": [], + "offers": [], + "notes": [], + "activityFeed": [], + "notifications": [], + "sources": [{"id": "src-applied", "name": "Applied"}], + "rejectionReasons": [], + "settings": {}, + "ui": {"selectedJobId": "job-se", "selectedApplicationId": "app-nina"}, + } + + +# ===================================================================== +# Gmail — recruiter mailbox; no sent email to Nina yet. +# ===================================================================== +def build_gmail_state(): + return { + "user": {"userId": "u1", "username": "Taylor Reed", "email": "recruiter@company.com", + "avatar": ""}, + "emails": [ + {"id": "email_1", "threadId": "thread_1", + "from": {"name": "Greenhouse Recruiting", "email": "no-reply@greenhouse.io"}, + "to": [{"name": "Taylor Reed", "email": "recruiter@company.com"}], + "subject": "Recruiter screen complete: Nina Patel — Software Engineer", + "body": "

Nina Patel passed her recruiter screen for the Software Engineer role.

", + "timestamp": "2026-06-24T09:00:00Z", "read": True, "starred": False, + "important": False, "labels": ["l1"], "category": "primary", + "folder": "inbox", "attachments": []}, + ], + "labels": [ + {"id": "l1", "name": "Work", "color": "#ef4444"}, + {"id": "l2", "name": "Personal", "color": "#3b82f6"}, + ], + "drafts": [], + } + + +# ===================================================================== +# Slack — #hiring with hiring manager Greg; no review request yet. +# ===================================================================== +def build_slack_state(): + recruiter = {"userId": "user_1", "fullName": "Taylor Reed", "displayName": "Taylor", + "email": "recruiter@company.com", "avatar": "", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"} + greg = {"userId": "user_greg", "fullName": "Greg Hall", "displayName": "greg", + "email": "greg.hall@company.com", "avatar": "", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"} + return { + "currentUser": recruiter, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Company Hiring", "icon": ""}, + "users": [recruiter, greg], + "channels": [ + {"channelId": "hiring", "name": "hiring", "description": "Hiring team coordination", + "topic": "Candidate discussions and hiring process", "isPrivate": False, + "isStarred": True, "members": ["user_1", "user_greg"], "createdBy": "user_1", + "createdAt": "2026-06-20T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "general", "name": "general", "description": "General workspace chat", + "topic": "", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_greg"], "createdBy": "user_1", + "createdAt": "2026-06-20T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "hiring": [ + {"messageId": "msg_1", "senderId": "user_1", + "content": "Welcome to the hiring channel! Let's coordinate candidate reviews here.", + "timestamp": "2026-06-20T10:05:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + "general": [], + }, + "threads": {}, "dms": [], "bookmarkedMessages": [], "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], "notifications": [], + } + + +# ===================================================================== +# Inject baseline state (action: "set") +# ===================================================================== +mocks = [ + ("Greenhouse", GREENHOUSE_URL, build_greenhouse_state()), + ("Gmail", GMAIL_URL, build_gmail_state()), + ("Slack", SLACK_URL, build_slack_state()), +] + +for name, url, state in mocks: + print(f'Injecting initial state into {name} mock...') + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name} state injection failed: {resp.status_code} {resp.text}' + +for name, url, _ in mocks: + go = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state'), f'{name} initial_state is None after injection' + assert go.get('current_state'), f'{name} current_state is None after injection' +print(f'States injected + verified for all three mocks: sid={sid}') + + +# ===================================================================== +# Launch GUI (Chrome) for all three surfaces with DISPLAY=:0 +# ===================================================================== +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + + +launch_gui(f'google-chrome "{GREENHOUSE_URL}/?sid={sid}"', delay_sec=3.0) +print(f'GUI_READY: launched Greenhouse at {GREENHOUSE_URL}/?sid={sid}') +launch_gui(f'google-chrome "{GMAIL_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched Gmail at {GMAIL_URL}/?sid={sid}') +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched Slack at {SLACK_URL}/?sid={sid}') + +print('Initial setup complete - Greenhouse, Gmail, and Slack are ready for the agent') diff --git a/recruit_screen_002/reward.py b/recruit_screen_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..5d7a63e5878014066137bcbe4860aa68a1c106c6 --- /dev/null +++ b/recruit_screen_002/reward.py @@ -0,0 +1,207 @@ +""" +Reward Script: Candidate screening advance — Nina Patel to Hiring Manager Interview. +Task ID: recruit_screen_002 +Domain: mock_websites (greenhouse + gmail + slack) + +Fully DETERMINISTIC / rule-based (no LLM judge). All checks are DELTA vs +initial_state, so reward(initial_env) == 0.0. + +Scoring (total 1.0): + Component 1 — GREENHOUSE stage (0.30): + Nina's application moved INTO the 'Hiring Manager Interview' stage + (out of its initial stage). + Component 2 — GREENHOUSE scorecard note (0.30): + A NEW scorecard OR note was added for Nina whose text mentions BOTH + '6 years' (relevant experience) AND communication. + Component 3 — GMAIL (0.20): + A NEW sent email to nina.patel@gmail.com referencing the hiring-manager + interview as the next step. + Component 4 — SLACK (0.20): + A NEW #hiring message tagging the hiring manager (Greg) and asking to + review Nina's profile. +""" +import re +import sys + +import requests + +GREENHOUSE_URL = 'http://28.7.184.198:8146' +GMAIL_URL = 'http://28.7.184.198:8138' +SLACK_URL = 'http://28.7.184.198:8178' + +NINA_EMAIL = 'nina.patel@gmail.com' +HM_STAGE = 'hiring manager interview' + + +def read_sid(): + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid empty') + return sid + except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + return None + + +def fetch(url, sid): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=20).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + except Exception as e: + print(f'ERROR: cannot fetch {url}: {e}') + return None, None + + +def strip_html(s): + return re.sub(r'<[^>]+>', ' ', s or '') + + +def mentions_six_years(text): + t = (text or '').lower() + # '6 years', 'six years', '6 yrs', '6+ years' + return bool(re.search(r'\b(6|six)\s*\+?\s*(years|yrs)\b', t)) + + +def verify_greenhouse(sid): + """Components 1 (0.30) + 2 (0.30).""" + init, cur = fetch(GREENHOUSE_URL, sid) + if cur is None: + print('FAIL: Greenhouse unreachable') + return 0.0 + score = 0.0 + try: + stages = {s.get('id'): (s.get('name') or '').strip().lower() + for s in (cur.get('jobStages') or [])} + hm_stage_ids = {sid_ for sid_, nm in stages.items() if nm == HM_STAGE} + + def find_app(state): + cand_id = None + for c in (state.get('candidates') or []): + if (c.get('email') or '').lower() == NINA_EMAIL: + cand_id = c.get('id') + break + for a in (state.get('applications') or []): + if a.get('candidateId') == cand_id: + return a, cand_id + return None, cand_id + + init_app, _ = find_app(init) + cur_app, cand_id = find_app(cur) + init_app = init_app or {} + cur_app = cur_app or {} + init_stage = init_app.get('currentStageId') + cur_stage = cur_app.get('currentStageId') + + # Component 1: moved INTO Hiring Manager Interview (0.30) + moved = (cur_stage in hm_stage_ids) and (init_stage not in hm_stage_ids) + if moved: + print(f'PASS: C1 — Nina moved into Hiring Manager Interview (init={init_stage} ' + f'cur={cur_stage}) (0.30)') + score += 0.30 + else: + print(f'FAIL: C1 — stage move. hm_stage_ids={hm_stage_ids} ' + f'init={init_stage} cur={cur_stage}') + + # Component 2: NEW scorecard OR note for Nina mentioning 6 years + communication (0.30) + app_id = cur_app.get('id') + # New scorecards (by id) tied to Nina's application. + init_sc_ids = {s.get('id') for s in (init.get('scorecards') or [])} + new_scorecards = [s for s in (cur.get('scorecards') or []) + if s.get('id') not in init_sc_ids and s.get('applicationId') == app_id] + # New notes (by id) tied to Nina's candidate. + init_note_ids = {n.get('id') for n in (init.get('notes') or [])} + new_notes = [n for n in (cur.get('notes') or []) + if n.get('id') not in init_note_ids and n.get('candidateId') == cand_id] + + def scorecard_text(sc): + parts = [str(sc.get('notes') or '')] + for a in (sc.get('attributes') or []): + parts.append(str(a.get('name') or '')) + parts.append(str(a.get('note') or '')) + return ' '.join(parts) + + texts = [scorecard_text(s) for s in new_scorecards] + \ + [str(n.get('body') or '') for n in new_notes] + note_ok = any(mentions_six_years(t) and ('communicat' in t.lower()) for t in texts) + if note_ok: + print('PASS: C2 — new scorecard/note mentions 6 years experience + communication (0.30)') + score += 0.30 + else: + print(f'FAIL: C2 — no new scorecard/note with both 6-years and communication ' + f'(new scorecards={len(new_scorecards)} new notes={len(new_notes)})') + return score + except Exception as e: + print(f'ERROR: Greenhouse component — {e}') + return score + + +def verify_gmail(sid): + """Component 3 (0.20): NEW sent email to Nina about the hiring-manager interview.""" + init, cur = fetch(GMAIL_URL, sid) + if cur is None: + print('FAIL: Gmail unreachable') + return 0.0 + try: + init_ids = {e.get('id') for e in (init.get('emails') or [])} + for e in (cur.get('emails') or []): + if e.get('folder') != 'sent' or e.get('id') in init_ids: + continue + tos = [str(t.get('email') or '').lower() for t in (e.get('to') or [])] + if NINA_EMAIL not in tos: + continue + text = (strip_html(e.get('body')) + ' ' + (e.get('subject') or '')).lower() + # Next step is a hiring-manager interview. + if 'interview' in text and ('hiring manager' in text or 'hiring-manager' in text + or 'next step' in text): + print('PASS: C3 — new sent email to Nina about hiring-manager interview (0.20)') + return 0.20 + print('FAIL: C3 — no new sent email to Nina referencing the hiring-manager interview') + return 0.0 + except Exception as e: + print(f'ERROR: Gmail component — {e}') + return 0.0 + + +def verify_slack(sid): + """Component 4 (0.20): NEW #hiring message tagging Greg to review Nina.""" + init, cur = fetch(SLACK_URL, sid) + if cur is None: + print('FAIL: Slack unreachable') + return 0.0 + try: + init_ids = {m.get('messageId') for m in (init.get('messages') or {}).get('hiring', [])} + new_msgs = [m for m in (cur.get('messages') or {}).get('hiring', []) + if m.get('messageId') not in init_ids] + for m in new_msgs: + low = (m.get('content') or '').lower() + tags_greg = bool(re.search(r'@?\bgreg\b', low)) + asks_review = ('review' in low or 'take a look' in low or 'look at' in low) + mentions_nina = 'nina' in low + if tags_greg and asks_review and mentions_nina: + print('PASS: C4 — new #hiring msg tags Greg to review Nina (0.20)') + return 0.20 + print(f'FAIL: C4 — no new #hiring message tagging Greg to review Nina ' + f'({len(new_msgs)} new msgs)') + return 0.0 + except Exception as e: + print(f'ERROR: Slack component — {e}') + return 0.0 + + +def main(): + sid = read_sid() + if not sid: + print('REWARD: 0.0') + return + total = 0.0 + total += verify_greenhouse(sid) + total += verify_gmail(sid) + total += verify_slack(sid) + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + + +main() diff --git a/recruit_screen_002/reward_label.json b/recruit_screen_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..41ba5c3617b7ed303645b8024f934a0a14d003cc --- /dev/null +++ b/recruit_screen_002/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/recruit_screen_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:32:40", + "label": { + "task_id": "recruit_screen_002", + "domain": "mock_websites", + "summary": "验证是否将候选人Nina Patel推进到Hiring Manager Interview阶段,并在Greenhouse添加包含6年经验和沟通能力的评分卡/备注,同时通过Gmail发送面试通知邮件,以及在Slack #hiring频道@Greg请求审核Nina资料", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "greenhouse_mock (http://28.7.186.212:8166)", + "gmail_mock (http://28.7.186.212:8158)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Component 1 — GREENHOUSE stage", + "weight": 0.3, + "description": "Nina的申请从初始阶段移动到了'Hiring Manager Interview'阶段", + "check_logic": "通过fetch获取Greenhouse的initial_state和current_state,在jobStages中查找name为'hiring manager interview'的stage ID集合hm_stage_ids;在candidates中匹配email为nina.patel@gmail.com的候选人,再查找其application;比较init_app.currentStageId和cur_app.currentStageId,判断cur_stage是否在hm_stage_ids中且init_stage不在其中", + "pass_condition": "cur_stage属于hiring manager interview阶段,且init_stage不属于该阶段" + }, + { + "name": "Component 2 — GREENHOUSE scorecard note", + "weight": 0.3, + "description": "为Nina新增了scorecard或note,且文本同时提及'6 years'相关经验和communication", + "check_logic": "筛选出id不在initial_state中的新scorecards(匹配applicationId)和新notes(匹配candidateId);将scorecard的notes、attributes.name、attributes.note拼接,note取body;检查所有文本是否满足mentions_six_years()(正则\\b(6|six)\\s*\\+?\\s*(years|yrs)\\b)且包含'communicat'子串", + "pass_condition": "存在至少一条新的scorecard或note,其文本同时匹配6年经验正则且包含communicat" + }, + { + "name": "Component 3 — GMAIL", + "weight": 0.2, + "description": "新增发送给Nina的邮件,提及hiring-manager interview作为下一步", + "check_logic": "获取Gmail的initial和current状态,筛选folder为'sent'且id不在init_ids中的新邮件;检查收件人to列表包含nina.patel@gmail.com;将邮件body去除HTML后与subject拼接转小写,判断是否包含'interview'且包含'hiring manager'或'hiring-manager'或'next step'", + "pass_condition": "存在一封新的已发送邮件,收件人为Nina,且主题/正文中同时包含interview和hiring manager/next step相关表述" + }, + { + "name": "Component 4 — SLACK", + "weight": 0.2, + "description": "在#hiring频道新增消息@Greg请求review Nina的资料", + "check_logic": "获取Slack的messages.hiring频道,筛选messageId不在init_ids中的新消息;检查content是否同时满足:正则@?\\bgreg\\b匹配(tag Greg)、包含'review'/'take a look'/'look at'(请求审核)、包含'nina'", + "pass_condition": "存在一条新的#hiring频道消息,内容中@Greg、请求review/take a look/look at、且提到Nina" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终结果通过min(total, 1.0)钳制到上限1.0,再round(..., 4)保留四位小数", + "failure_modes": [ + "读取/tmp/task_web_sid失败或为空时,脚本提前退出,输出REWARD: 0.0", + "Greenhouse/Gmail/Slack任一服务fetch失败或返回None时,对应组件得0.0", + "Greenhouse中未找到Nina的application或candidate时,组件1和2判定失败", + "Gmail中没有符合条件的新sent邮件时,组件3得0.0", + "Slack #hiring频道没有符合条件的新消息时,组件4得0.0", + "各组件内部发生异常时,该组件返回已得分数或0.0" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID。然后依次执行三个验证函数:1) verify_greenhouse同时检查组件1(阶段移动)和组件2(评分卡/备注内容),通过比较initial_state与current_state的delta来检测变更,每项通过分别加0.3分;2) verify_gmail检查是否有新的已发送邮件给Nina并提及hiring manager interview,通过加0.2分;3) verify_slack检查#hiring频道是否有新消息@Greg并请求review Nina,通过加0.2分。所有组件分数累加后,用min(total, 1.0)确保不超过满分1.0,最后四舍五入到4位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读源码:\n\n1. **任务信息提取**:\n - Task ID: recruit_screen_002\n - Domain: mock_websites (greenhouse + gmail + slack)\n - 这是一个完全确定性的基于规则的评分脚本,没有 LLM 评判。\n\n2. **数据源**:\n - GREENHOUSE_URL = 'http://28.7.186.212:8166'\n - GMAIL_URL = 'http://28.7.186.212:8158'\n - SLACK_URL = 'http://28.7.186.212:8198'\n - 从 /tmp/task_web_sid 读取 sid\n\n3. **评分组件**:\n - Component 1: GREENHOUSE stage (0.30) - Nina 的申请移动到 'Hiring Manager Interview' 阶段\n - Component 2: GREENHOUSE scorecard note (0.30) - 新增 scorecard 或 note,文本同时提到 '6 years' 和 communication\n - Component 3: GMAIL (0.20) - 新增发送给 nina.patel@gmail.com 的邮件,提到 hiring-manager interview 作为下一步\n - Component 4: SLACK (0.20) - 新增 #hiring 消息,@Greg 并要求 review Nina 的 profile\n\n4. **评分逻辑**:\n - 读取 sid\n - 分别调用 verify_greenhouse, verify_gmail, verify_slack\n - 分数相加\n - final = round(min(total, 1.0), 4)\n - 如果 sid 读取失败,直接返回\n\n5. **各组件详细逻辑**:\n\n **verify_greenhouse**:\n - 获取 initial_state 和 current_state\n - 查找 jobStages 中 name 为 'hiring manager interview' 的 stage id\n - 在 candidates 中找 email 为 nina.patel@gmail.com 的 candidate\n - 在 applications 中找 candidateId 匹配的 application\n - C1: cur_stage 在 hm_stage_ids 中且 init_stage 不在其中 → +0.30\n - C2: \n - 找新的 scorecards(id 不在 init 中,且 applicationId 匹配)\n - 找新的 notes(id 不在 init 中,且 candidateId 匹配)\n - scorecard_text 组合 notes, attributes 的 name 和 note\n - 检查是否有任何文本 mentions_six_years (正则 \\b(6|six)\\s*\\+?\\s*(years|yrs)\\b) 且包含 'communicat'\n - 通过 → +0.30\n\n **verify_gmail**:\n - 获取 initial 和 current emails\n - 找新邮件(id 不在 init 中)\n - folder 为 'sent'\n - to 包含 nina.patel@gmail.com\n - body (去除 html) + subject 中包含 'interview' 且 ('hiring manager' 或 'hiring-manager' 或 'next step')\n - 通过 → +0.20\n\n **verify_slack**:\n - 获取 messages.hiring 频道\n - 找新消息(messageId 不在 init 中)\n - content 中:\n - tags_greg: 正则 @?\\bgreg\\b\n - asks_review: 'review' 或 'take a look' 或 'look at'\n - mentions_nina: 'nina'\n - 全部满足 → +0.20\n\n6. **失败模式**:\n - sid 读取失败 → 提前退出,输出 REWARD: 0.0\n - Greenhouse 不可达 → C1+C2 得 0\n - Gmail 不可达 → C3 得 0\n - Slack 不可达 → C4 得 0\n - 各组件内部异常 → 该组件得 0(或部分得分)\n - 未满足条件 → 该组件不得分\n\n7. **is_placeholder**: false,因为这是一个完整的评分脚本。\n\n8. **score_aggregation**: 各组件分数相加,然后 min(total, 1.0),再 round(..., 4)。\n\n9. **confidence**: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"recruit_screen_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否将候选人Nina Patel推进到Hiring Manager Interview阶段,并在Greenhouse添加包含6年经验和沟通能力的评分卡/备注,同时通过Gmail发送面试通知邮件,以及在Slack #hiring频道@Greg请求审核Nina资料。\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"greenhouse_mock (http://28.7.186.212:8166)\",\n \"gmail_mock (http://28.7.186.212:8158)\",\n \"slack_mock (http://28.7.186.212:8198)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 — GREENHOUSE stage\",\n \"weight\": 0.3,\n \"description\": \"Nina的申请从初始阶段移动到了'Hiring Manager Interview'阶段\",\n \"check_logic\": \"通过fetch获取Greenhouse的initial_state和current_state,在jobStages中查找name为'hiring manager interview'的stage ID;在candidates中匹配email为nina.patel@gmail.com的候选人,再查找其application;比较init_app.currentStageId和cur_app.currentStageId,判断cur_stage是否在hm_stage_ids中且init_stage不在其中\",\n \"pass_condition\": \"cur_stage属于hiring manager interview阶段,且init_stage不属于该阶段\"\n },\n {\n \"name\": \"Component 2 — GREENHOUSE scorecard note\",\n \"weight\": 0.3,\n \"description\": \"为Nina新增了scorecard或note,且文本同时提及'6 years'相关经验和communication\",\n \"check_logic\": \"筛选出id不在initial_state中的新scorecards(匹配applicationId)和新notes(匹配candidateId);将scorecard的notes、attributes.name、attributes.note拼接,note取body;检查所有文本是否满足mentions_six_years()(正则\\\\b(6|six)\\\\s*\\\\+?\\\\s*(years|yrs)\\\\b)且包含'communicat'子串\",\n \"pass_condition\": \"存在至少一条新的scorecard或note,其文本同时匹配6年经验正则且包含communicat\"\n },\n {\n \"name\": \"Component 3 — GMAIL\",\n \"weight\": 0.2,\n \"description\": \"新增发送给Nina的邮件,提及hiring-manager interview作为下一步\",\n \"check_logic\": \"获取Gmail的initial和current状态,筛选folder为'sent'且id不在init_ids中的新邮件;检查收件人to列表包含nina.patel@gmail.com;将邮件body去除HTML后与subject拼接转小写,判断是否包含'interview'且包含'hiring manager'或'hiring-manager'或'next step'\",\n \"pass_condition\": \"存在一封新的已发送邮件,收件人为Nina,且主题/正文中同时包含interview和hiring manager/next step相关表述\"\n },\n {\n \"name\": \"Component 4 — SLACK\",\n \"weight\": 0.2,\n \"description\": \"在#hiring频道新增消息@Greg请求review Nina的资料\",\n \"check_logic\": \"获取Slack的messages.hiring频道,筛选messageId不在init_ids中的新消息;检查content是否同时满足:正则@?\\\\bgreg\\\\b匹配(tag Greg)、包含'review'/'take a look'/'look at'(请求审核)、包含'nina'\",\n \"pass_condition\": \"存在一条新的#hiring频道消息,内容中@Greg、请求review/take a look/look at、且提到Nina\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终结果通过min(total, 1.0)钳制到上限1.0,再round(..., 4)保留四位小数\",\n \"failure_modes\": [\n \"读取/tmp/task_web_sid失败或为空时,脚本提前退出,输出REWARD: 0.0\",\n \"Greenhouse/Gmail/Slack任一服务fetch失败或返回None时,对应组件得0.0\",\n \"Greenhouse中未找到Nina的application或candidate时,组件1和2判定失败\",\n \"Gmail中没有符合条件的新sent邮件时,组件3得0.0\",\n \"Slack #hiring频道没有符合条件的新消息时,组件4得0.0\",\n \"各组件内部发生异常时,该组件返回已得分数或0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID。然后依次执行三个验证函数:1) verify_greenhouse同时检查组件1(阶段移动)和组件2(评分卡/备注内容),通过比较initial_state与current_state的delta来检测变更,每项通过分别加0.3分;2) verify_gmail检查是否有新的已发送邮件给Nina并提及hiring manager interview,通过加0.2分;3) verify_slack检查#hiring频道是否有新消息@Greg并请求review Nina,通过加0.2分。所有组件分数累加后,用min(total, 1.0)确保不超过满分1.0,最后四舍五入到4位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 thinking 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n确认 JSON 格式正确,没有多余内容。 {\n \"task_id\": \"recruit_screen_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否将候选人Nina Patel推进到Hiring Manager Interview阶段,并在Greenhouse添加包含6年经验和沟通能力的评分卡/备注,同时通过Gmail发送面试通知邮件,以及在Slack #hiring频道@Greg请求审核Nina资料\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"greenhouse_mock (http://28.7.186.212:8166)\",\n \"gmail_mock (http://28.7.186.212:8158)\",\n \"slack_mock (http://28.7.186.212:8198)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 — GREENHOUSE stage\",\n \"weight\": 0.3,\n \"description\": \"Nina的申请从初始阶段移动到了'Hiring Manager Interview'阶段\",\n \"check_logic\": \"通过fetch获取Greenhouse的initial_state和current_state,在jobStages中查找name为'hiring manager interview'的stage ID集合hm_stage_ids;在candidates中匹配email为nina.patel@gmail.com的候选人,再查找其application;比较init_app.currentStageId和cur_app.currentStageId,判断cur_stage是否在hm_stage_ids中且init_stage不在其中\",\n \"pass_condition\": \"cur_stage属于hiring manager interview阶段,且init_stage不属于该阶段\"\n },\n {\n \"name\": \"Component 2 — GREENHOUSE scorecard note\",\n \"weight\": 0.3,\n \"description\": \"为Nina新增了scorecard或note,且文本同时提及'6 years'相关经验和communication\",\n \"check_logic\": \"筛选出id不在initial_state中的新scorecards(匹配applicationId)和新notes(匹配candidateId);将scorecard的notes、attributes.name、attributes.note拼接,note取body;检查所有文本是否满足mentions_six_years()(正则\\\\b(6|six)\\\\s*\\\\+?\\\\s*(years|yrs)\\\\b)且包含'communicat'子串\",\n \"pass_condition\": \"存在至少一条新的scorecard或note,其文本同时匹配6年经验正则且包含communicat\"\n },\n {\n \"name\": \"Component 3 — GMAIL\",\n \"weight\": 0.2,\n \"description\": \"新增发送给Nina的邮件,提及hiring-manager interview作为下一步\",\n \"check_logic\": \"获取Gmail的initial和current状态,筛选folder为'sent'且id不在init_ids中的新邮件;检查收件人to列表包含nina.patel@gmail.com;将邮件body去除HTML后与subject拼接转小写,判断是否包含'interview'且包含'hiring manager'或'hiring-manager'或'next step'\",\n \"pass_condition\": \"存在一封新的已发送邮件,收件人为Nina,且主题/正文中同时包含interview和hiring manager/next step相关表述\"\n },\n {\n \"name\": \"Component 4 — SLACK\",\n \"weight\": 0.2,\n \"description\": \"在#hiring频道新增消息@Greg请求review Nina的资料\",\n \"check_logic\": \"获取Slack的messages.hiring频道,筛选messageId不在init_ids中的新消息;检查content是否同时满足:正则@?\\\\bgreg\\\\b匹配(tag Greg)、包含'review'/'take a look'/'look at'(请求审核)、包含'nina'\",\n \"pass_condition\": \"存在一条新的#hiring频道消息,内容中@Greg、请求review/take a look/look at、且提到Nina\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终结果通过min(total, 1.0)钳制到上限1.0,再round(..., 4)保留四位小数\",\n \"failure_modes\": [\n \"读取/tmp/task_web_sid失败或为空时,脚本提前退出,输出REWARD: 0.0\",\n \"Greenhouse/Gmail/Slack任一服务fetch失败或返回None时,对应组件得0.0\",\n \"Greenhouse中未找到Nina的application或candidate时,组件1和2判定失败\",\n \"Gmail中没有符合条件的新sent邮件时,组件3得0.0\",\n \"Slack #hiring频道没有符合条件的新消息时,组件4得0.0\",\n \"各组件内部发生异常时,该组件返回已得分数或0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID。然后依次执行三个验证函数:1) verify_greenhouse同时检查组件1(阶段移动)和组件2(评分卡/备注内容),通过比较initial_state与current_state的delta来检测变更,每项通过分别加0.3分;2) verify_gmail检查是否有新的已发送邮件给Nina并提及hiring manager interview,通过加0.2分;3) verify_slack检查#hiring频道是否有新消息@Greg并请求review Nina,通过加0.2分。所有组件分数累加后,用min(total, 1.0)确保不超过满分1.0,最后四舍五入到4位小数输出。\",\n \"confidence\": 1.0\n}" +}