diff --git a/ae_contract_signature_001/_cua_gym_vm_bridge.sh b/ae_contract_signature_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ae_contract_signature_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/ae_contract_signature_001/initial_setup.py b/ae_contract_signature_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..181b6a1c17d19367bd2ac2bf19df0a9941d04612 --- /dev/null +++ b/ae_contract_signature_001/initial_setup.py @@ -0,0 +1,609 @@ +# --- 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: Get the Globex Platform Expansion order form out for signature. +Task ID: ae_contract_signature_001 +Domain: mock_websites (multi-mock) +Mocks: salesforce, notion, docusign, slack + +Persona: Alex Rivera (user-1), Account Executive at Northwind Cloud + (alex.rivera@northwindcloud.com). Today = 2026-06-24. + +The deal to process: + opp-1 'Globex - Platform Expansion' | Globex Corporation | Maria Gomez + (VP of Operations, maria.gomez@globex.com) | $120,000 | Closed Won. + +Pre-task state ONLY. MUST NOT contain task-completed elements: + - DocuSign: NO envelope for the Globex Platform Expansion order form. + - Notion 'Contracts' database: NO row for Globex Platform Expansion. + - Salesforce: NO activity on opp-1 recording the order form / DocuSign + envelope being sent. + - Slack #deal-desk: NO message about Globex awaiting signature. + +Distractors that MUST exist and stay untouched by the golden state: + - Salesforce opp-2 (Initech - Annual Renewal, Negotiation, NOT won). + - Salesforce opp-6 (Globex - SMB Add-on, Closed Lost). + - DocuSign address-book contacts Michael Torres, Daniel Park (NOT signers). +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Mock registry --- +MOCKS = { + 'salesforce': 'http://28.7.184.198:8175', + 'notion': 'http://28.7.184.198:8166', + 'docusign': 'http://28.7.184.198:8130', + 'slack': 'http://28.7.184.198:8178', +} + +# --- Shared session id --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid = {sid}') + + +# ---------------------------------------------------------------------------- +# Salesforce state +# opp-1 Globex Platform Expansion Closed Won <- the deal to process +# opp-2 Initech Annual Renewal Negotiation (distractor, not won) +# opp-6 Globex SMB Add-on Closed Lost (distractor, lost) +# NO activity on opp-1 about the order form / DocuSign envelope. +# ---------------------------------------------------------------------------- +def salesforce_state(): + user_1 = { + "userId": "user-1", "firstName": "Alex", "lastName": "Rivera", + "email": "alex.rivera@northwindcloud.com", "phone": "(555) 240-1188", + "title": "Account Executive", "department": "Sales", "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/Los_Angeles", "locale": "en-US", + "theme": "lightning", + } + user_2 = { + "userId": "user-2", "firstName": "Sam", "lastName": "Lee", + "email": "sam.lee@northwindcloud.com", "phone": "(555) 240-1190", + "title": "Sales Manager", "department": "Sales", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/Los_Angeles", "locale": "en-US", + "theme": "lightning", + } + + accounts = [ + {"accountId": "account-1", "name": "Globex Corporation", + "type": "Customer", "industry": "Technology", "revenue": 480000000, + "employees": 5200, "ownerId": "user-1", + "billingStreet": "500 Innovation Way", "billingCity": "San Jose", + "billingState": "CA", "billingZip": "95110", "billingCountry": "USA"}, + {"accountId": "account-2", "name": "Initech LLC", "type": "Customer", + "industry": "Software", "revenue": 22000000, "employees": 320, + "ownerId": "user-1", "billingStreet": "78 Office Park Dr", + "billingCity": "Austin", "billingState": "TX", + "billingZip": "73301", "billingCountry": "USA"}, + ] + + contacts = [ + {"contactId": "contact-1", "accountId": "account-1", + "firstName": "Maria", "lastName": "Gomez", "title": "VP of Operations", + "department": "Operations", "email": "maria.gomez@globex.com", + "phone": "(555) 101-2201", "ownerId": "user-1"}, + {"contactId": "contact-2", "accountId": "account-2", + "firstName": "Daniel", "lastName": "Park", "title": "CTO", + "department": "Engineering", "email": "daniel.park@initech.com", + "phone": "(555) 330-2201", "ownerId": "user-1"}, + ] + + opportunities = [ + {"opportunityId": "opp-1", "name": "Globex - Platform Expansion", + "accountId": "account-1", "contactId": "contact-1", "amount": 120000, + "closeDate": "2026-06-20", "stage": "Closed Won", "probability": 100, + "ownerId": "user-1"}, + {"opportunityId": "opp-2", "name": "Initech - Annual Renewal", + "accountId": "account-2", "contactId": "contact-2", "amount": 60000, + "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 60, + "ownerId": "user-1"}, + {"opportunityId": "opp-6", "name": "Globex - SMB Add-on", + "accountId": "account-1", "contactId": "contact-1", "amount": 9000, + "closeDate": "2026-05-30", "stage": "Closed Lost", "probability": 0, + "ownerId": "user-1"}, + ] + + # An unrelated pre-existing activity on opp-1 (a closed-won celebration + # note). It is NOT about the order form / DocuSign envelope being sent, + # so it must not satisfy the success checkpoint by itself. + activities = [ + {"activityId": "activity-1", "type": "task", + "subject": "Send thank-you note to Globex stakeholders", + "status": "Completed", "priority": "Normal", + "dueDate": "2026-06-20", + "relatedToType": "opportunity", "relatedToId": "opp-1", + "assignedToId": "user-1", + "description": "Closed-won celebration outreach to the Globex team.", + "createdDate": "2026-06-20T17:00:00.000Z", + "modifiedDate": "2026-06-20T17:00:00.000Z"}, + ] + + return { + "user": user_1, + "users": [user_1, user_2], + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": activities, + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# ---------------------------------------------------------------------------- +# Notion state +# workspace 'Northwind Sales' with a 'Contracts' database (table view). +# Properties: Customer (text), Deal (text), Amount (number), +# Status (select: Draft/Sent/Completed). +# Has ONE unrelated existing row (Acme Tooling) but NO Globex Platform +# Expansion row. +# ---------------------------------------------------------------------------- +def notion_state(): + user = {"id": "user-1", "name": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com", "avatar": ""} + workspace = {"id": "ws-1", "name": "Northwind Sales", "icon": "\U0001F3E2", + "members": ["user-1"]} + + db_id = "db-contracts" + properties = [ + {"id": "prop_customer", "name": "Customer", "type": "text"}, + {"id": "prop_deal", "name": "Deal", "type": "text"}, + {"id": "prop_amount", "name": "Amount", "type": "number"}, + {"id": "prop_status", "name": "Status", "type": "select", + "options": ["Draft", "Sent", "Completed"]}, + ] + + # One unrelated existing row so the tracker isn't empty (distractor data). + existing_row = { + "id": "row-acme", + "title": "Acme Tooling", + "icon": "", "cover": None, "parentId": db_id, + "blockIds": [], "favorite": False, + "createdDate": "2026-05-12T09:00:00.000Z", + "lastEditedDate": "2026-05-12T09:00:00.000Z", + "properties": { + "prop_customer": "Acme Tooling", + "prop_deal": "Acme - Starter Bundle", + "prop_amount": 30000, + "prop_status": "Completed", + }, + } + + contracts_db = { + "id": db_id, + "title": "Contracts", + "icon": "\U0001F4DD", "cover": None, "parentId": None, + "type": "database", "viewType": "table", + "properties": properties, + "views": [{ + "id": "view-contracts", "name": "Table", "type": "table", + "filters": [], "sorts": [], "groupBy": None, + "visibleProperties": ["prop_customer", "prop_deal", + "prop_amount", "prop_status"], + }], + "items": ["row-acme"], + "blockIds": [], "favorite": False, + "createdDate": "2026-05-01T09:00:00.000Z", + } + + return { + "user": user, + "workspace": workspace, + "pages": {db_id: contracts_db, "row-acme": existing_row}, + "blocks": {}, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, + "fontSize": "default"}, + "notifications": [], + "pageOrder": [db_id], + } + + +# ---------------------------------------------------------------------------- +# DocuSign state +# user Alex Rivera. An 'Order Form' template + address-book contact for +# Maria Gomez. Distractor contacts (Michael Torres, Daniel Park) present. +# NO envelope for the Globex order form. +# ---------------------------------------------------------------------------- +def docusign_state(): + user = { + "id": "user-1", "name": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com", + "title": "Account Executive", "company": "Northwind Cloud", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "memberSince": "2024-01-15T00:00:00Z", + "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120, + "timezone": "America/Los_Angeles"}, + } + + # One unrelated, already-completed envelope as a distractor — nothing to + # do with the Globex Platform Expansion order form. + distractor_env = { + "id": "env_initech_old", + "subject": "Initech - NDA", + "message": "Please review and sign the mutual NDA.", + "status": "completed", + "createdAt": "2026-04-10T09:00:00Z", + "sentAt": "2026-04-10T09:30:00Z", + "completedAt": "2026-04-12T14:00:00Z", + "voidedAt": None, "declinedAt": None, + "lastActivityAt": "2026-04-12T14:00:00Z", "expiresAt": None, + "senderId": "user-1", "folderId": None, "templateId": None, + "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2, + "documents": [{"id": "doc_initech_nda", "name": "Initech_NDA.pdf", + "pageCount": 3, "order": 1, + "fileUrl": "https://picsum.photos/seed/initechnda/800/1100", + "fileType": "pdf"}], + "recipients": [{"id": "rec_initech_nda", "name": "Daniel Park", + "email": "daniel.park@initech.com", "role": "signer", + "routingOrder": 1, "status": "signed", + "signedAt": "2026-04-12T14:00:00Z", + "viewedAt": "2026-04-11T10:00:00Z", + "deliveredAt": "2026-04-10T09:31:00Z", + "declinedAt": None, "declineReason": None}], + "fields": [], + "history": [ + {"id": "evt_initech_nda_1", "timestamp": "2026-04-10T09:00:00Z", + "action": "created", "actorName": "Alex Rivera", + "actorEmail": "alex.rivera@northwindcloud.com", + "details": "Envelope created"}, + {"id": "evt_initech_nda_2", "timestamp": "2026-04-12T14:00:00Z", + "action": "completed", "actorName": "Daniel Park", + "actorEmail": "daniel.park@initech.com", + "details": "All recipients signed"}, + ], + } + + return { + "user": user, + "envelopes": [distractor_env], + "templates": [ + {"id": "tmpl_order_form", "name": "Order Form", + "description": "Standard Northwind Cloud order form template.", + "createdAt": "2025-01-10T09:00:00Z", + "lastUsedAt": "2026-05-01T10:00:00Z", + "usageCount": 22, "ownerId": "user-1", "shared": True, + "documents": [{"id": "tdoc_order_form_1", "name": "Order_Form.pdf", + "pageCount": 4, "order": 1, + "fileUrl": "https://picsum.photos/seed/orderform/800/1100", + "fileType": "pdf"}], + "roles": [{"id": "trole_signer", "name": "Customer Signer", + "role": "signer", "routingOrder": 1}], + "fields": []}, + ], + "folders": [], + "contacts": [ + {"id": "con_maria", "name": "Maria Gomez", + "email": "maria.gomez@globex.com", + "company": "Globex Corporation", "title": "VP of Operations"}, + {"id": "con_michael", "name": "Michael Torres", + "email": "michael.torres@example.com", + "company": "Stark Holdings", "title": "Procurement Lead"}, + {"id": "con_daniel", "name": "Daniel Park", + "email": "daniel.park@initech.com", + "company": "Initech LLC", "title": "CTO"}, + ], + "auditLog": [ + {"id": "audit_initech_nda", "timestamp": "2026-04-12T14:00:00Z", + "action": "COMPLETE_ENVELOPE", + "details": "Initech - NDA completed", + "envelopeId": "env_initech_old"}, + ], + } + + +# ---------------------------------------------------------------------------- +# Slack state — workspace 'Northwind Cloud', currentUser Alex Rivera (user_1), +# channel '#deal-desk' exists with prior chatter but NO awaiting-signature +# message for Globex. +# ---------------------------------------------------------------------------- +def slack_state(): + user_1 = {"userId": "user_1", "fullName": "Alex Rivera", + "displayName": "Alex", "email": "alex.rivera@northwindcloud.com", + "avatar": "https://picsum.photos/200/200?random=1", + "status": "online", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/Los_Angeles", "title": "Account Executive"} + user_2 = {"userId": "user_2", "fullName": "Sam Lee", + "displayName": "Sam", "email": "sam.lee@northwindcloud.com", + "avatar": "https://picsum.photos/200/200?random=2", + "status": "online", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/Los_Angeles", "title": "Sales Manager"} + + deal_desk = { + "channelId": "deal-desk", "name": "deal-desk", + "description": "Deal desk coordination", + "topic": "Contracts, order forms & signatures", + "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2"], "createdBy": "user_2", + "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], + "unreadCount": 0} + + return { + "currentUser": user_1, + "workspace": {"workspaceId": "ws_1", + "workspaceName": "Northwind Cloud", "icon": ""}, + "users": [user_1, user_2], + "channels": [deal_desk], + "messages": { + "deal-desk": [ + {"messageId": "msg_1", "senderId": "user_2", + "content": "Reminder: log every order form you send out here " + "so finance can track signatures.", + "timestamp": "2026-06-24T08:05: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 all states +# ---------------------------------------------------------------------------- +STATE_BUILDERS = { + 'salesforce': salesforce_state, + 'notion': notion_state, + 'docusign': docusign_state, + 'slack': slack_state, +} + +for name, build in STATE_BUILDERS.items(): + url = MOCKS[name] + state = build() + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, \ + f'{name} injection failed: {resp.status_code} {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' injected {name}: initial_state OK') + +print(f'All 4 mocks injected with sid={sid}') + + +# ---------------------------------------------------------------------------- +# GUI-ready: launch Chrome on Salesforce (where the task starts) +# ---------------------------------------------------------------------------- +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 +_primary_mock_url = MOCKS["salesforce"] +launch_gui(f'google-chrome "{MOCKS["salesforce"]}/?sid={sid}"', delay_sec=2.0) +_open_remaining_mock_tabs(_primary_mock_url) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {MOCKS["salesforce"]}/?sid={sid}') diff --git a/ae_contract_signature_001/reward.py b/ae_contract_signature_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa08aafd234ede723de8fb5c2c9db78c6bee784 --- /dev/null +++ b/ae_contract_signature_001/reward.py @@ -0,0 +1,467 @@ +# --- 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: Globex Platform Expansion order form — close-won contract signature flow +Task ID: ae_contract_signature_001 +Domain: mock_websites (multi-mock: docusign, notion, salesforce, slack) + +Scoring (1.0 total) — every component verifies a NEW artifact present in current_state +but ABSENT from initial_state (so it is the task-introduced change, not a precondition): + + Component 1 — DocuSign envelope (0.35) + - a NEW envelope referencing the Globex Platform Expansion order form (0.10) + - status == 'sent' AND sentAt populated (0.10) + - exactly one signer recipient named 'Maria Gomez' / maria.gomez@globex.com (0.15) + Component 2 — Notion 'Contracts' row (0.25) + - NEW db row: Customer 'Globex Corporation', Deal ~ 'Platform Expansion', + Amount 120000, Status 'Sent' + Component 3 — Salesforce activity on opp-1 (0.20) + - NEW activity related to opp-1 referencing order form/DocuSign + sent, + AND opp-1 stage still 'Closed Won' + Component 4 — Slack #deal-desk message (0.20) + - NEW message mentioning Globex, amount 120000 ($120,000), awaiting signature + +Verification is fully deterministic (structured mock state). No LLM judge used. +""" +import os +import re +import unicodedata +from datetime import datetime + +import requests + +# Which state to score. Default 'current_state' (post-task / agent result). +# Override to 'initial_state' only for discriminator self-testing of the 0.0 baseline. +STATE_TO_SCORE = os.environ.get('REWARD_STATE_KEY', 'current_state') + +MOCKS = { + 'docusign': 'http://28.7.184.198:8130', + 'notion': 'http://28.7.184.198:8166', + 'salesforce': 'http://28.7.184.198:8175', + 'slack': 'http://28.7.184.198:8178', +} + + +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 /tmp/task_web_sid: {e}') + return None + + +def fetch_all(sid): + """Fetch /go from every mock. Returns {name: {initial, current}} or None on failure.""" + out = {} + for name, base in MOCKS.items(): + try: + data = requests.get(f'{base}/go?sid={sid}', timeout=15).json() + except Exception as e: + print(f'CRITICAL: cannot fetch {name} state: {e}') + return None + out[name] = { + 'initial': data.get('initial_state') or {}, + 'current': data.get('current_state') or {}, + } + return out + + +def pick(states, name): + """Return (scored_state, initial_state) for a mock per STATE_TO_SCORE.""" + s = states[name] + return s.get(STATE_TO_SCORE.replace('_state', '')), s['initial'] + + +# --------------------------------------------------------------------------- +# Component checks. Each returns (points_awarded, max_points). +# Each is anchored to artifacts NEW in scored-state vs initial_state. +# --------------------------------------------------------------------------- + +def _norm_words(value): + """Lowercase text and collapse punctuation/spacing for tolerant matching.""" + if value is None: + return '' + text = unicodedata.normalize('NFKC', str(value)).lower() + text = re.sub(r'[^a-z0-9]+', ' ', text) + return re.sub(r'\s+', ' ', text).strip() + + +def _has_all(value, terms): + text = _norm_words(value) + return all(_norm_words(term) in text for term in terms) + + +def _has_any(value, terms): + text = _norm_words(value) + return any(_norm_words(term) in text for term in terms) + + +def _email(value): + return re.sub(r'\s+', '', str(value or '')).lower() + + +def _name_matches(value, first, last): + tokens = set(_norm_words(value).split()) + return first.lower() in tokens and last.lower() in tokens + + +def _parse_datetime(value): + if not value: + return None + text = str(value).strip() + try: + return datetime.fromisoformat(text.replace('Z', '+00:00')) + except Exception: + pass + for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d'): + try: + return datetime.strptime(text[:19], fmt) + except Exception: + continue + return None + + +def _amount_matches(value, expected): + if isinstance(value, (int, float)): + return abs(float(value) - expected) < 0.01 + text = str(value or '').lower().strip() + if not text: + return False + cleaned = text.replace(',', '').replace('$', '') + compact = re.sub(r'\s+', '', cleaned) + candidates = re.findall(r'\d+(?:\.\d+)?\s*k|\d+(?:\.\d+)?', cleaned) + if re.search(r'(? (0.15)') + pts += 0.15 + else: + print(f'FAIL: C1c — signer mismatch: name="{r.get("name")}" ' + f'email="{r.get("email")}"') + else: + print(f'FAIL: C1c — expected exactly 1 signer, found {len(signers)}') + except Exception as e: + print(f'ERROR: C1 (docusign) — {e}') + return pts, 0.35 + + +def check_notion(scored, initial): + """Component 2 — new Contracts row for Globex Platform Expansion. (0.25)""" + max_pts = 0.25 + try: + ini_pages = initial.get('pages', {}) or {} + cur_pages = scored.get('pages', {}) or {} + + # Find the Contracts database (by title) in scored state. + db = None + for pid, p in cur_pages.items(): + if p.get('type') == 'database' and _norm_words(p.get('title')) == 'contracts': + db = p + break + if db is None: + print('FAIL: C2 — Contracts database not found') + return 0.0, max_pts + + db_id = db.get('id') + ini_items = set((ini_pages.get(db_id, {}) or {}).get('items', []) or []) + new_item_ids = [i for i in (db.get('items', []) or []) if i not in ini_items] + for pid, page in cur_pages.items(): + if pid not in ini_pages and page.get('parentId') == db_id and pid not in new_item_ids: + new_item_ids.append(pid) + if not new_item_ids: + print('FAIL: C2 — no NEW row added to Contracts database') + return 0.0, max_pts + + # Evaluate each new row; require ALL four fields correct for full credit. + prop_name_to_id = { + _norm_words(p.get('name')): p.get('id') + for p in (db.get('properties', []) or []) + if p.get('id') and p.get('name') + } + + def field_text(props, names, fallback_ids): + keys = list(fallback_ids) + keys.extend(prop_name_to_id.get(_norm_words(n)) for n in names) + for key in [k for k in keys if k]: + if key not in props: + continue + v = props.get(key, {}) + if isinstance(v, dict): + for value_key in ('title', 'text', 'select', 'status', + 'number', 'date'): + if v.get(value_key) not in (None, ''): + return v.get(value_key) + elif v not in (None, ''): + return v + return None + + best = None + for rid in new_item_ids: + row = cur_pages.get(rid, {}) or {} + props = row.get('properties', {}) or {} + customer = ( + field_text(props, ['Customer'], ['prop_customer']) + or row.get('title') + or '' + ) + deal = field_text(props, ['Deal'], ['prop_deal']) or '' + amount = field_text(props, ['Amount'], ['prop_amount']) + status = field_text(props, ['Status'], ['prop_status']) or '' + checks = { + 'customer': _has_any(customer, ['globex corporation', 'globex corp', 'globex']), + 'deal': _has_all(deal, ['platform', 'expansion']), + 'amount': _amount_matches(amount, 120000), + 'status': _norm_words(status) == 'sent', + } + score = sum(checks.values()) + if best is None or score > best[0]: + best = (score, checks, customer, deal, amount, status) + + score, checks, customer, deal, amount, status = best + if all(checks.values()): + print(f'PASS: C2 — new Contracts row Customer="{customer}" Deal="{deal}" ' + f'Amount={amount} Status="{status}" (0.25)') + return max_pts, max_pts + else: + print(f'FAIL: C2 — row field mismatch {checks} ' + f'(customer={customer}, deal={deal}, amount={amount}, status={status})') + return 0.0, max_pts + except Exception as e: + print(f'ERROR: C2 (notion) — {e}') + return 0.0, max_pts + + +def check_salesforce(scored, initial): + """Component 3 — new activity on opp-1 logging the sent order form; stage intact. (0.20)""" + max_pts = 0.20 + try: + ini_acts = initial.get('activities', []) or [] + cur_acts = scored.get('activities', []) or [] + ini_ids = {a.get('activityId') for a in ini_acts} + new_acts = [a for a in cur_acts if a.get('activityId') not in ini_ids] + + def target_opp(state): + for opp in (state.get('opportunities', []) or []): + name = opp.get('name', '') + if (_has_any(name, ['globex']) + and _has_all(name, ['platform', 'expansion']) + and _amount_matches(opp.get('amount'), 120000)): + return opp + return None + + opp1 = target_opp(scored) or next( + (o for o in (scored.get('opportunities', []) or []) + if o.get('opportunityId') == 'opp-1'), None) + opp_id = (opp1 or {}).get('opportunityId', 'opp-1') + + def relates_target_opp(a): + return a.get('relatedToId') == opp_id + + def logs_orderform_sent(a): + blob = ' '.join([ + str(a.get('subject', '')), + str(a.get('description', '')), + str(a.get('type', '')), + str(a.get('status', '')), + ]) + mentions_contract = _has_any(blob, [ + 'order form', 'orderform', 'docu sign', 'docusign', + 'envelope', 'signature packet', + ]) + return mentions_contract and _sent_for_signature(blob) + + matching = [ + a for a in new_acts + if relates_target_opp(a) and logs_orderform_sent(a) + ] + # Target opportunity must remain Closed Won. + stage_ok = opp1 is not None and _norm_words(opp1.get('stage')) == 'closed won' + + if matching and stage_ok: + print(f'PASS: C3 — new opp activity "{matching[0].get("subject")}" logged; ' + f'stage still Closed Won (0.20)') + return max_pts, max_pts + else: + print(f'FAIL: C3 — matching_new_activity={bool(matching)} ' + f'target_stage_closed_won={stage_ok}') + return 0.0, max_pts + except Exception as e: + print(f'ERROR: C3 (salesforce) — {e}') + return 0.0, max_pts + + +def check_slack(scored, initial): + """Component 4 — new #deal-desk message: Globex, $120,000, awaiting signature. (0.20)""" + max_pts = 0.20 + try: + channel_ids = { + c.get('channelId') for c in (scored.get('channels', []) or []) + if _norm_words(c.get('name')) == 'deal desk' + or _norm_words(c.get('channelId')) == 'deal desk' + } + channel_ids.add('deal-desk') + + new_msgs = [] + for channel_id in [c for c in channel_ids if c]: + ini_msgs = (initial.get('messages', {}) or {}).get(channel_id, []) or [] + cur_msgs = (scored.get('messages', {}) or {}).get(channel_id, []) or [] + ini_ids = {m.get('messageId') for m in ini_msgs} + new_msgs.extend(m for m in cur_msgs if m.get('messageId') not in ini_ids) + if not new_msgs: + print('FAIL: C4 — no NEW message in #deal-desk') + return 0.0, max_pts + + for m in new_msgs: + blob = str(m.get('content', '')) + has_customer = _has_any(blob, ['globex', 'globex corporation']) + has_amount = _amount_matches(blob, 120000) + has_await = _sent_for_signature(blob) + if has_customer and has_amount and has_await: + print(f'PASS: C4 — #deal-desk message mentions Globex, $120,000, ' + f'awaiting signature (0.20)') + return max_pts, max_pts + print(f'FAIL: C4 — new message(s) present but none mention all of ' + f'{{Globex, 120000, awaiting signature}}: ' + f'{[m.get("content") for m in new_msgs]}') + return 0.0, max_pts + except Exception as e: + print(f'ERROR: C4 (slack) — {e}') + return 0.0, max_pts + + +def _num(v): + try: + text = str(v).replace(',', '').replace('$', '') + if text.lower().strip().endswith('k'): + return float(text[:-1]) * 1000 + return float(text) + except Exception: + return None + + +def main(): + sid = read_sid() + if not sid: + print('REWARD: 0.0') + return + + print(f'Egress: direct; scoring state: {STATE_TO_SCORE}') + + states = fetch_all(sid) + if states is None: + print('REWARD: 0.0') + return + + total = 0.0 + ds_s, ds_i = pick(states, 'docusign') + no_s, no_i = pick(states, 'notion') + sf_s, sf_i = pick(states, 'salesforce') + sl_s, sl_i = pick(states, 'slack') + + p, _ = check_docusign(ds_s or {}, ds_i or {}); total += p + p, _ = check_notion(no_s or {}, no_i or {}); total += p + p, _ = check_salesforce(sf_s or {}, sf_i or {}); total += p + p, _ = check_slack(sl_s or {}, sl_i or {}); total += p + + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + + +main() diff --git a/ae_contract_signature_001/reward_label.json b/ae_contract_signature_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..0acf4b10fd48509ada1bd16bce78ba12670b2e30 --- /dev/null +++ b/ae_contract_signature_001/reward_label.json @@ -0,0 +1,63 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ae_contract_signature_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 18:47:48", + "label": { + "task_id": "ae_contract_signature_001", + "domain": "mock_websites", + "summary": "验证在DocuSign、Notion、Salesforce和Slack四个mock服务中,是否针对Globex Platform Expansion订单成功创建了新的信封、数据库行、活动记录和频道消息,并满足指定的内容与状态要求。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "docusign_mock (http://28.7.186.212:8150)", + "notion_mock (http://28.7.186.212:8186)", + "salesforce_mock (http://28.7.186.212:8195)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Component 1 — DocuSign envelope", + "weight": 0.35, + "description": "检查DocuSign中是否新增了引用Globex Platform Expansion订单的信封,且状态为已发送,并包含指定的签署人。", + "check_logic": "对比initial_state与scored_state的envelopes列表,筛选出id不在初始状态的新信封;通过subject/message/documents.name匹配是否包含globex、platform、expansion、order form等关键词;若找到则得0.10。进一步检查status归一化后是否为sent或delivered且sentAt可解析为有效时间戳,满足则再加0.10。最后检查recipients中role含signer的恰好只有一人,且其email必须为maria.gomez@globex.com,name最好匹配Maria Gomez,满足则再加0.15。", + "pass_condition": "存在新的Globex Platform Expansion订单信封(+0.10),status为sent/delivered且sentAt有效(+0.10),恰好一个signer且email为maria.gomez@globex.com(+0.15)" + }, + { + "name": "Component 2 — Notion 'Contracts' row", + "weight": 0.25, + "description": "检查Notion的Contracts数据库中是否新增了符合要求的合同行。", + "check_logic": "在scored_state中查找title归一化后为contracts的数据库;对比initial_state找出该数据库下新增的item(通过items列表或parentId判断)。对新增行提取Customer、Deal、Amount、Status四个字段,要求Customer包含globex,Deal同时包含platform和expansion,Amount匹配120000,Status归一化后等于sent。四个条件全部满足得0.25,否则该组件得0.0。", + "pass_condition": "Contracts数据库中存在新增行,且Customer含Globex、Deal含Platform Expansion、Amount为120000、Status为Sent" + }, + { + "name": "Component 3 — Salesforce activity on opp-1", + "weight": 0.2, + "description": "检查Salesforce中是否在opp-1上新增了记录发送订单表单的活动,且机会阶段保持Closed Won。", + "check_logic": "对比activities找出activityId不在初始状态的新活动。定位目标机会(opp-1或name匹配Globex Platform Expansion且amount为120000的机会)。检查新活动的relatedToId是否等于该机会ID,且subject/description/type/status的拼接文本中提及order form/docusign/envelope等关键词,并通过_sent_for_signature判断为待签署状态。同时要求该机会的stage归一化后仍为closed won。全部满足得0.20,否则0.0。", + "pass_condition": "存在与opp-1相关的新活动,内容表明订单表单/DocuSign已发送待签署,且对应机会阶段仍为Closed Won" + }, + { + "name": "Component 4 — Slack #deal-desk message", + "weight": 0.2, + "description": "检查Slack的#deal-desk频道中是否新增了提及Globex、金额12万且等待签署的消息。", + "check_logic": "在scored_state中查找name或channelId匹配deal desk的频道(包括deal-desk)。对比initial_state的messages,筛选出messageId不在初始状态的新消息。遍历新消息,检查content是否同时包含:Globex相关关键词、金额120000、以及待签署语义(通过_sent_for_signature判断)。任一消息满足全部三个条件即得0.20,否则0.0。", + "pass_condition": "#deal-desk频道中存在新消息,同时提及Globex、金额120000和等待签署/已发送待签等语义" + } + ], + "total_max_score": 1.0, + "score_aggregation": "四个组件得分直接相加,最终结果通过min(total, 1.0)钳制到上限1.0,并四舍五入保留4位小数。", + "failure_modes": [ + "读取/tmp/task_web_sid失败或sid为空时,脚本打印CRITICAL并直接返回REWARD: 0.0", + "任一mock服务(docusign/notion/salesforce/slack)的/go接口请求失败或超时,fetch_all返回None,脚本直接返回REWARD: 0.0", + "DocuSign中未找到新的Globex Platform Expansion信封,该组件得0分(后续子项不再计分)", + "Notion中未找到Contracts数据库、无新增行、或新增行四个字段任一不匹配,该组件得0分", + "Salesforce中未找到匹配的新activity、activity未关联目标机会、内容未提及订单/DocuSign/待签署、或机会stage不是Closed Won,该组件得0分", + "Slack中#deal-desk无新消息,或新消息未同时包含Globex、120000、待签署三个要素,该组件得0分" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,然后并行(顺序)向四个mock服务请求/go接口获取initial_state和current_state。根据环境变量REWARD_STATE_KEY(默认current_state)确定要评分的状态。随后依次执行四个组件检查:每个组件都将当前状态与初始状态对比,仅验证任务执行期间新增的artifact。Component 1采用增量计分(0.10+0.10+0.15),其余组件为二值判定(通过得满分,否则得0)。各组件得分累加后,用min函数确保不超过1.0上限,最后输出REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ae_contract_signature_003(从 docstring 中明确提取)\n - Domain: mock_websites (multi-mock: docusign, notion, salesforce, slack)(从 docstring 中提取)\n\n2. **脚本性质**:\n - 这不是占位脚本,它实际检查了多个 mock 服务的状态。\n - is_placeholder: false\n\n3. **数据源**:\n - /tmp/task_web_sid(读取 sid)\n - docusign mock: http://28.7.186.212:8150\n - notion mock: http://28.7.186.212:8186\n - salesforce mock: http://28.7.186.212:8195\n - slack mock: http://28.7.186.212:8198\n\n4. **评分组件**:\n - Component 1: DocuSign envelope (0.35)\n - 检查新的 envelope 引用 Globex Platform Expansion order form (0.10)\n - status == 'sent' 或 'delivered' 且 sentAt 可解析 (0.10)\n - 恰好一个 signer recipient 名为 Maria Gomez / maria.gomez@globex.com (0.15)\n - 注意:代码中 1a、1b、1c 是累加的,但 1a 只要找到 globex_new 就加 0.10,1b 条件满足加 0.10,1c 条件满足加 0.15。如果前面失败会提前 return。\n \n - Component 2: Notion 'Contracts' row (0.25)\n - 检查 Contracts 数据库中新增的行\n - Customer 包含 Globex\n - Deal 包含 Platform Expansion\n - Amount 匹配 120000\n - Status 为 'sent'\n - 这是一个全有或全无的检查,通过得 0.25,否则 0.0\n \n - Component 3: Salesforce activity on opp-1 (0.20)\n - 检查 opp-1(或匹配的 Globex Platform Expansion 机会)上的新 activity\n - activity 内容引用 order form/DocuSign/sent\n - 且 opp-1 stage 仍为 'Closed Won'\n - 全有或全无,0.20 或 0.0\n \n - Component 4: Slack #deal-desk message (0.20)\n - 检查 #deal-desk 频道的新消息\n - 消息提及 Globex、amount 120000、awaiting signature\n - 全有或全无,0.20 或 0.0\n\n5. **分数汇总**:\n - 各组件分数相加\n - 最后 min(total, 1.0) 并四舍五入到 4 位小数\n - total_max_score: 1.0\n\n6. **失败模式**:\n - 读取 /tmp/task_web_sid 失败 → return 0.0\n - fetch_all 任一 mock 拉取失败 → return 0.0\n - DocuSign: 无新 envelope → 该组件 0 分(不会提前退出,只是该组件 0 分)\n - Notion: 找不到 Contracts 数据库 → 0 分;无新行 → 0 分;字段不匹配 → 0 分\n - Salesforce: 无匹配新 activity 或 stage 不是 Closed Won → 0 分\n - Slack: 无新消息 → 0 分;新消息但不包含所有要求 → 0 分\n\n7. **评分逻辑详细解释**:\n - 读取 sid 文件\n - 从四个 mock 服务获取 initial_state 和 current_state\n - 根据 STATE_TO_SCORE 环境变量决定评分状态(默认 current_state)\n - 分别检查四个组件,每个组件对比 scored state 和 initial state,只验证 NEW 的 artifact\n - 累加各组件得分,上限 1.0\n\n8. **Confidence**: 1.0(代码逻辑清晰完整)\n\n现在构建 JSON:\n\n- task_id: \"ae_contract_signature_003\"\n- domain: \"mock_websites\"\n- summary: \"验证在 DocuSign、Notion、Salesforce 和 Slack 四个 mock 服务中是否成功创建了与 Globex Platform Expansion 订单相关的新工件(信封、数据库行、活动记录和 Slack 消息),并确保状态正确。\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"docusign_mock\", \"notion_mock\", \"salesforce_mock\", \"slack_mock\"] 或者更具体地按照代码中的 URL。但通常写 mock 服务名即可。代码中写的是 MOCKS 字典的 key 和 /tmp/task_web_sid。\n\n让我再仔细看 Component 1 的 weight。代码中:\n- 1a: 0.10\n- 1b: 0.10\n- 1c: 0.15\n- 总计 max 0.35\n\n但 JSON 格式要求每个组件一个 weight。Component 1 的总 weight 是 0.35。在 check_logic 中说明子分数。\n\n对于 Component 2、3、4,代码中是二值判定(返回 max_pts 或 0.0),weight 应填 1.0?不,等等。用户说:\"weight 字段填写代码中显式给出的分值(如 0.3);若代码未显式分值但有通过/失败二值判定,weight 填 1.0 并在 check_logic 中说明。\"\n\n但是这里 Component 2 的 max_pts 是 0.25,Component 3 是 0.20,Component 4 是 0.20。这些分值在 docstring 和代码中都明确给出了。所以 weight 应该填这些分值。\n\n等等,用户说:\"若代码未显式分值但有通过/失败二值判定,weight 填 1.0\"。但这里代码有显式分值(0.25, 0.20, 0.20),所以填这些。\n\nComponent 1 比较特殊,它内部有子分数(0.10, 0.10, 0.15),但总体 max 是 0.35。weight 填 0.35。\n\ncheck_logic 需要描述具体判断逻辑。\n\n让我再确认一下 Component 1 的通过条件:\n- 必须存在新的 envelope 引用 Globex Platform Expansion order form(否则直接 return 0.0, 0.35)\n- 如果存在,+0.10\n- status 是 sent/delivered 且 sentAt 可解析,+0.10\n- 恰好一个 signer,名字匹配 Maria Gomez 或邮箱是 maria.gomez@globex.com,且邮箱必须等于 maria.gomez@globex.com,+0.15\n\n注意 C1c 的条件:`name_ok and em == 'maria.gomez@globex.com'`,其中 name_ok 是 `_name_matches(nm, 'maria', 'gomez') or em == 'maria.gomez@globex.com'`。所以实际上邮箱必须匹配,名字最好也匹配(或者如果名字不匹配但邮箱匹配,name_ok 为 true,然后 `name_ok and em == ...` 只要邮箱对就过)。\n\nComponent 2:\n- 找到 Contracts 数据库\n- 找到新行\n- 检查四个字段:customer 含 globex,deal 含 platform+expansion,amount 匹配 120000,status 为 sent\n- 全部满足得 0.25,否则 0.0\n\nComponent 3:\n- 找到 opp-1(或匹配的 Globex Platform Expansion 机会)\n- 检查新 activity 是否 relatedToId 匹配 opp_id\n- activity 内容 blob 包含 order form/orderform/docu sign/docusign/envelope/signature packet 之一,且 _sent_for_signature 为 true\n- opp1 stage 仍为 closed won\n- 全满足得 0.20\n\nComponent 4:\n- 在 #deal-desk 频道(channelId 或 name 匹配)\n- 找到新消息\n- 消息内容包含 Globex、120000、awaiting signature(通过 _sent_for_signature 判断)\n- 满足得 0.20\n\nScore aggregation: 相加,然后 min(total, 1.0),四舍五入到 4 位小数。\n\nFailure modes:\n- 读取 sid 失败 → REWARD: 0.0\n- fetch_all 任一 mock 失败 → REWARD: 0.0\n- DocuSign 无新 Globex envelope → 该组件 0 分\n- Notion 无 Contracts DB → 0 分;无新行 → 0 分;字段不匹配 → 0 分\n- Salesforce 无匹配 activity 或 stage 非 Closed Won → 0 分\n- Slack 无新消息或内容不匹配 → 0 分\n\n现在组织 JSON。 {\"task_id\":\"ae_contract_signature_003\",\"domain\":\"mock_websites\",\"summary\":\"验证在DocuSign、Notion、Salesforce和Slack四个mock服务中,是否针对Globex Platform Expansion订单成功创建了新的信封、数据库行、活动记录和频道消息,并满足指定的内容与状态要求。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"docusign_mock (http://28.7.186.212:8150)\",\"notion_mock (http://28.7.186.212:8186)\",\"salesforce_mock (http://28.7.186.212:8195)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Component 1 — DocuSign envelope\",\"weight\":0.35,\"description\":\"检查DocuSign中是否新增了引用Globex Platform Expansion订单的信封,且状态为已发送,并包含指定的签署人。\",\"check_logic\":\"对比initial_state与scored_state的envelopes列表,筛选出id不在初始状态的新信封;通过subject/message/documents.name匹配是否包含globex、platform、expansion、order form等关键词;若找到则得0.10。进一步检查status归一化后是否为sent或delivered且sentAt可解析为有效时间戳,满足则再加0.10。最后检查recipients中role含signer的恰好只有一人,且其email必须为maria.gomez@globex.com,name最好匹配Maria Gomez,满足则再加0.15。\",\"pass_condition\":\"存在新的Globex Platform Expansion订单信封(+0.10),status为sent/delivered且sentAt有效(+0.10),恰好一个signer且email为maria.gomez@globex.com(+0.15)\"},{\"name\":\"Component 2 — Notion 'Contracts' row\",\"weight\":0.25,\"description\":\"检查Notion的Contracts数据库中是否新增了符合要求的合同行。\",\"check_logic\":\"在scored_state中查找title归一化后为contracts的数据库;对比initial_state找出该数据库下新增的item(通过items列表或parentId判断)。对新增行提取Customer、Deal、Amount、Status四个字段,要求Customer包含globex,Deal同时包含platform和expansion,Amount匹配120000,Status归一化后等于sent。四个条件全部满足得0.25,否则该组件得0.0。\",\"pass_condition\":\"Contracts数据库中存在新增行,且Customer含Globex、Deal含Platform Expansion、Amount为120000、Status为Sent\"},{\"name\":\"Component 3 — Salesforce activity on opp-1\",\"weight\":0.20,\"description\":\"检查Salesforce中是否在opp-1上新增了记录发送订单表单的活动,且机会阶段保持Closed Won。\",\"check_logic\":\"对比activities找出activityId不在初始状态的新活动。定位目标机会(opp-1或name匹配Globex Platform Expansion且amount为120000的机会)。检查新活动的relatedToId是否等于该机会ID,且subject/description/type/status的拼接文本中提及order form/docusign/envelope等关键词,并通过_sent_for_signature判断为待签署状态。同时要求该机会的stage归一化后仍为closed won。全部满足得0.20,否则0.0。\",\"pass_condition\":\"存在与opp-1相关的新活动,内容表明订单表单/DocuSign已发送待签署,且对应机会阶段仍为Closed Won\"},{\"name\":\"Component 4 — Slack #deal-desk message\",\"weight\":0.20,\"description\":\"检查Slack的#deal-desk频道中是否新增了提及Globex、金额12万且等待签署的消息。\",\"check_logic\":\"在scored_state中查找name或channelId匹配deal desk的频道(包括deal-desk)。对比initial_state的messages,筛选出messageId不在初始状态的新消息。遍历新消息,检查content是否同时包含:Globex相关关键词、金额120000、以及待签署语义(通过_sent_for_signature判断)。任一消息满足全部三个条件即得0.20,否则0.0。\",\"pass_condition\":\"#deal-desk频道中存在新消息,同时提及Globex、金额120000和等待签署/已发送待签等语义\"}],\"total_max_score\":1.0,\"score_aggregation\":\"四个组件得分直接相加,最终结果通过min(total, 1.0)钳制到上限1.0,并四舍五入保留4位小数。\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或sid为空时,脚本打印CRITICAL并直接返回REWARD: 0.0\",\"任一mock服务(docusign/notion/salesforce/slack)的/go接口请求失败或超时,fetch_all返回None,脚本直接返回REWARD: 0.0\",\"DocuSign中未找到新的Globex Platform Expansion信封,该组件得0分(后续子项不再计分)\",\"Notion中未找到Contracts数据库、无新增行、或新增行四个字段任一不匹配,该组件得0分\",\"Salesforce中未找到匹配的新activity、activity未关联目标机会、内容未提及订单/DocuSign/待签署、或机会stage不是Closed Won,该组件得0分\",\"Slack中#deal-desk无新消息,或新消息未同时包含Globex、120000、待签署三个要素,该组件得0分\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,然后并行(顺序)向四个mock服务请求/go接口获取initial_state和current_state。根据环境变量REWARD_STATE_KEY(默认current_state)确定要评分的状态。随后依次执行四个组件检查:每个组件都将当前状态与初始状态对比,仅验证任务执行期间新增的artifact。Component 1采用增量计分(0.10+0.10+0.15),其余组件为二值判定(通过得满分,否则得0)。各组件得分累加后,用min函数确保不超过1.0上限,最后输出REWARD。\",\"confidence\":1.0}" +} diff --git a/ae_deal_handoff_002__long/_cua_gym_vm_bridge.sh b/ae_deal_handoff_002__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ae_deal_handoff_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/ae_deal_handoff_002__long/initial_setup.py b/ae_deal_handoff_002__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..46a82e5cec07bcd15722c95654a69c093d159bdc --- /dev/null +++ b/ae_deal_handoff_002__long/initial_setup.py @@ -0,0 +1,762 @@ +""" +Initial Setup: Hand off qualified opportunities (H16) +Task ID: ae_deal_handoff_002__long +Mocks: salesforce_mock,trello_mock,gmail_mock,slack_mock + +A sales-ops rep hands off newly-qualified Salesforce Closed-Won opportunities +to the delivery team. For each qualifying opp the rep tiers by amount, then +takes tier-appropriate actions across SF (owner + optional kickoff task), +Trello (handoff card w/ tier label + due date), Gmail (label + kickoff email +for Tier-1 only), and Slack (summary post + pin). + +DEVIATION FROM DESIGN SPEC: the salesforce_mock Opportunity.stage enum has +NO 'Onboarding' value; per the design's construction note, the graded +Salesforce transition is Owner -> 'Delivery Lead' for every tier. Stage is +left unchanged. + +Ground-truth (answer key) is embedded in salesforce.initial_state._task_adapter +(task_opps + expected). Every listed action is ABSENT at injection (Rule 3): +no Handoff cards, no 'Kickoff -' activities, no Handoff labels or Kickoff +emails, no #delivery messages. +""" +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}') + +TASK_ID = '9e3cf2fc-771b-44a9-8dd3-2b8b9a6f91b4' +TODAY = _dt.date(2026, 6, 29) +SUMMARY_CHANNEL = 'delivery' + +TIER1_MIN = 100_000 +TIER2_MIN = 25_000 +TIER_DUE_DAYS = {'Tier-1': 3, 'Tier-2': 5, 'Tier-3': 7} +TIER_LABEL_NAMES = {'Tier-1': 'Tier-1', 'Tier-2': 'Tier-2', 'Tier-3': 'Tier-3'} + +DELIVERY_BOARD_ID = 'board-delivery' +DELIVERY_LIST_ID = 'list-delivery-queue' + +ADMIN_OWNER_ID = 'user-admin' +ADMIN_OWNER_NAME = 'Admin User' +DELIVERY_OWNER_ID = 'user-delivery' +DELIVERY_OWNER_NAME = 'Delivery Lead' +MANAGER_ID = 'user-1' + + +def _tier_of(amount): + if amount >= TIER1_MIN: + return 'Tier-1' + if amount >= TIER2_MIN: + return 'Tier-2' + return 'Tier-3' + + +def _due(days): + return (TODAY + _dt.timedelta(days=days)).isoformat() + + +_OPP_SPEC = [ + dict(name='Northstar Platform Rollout', account='Northstar Industries', + account_email='ap@northstarind.example', + amount=185_000, stage='Closed Won', owner=ADMIN_OWNER_ID), + dict(name='Cedar Grove Expansion', account='Cedar Grove Health', + account_email='billing@cedargrove.example', + amount=140_000, stage='Closed Won', owner=ADMIN_OWNER_ID), + dict(name='Blue Harbor Renewal', account='Blue Harbor Marine', + account_email='ap@blueharbor.example', + amount=68_000, stage='Closed Won', owner=ADMIN_OWNER_ID), + dict(name='Sunridge Solar Deploy', account='Sunridge Energy', + account_email='ap@sunridge.example', + amount=42_000, stage='Closed Won', owner=ADMIN_OWNER_ID), + dict(name='Fernway Analytics Pilot', account='Fernway Analytics', + account_email='ap@fernway.example', + amount=18_500, stage='Closed Won', owner=ADMIN_OWNER_ID), + dict(name='Kinley Retail Onboard', account='Kinley Retail', + account_email='ap@kinley.example', + amount=9_800, stage='Closed Won', owner=ADMIN_OWNER_ID), + dict(name='Ember Valley Upsell', account='Ember Valley Insurance', + account_email='ap@embervalley.example', + amount=210_000, stage='Negotiation', owner=ADMIN_OWNER_ID), + dict(name='Silverline Migration', account='Silverline Networks', + account_email='ap@silverline.example', + amount=125_000, stage='Closed Won', owner=DELIVERY_OWNER_ID), +] + +opportunities = [] +task_opps = {} +expected = [] + +for idx, spec in enumerate(_OPP_SPEC, start=1): + opp_id = f'opp-{idx}' + tier = _tier_of(spec['amount']) if spec['stage'] == 'Closed Won' else None + already_handed_off = (spec['owner'] == DELIVERY_OWNER_ID) + is_won = (spec['stage'] == 'Closed Won') + requires_action = bool(is_won and not already_handed_off) + + card_title = f'Handoff: {spec["name"]}' if requires_action else None + card_label = TIER_LABEL_NAMES.get(tier) if requires_action else None + card_due = _due(TIER_DUE_DAYS[tier]) if (requires_action and tier) else None + task_subject = f'Kickoff - {spec["name"]}' if (requires_action and tier == 'Tier-1') else None + email_subject = f'Kickoff for {spec["name"]}' if (requires_action and tier == 'Tier-1') else None + label_name = 'Handoff' if (requires_action and tier == 'Tier-1') else None + + opportunities.append({ + 'opportunityId': opp_id, + 'name': spec['name'], + 'accountId': f'acct-{idx}', + 'contactId': f'contact-{idx}', + 'amount': spec['amount'], + 'closeDate': (TODAY - _dt.timedelta(days=1)).isoformat(), + 'stage': spec['stage'], + 'probability': 100 if is_won else 60, + 'ownerId': spec['owner'], + 'createdDate': '2026-06-01T09:00:00Z', + 'modifiedDate': '2026-06-24T09:00:00Z', + }) + task_opps[opp_id] = { + 'id': opp_id, + 'name': spec['name'], + 'account': spec['account'], + 'ownerName': (ADMIN_OWNER_NAME if spec['owner'] == ADMIN_OWNER_ID + else DELIVERY_OWNER_NAME), + } + expected.append({ + 'opp_id': opp_id, + 'opp_name': spec['name'], + 'account': spec['account'], + 'account_email': spec['account_email'], + 'amount': spec['amount'], + 'stage_at_injection': spec['stage'], + 'owner_id_at_injection': spec['owner'], + 'tier': tier, + 'requires_action': requires_action, + 'target_owner_name': DELIVERY_OWNER_NAME if requires_action else None, + 'card_title': card_title, + 'card_label': card_label, + 'card_due': card_due, + 'task_subject': task_subject, + 'email_subject': email_subject, + 'label_name': label_name, + }) + +_won_action = [e for e in expected if e['requires_action']] +_tier1 = [e for e in _won_action if e['tier'] == 'Tier-1'] +_tier2 = [e for e in _won_action if e['tier'] == 'Tier-2'] +_tier3 = [e for e in _won_action if e['tier'] == 'Tier-3'] +_skipped = [e for e in expected if not e['requires_action']] + +assert len(expected) == 8 +assert len(_tier1) == 2 and len(_tier2) == 2 and len(_tier3) == 2 +assert len(_skipped) == 2 + +expected_card_titles = [e['card_title'] for e in _won_action] + +SF_USERS = [ + {'userId': MANAGER_ID, 'firstName': 'Jordan', 'lastName': 'Blake', + 'email': 'jordan.blake@company.example', 'phone': '(555) 123-4567', + 'title': 'Sales Ops', 'department': 'Sales', 'role': 'Manager', + 'avatar': 'https://i.pravatar.cc/150?u=user-1', + 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': ADMIN_OWNER_ID, 'firstName': 'Admin', 'lastName': 'User', + 'email': 'admin.user@company.example', 'phone': '', + 'title': 'System Administrator', 'department': 'Operations', 'role': 'Admin', + 'avatar': 'https://i.pravatar.cc/150?u=admin', + 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': DELIVERY_OWNER_ID, 'firstName': 'Delivery', 'lastName': 'Lead', + 'email': 'delivery.lead@company.example', 'phone': '', + 'title': 'Delivery Lead', 'department': 'Delivery', 'role': 'Rep', + 'avatar': 'https://i.pravatar.cc/150?u=delivery', + 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'user-2', 'firstName': 'Sara', 'lastName': 'Nolan', + 'email': 'sara.nolan@company.example', 'phone': '', + 'title': 'Account Executive', 'department': 'Sales', 'role': 'Rep', + 'avatar': 'https://i.pravatar.cc/150?u=user-2', + 'timezone': 'America/Chicago', 'locale': 'en-US', 'theme': 'lightning'}, +] + +SF_ACCOUNTS = [] +SF_CONTACTS = [] +for idx, spec in enumerate(_OPP_SPEC, start=1): + aid = f'acct-{idx}' + cid = f'contact-{idx}' + SF_ACCOUNTS.append({ + 'accountId': aid, 'name': spec['account'], 'industry': 'Technology', + 'annualRevenue': spec['amount'] * 8, 'website': '', + 'phone': '(555) 010-0100', 'billingStreet': '', + 'billingCity': '', 'billingState': '', 'billingZip': '', + 'billingCountry': 'United States', 'ownerId': ADMIN_OWNER_ID, + 'createdDate': '2026-05-01T00:00:00Z', + }) + SF_CONTACTS.append({ + 'contactId': cid, 'accountId': aid, + 'firstName': 'Ops', 'lastName': f'Contact {idx}', + 'email': spec['account_email'], 'phone': '(555) 010-0100', + 'title': 'Head of Ops', 'ownerId': ADMIN_OWNER_ID, + 'createdDate': '2026-05-01T00:00:00Z', + }) + +SF_ACTIVITIES = [ + {'activityId': 'activity-decoy-1', 'type': 'event', 'subject': 'Weekly deal review', + 'status': 'Completed', 'priority': 'Normal', + 'startDateTime': '2026-06-24T15:00:00Z', 'endDateTime': '2026-06-24T15:30:00Z', + 'relatedToType': 'Opportunity', 'relatedToId': 'opp-1', + 'assignedToId': 'user-2', 'description': ''}, + {'activityId': 'activity-decoy-2', 'type': 'task', + 'subject': 'Send proposal to Ember Valley', + 'status': 'Completed', 'priority': 'Low', + 'dueDate': (TODAY - _dt.timedelta(days=2)).isoformat(), + 'relatedToType': 'Opportunity', 'relatedToId': 'opp-7', + 'assignedToId': 'user-2', 'description': ''}, +] + +salesforce_state = { + 'user': SF_USERS[0], + 'users': SF_USERS, + 'leads': [], + 'accounts': SF_ACCOUNTS, + 'contacts': SF_CONTACTS, + 'opportunities': opportunities, + 'cases': [], + 'activities': SF_ACTIVITIES, + 'chatterPosts': [], + 'files': [], + 'dashboards': [], + 'following': [], + 'recentlyViewed': [], + 'dismissedNotifications': [], + '_task_adapter': { + 'task_id': TASK_ID, + 'variant': 'eval', + 'today': TODAY.isoformat(), + 'task_opps': task_opps, + 'expected': expected, + 'summary_channel': SUMMARY_CHANNEL, + 'delivery_owner_name': DELIVERY_OWNER_NAME, + 'delivery_board_id': DELIVERY_BOARD_ID, + 'delivery_list_id': DELIVERY_LIST_ID, + 'delivery_list_name': 'Delivery Queue', + 'delivery_board_name': 'Delivery Handoffs', + 'expected_card_titles': expected_card_titles, + 'tier_label_names': TIER_LABEL_NAMES, + }, +} + +_forbidden_task_subjects = { + (e['task_subject'] or '').lower() for e in _tier1 if e['task_subject'] +} +assert not any(str(a.get('subject', '')).lower() in _forbidden_task_subjects + for a in SF_ACTIVITIES) +_won_action_ids = {e['opp_id'] for e in _won_action} +for opp in opportunities: + if opp['opportunityId'] in _won_action_ids: + assert opp['ownerId'] == ADMIN_OWNER_ID + +LABEL_TIER1 = 'lbl-tier-1' +LABEL_TIER2 = 'lbl-tier-2' +LABEL_TIER3 = 'lbl-tier-3' + +trello_boards = { + DELIVERY_BOARD_ID: { + 'id': DELIVERY_BOARD_ID, + 'title': 'Delivery Handoffs', + 'description': 'Queue of qualified opps handed off to Delivery', + 'listIds': [DELIVERY_LIST_ID], + 'starred': True, + 'visibility': 'workspace', + 'archivedListIds': [], + 'archivedCardIds': [], + 'labels': [ + {'id': LABEL_TIER1, 'name': 'Tier-1', 'color': 'red'}, + {'id': LABEL_TIER2, 'name': 'Tier-2', 'color': 'orange'}, + {'id': LABEL_TIER3, 'name': 'Tier-3', 'color': 'green'}, + ], + 'memberIds': ['u1'], + 'createdAt': '2026-05-01T09:00:00.000Z', + }, +} + +trello_lists = { + DELIVERY_LIST_ID: { + 'id': DELIVERY_LIST_ID, + 'title': 'Delivery Queue', + 'boardId': DELIVERY_BOARD_ID, + 'cardIds': ['card-watermark'], + 'archived': False, + 'position': 0, + 'createdAt': '2026-05-01T09:00:00.000Z', + }, +} + +trello_cards = { + 'card-watermark': { + 'id': 'card-watermark', + 'title': 'Delivery Queue -- add handoff cards below', + 'description': 'Watermark card. Do not touch.', + 'listId': DELIVERY_LIST_ID, + 'boardId': DELIVERY_BOARD_ID, + 'labelIds': [], + 'memberIds': [], + 'dueDate': None, + 'startDate': None, + 'completed': False, + 'cover': None, + 'checklists': [], + 'comments': [], + 'attachments': [], + 'archived': False, + 'watching': False, + 'position': 0, + 'createdAt': '2026-05-01T09:00:00.000Z', + }, +} + +trello_state = { + 'currentUser': {'id': 'u1', 'name': 'Jordan Blake', + 'email': 'jordan.blake@company.example', + 'avatar': 'https://picsum.photos/200/200?random=trello'}, + 'members': [{'id': 'u1', 'name': 'Jordan Blake', + 'email': 'jordan.blake@company.example', + 'avatar': 'https://picsum.photos/200/200?random=trello'}], + 'boards': trello_boards, + 'lists': trello_lists, + 'cards': trello_cards, + 'workspaces': [{'id': 'ws-1', 'name': 'Sales Ops', 'boards': [DELIVERY_BOARD_ID]}], + 'activeBoard': DELIVERY_BOARD_ID, + 'ui': {'openCardId': None, 'searchQuery': ''}, +} + +_forbidden_card_titles = {t.lower() for t in expected_card_titles} +assert not any(str(c.get('title', '')).lower() in _forbidden_card_titles + for c in trello_cards.values()) + +GMAIL_USER = { + 'userId': 'u1', + 'username': 'Jordan Blake', + 'email': 'jordan.blake@company.example', + 'avatar': 'https://picsum.photos/200/200?random=gmail', +} + +GMAIL_LABELS = [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'lbl-handoff', 'name': 'Handoff', 'color': '#8b5cf6'}, + {'id': 'lbl-tier1', 'name': 'Tier-1', 'color': '#f59e0b'}, +] + + +def _gmail_email(eid, sender_name, sender_email, subject, body, ts, folder='inbox'): + return { + 'id': eid, 'threadId': f'thread_{eid}', + 'from': {'name': sender_name, 'email': sender_email, 'avatar': ''}, + 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}], + 'cc': [], 'bcc': [], 'folder': folder, + 'subject': subject, 'body': body, 'snippet': body[:120], + 'timestamp': ts, 'read': False, 'starred': False, 'important': False, + 'labels': [], 'category': 'primary', 'attachments': [], + } + + +EMAILS = [] +_ts_pool = ['2026-06-29T07:12:00Z', '2026-06-29T06:40:00Z', + '2026-06-29T05:55:00Z', '2026-06-29T05:20:00Z', + '2026-06-28T18:02:00Z', '2026-06-28T16:15:00Z'] +for i, e in enumerate(_won_action): + EMAILS.append(_gmail_email( + f'm-acct-{i + 1}', e['account'], e['account_email'], + f"Onboarding logistics -- {e['opp_name']}", + (f"Hi Jordan, this is {e['account']}. Now that we are signed we would like to " + f"align on the kickoff plan and delivery timeline for {e['opp_name']}. " + f"Can you loop in the delivery team?"), + _ts_pool[i % len(_ts_pool)])) +EMAILS.append(_gmail_email( + 'm-noise-1', 'Sales Weekly', 'newsletter@company.example', + 'Sales Weekly digest', 'Wins from this week + a couple of reminders.', + '2026-06-29T04:00:00Z')) + +_tier1_addrs = {e['account_email'].lower() for e in _tier1} +assert all(em['labels'] == [] for em in EMAILS) +assert not any(em['folder'] == 'sent' + and any((r.get('email') or '').lower() in _tier1_addrs + for r in em.get('to', [])) + for em in EMAILS) + +gmail_state = { + 'user': GMAIL_USER, + 'emails': EMAILS, + 'labels': GMAIL_LABELS, + 'drafts': [], + 'settings': {'density': 'default', 'undoSend': 10}, + 'today': TODAY.isoformat(), +} + +SLACK_USERS = [ + {'userId': 'user_1', 'fullName': 'Jordan Blake', 'displayName': 'Jordan', + 'email': 'jordan.blake@company.example', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Sales Ops', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Sara Nolan', 'displayName': 'Sara', + 'email': 'sara.nolan@company.example', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'AE', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/Chicago'}, + {'userId': 'user_3', 'fullName': 'Delivery Lead', 'displayName': 'Delivery', + 'email': 'delivery.lead@company.example', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Delivery Lead', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, +] + + +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 Sales Ops', 'icon': ''}, + 'users': SLACK_USERS, + 'channels': [ + _slack_channel('delivery', 'delivery', 'Handoffs to the delivery team', + 'Post the daily handoff summary here', starred=True), + _slack_channel('general', 'general', 'Company-wide announcements', + 'Welcome!', starred=True), + _slack_channel('random', 'random', 'Non-work banter', 'Watercooler', + unread=2), + _slack_channel('deals', 'deals', 'War-room for active deals', + 'Post wins here', unread=1), + ], + 'messages': { + 'delivery': [], + 'general': [ + _slack_msg('m_g_1', 'user_2', 'Morning all -- pipeline is looking good.', + '2026-06-29T07:55:00Z'), + ], + 'random': [ + _slack_msg('m_r_1', 'user_3', 'Anyone up for coffee?', + '2026-06-29T07:20:00Z'), + ], + 'deals': [ + _slack_msg('m_d_1', 'user_2', 'Northstar came in above quota.', + '2026-06-27T16:15:00Z'), + ], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', + 'displayDensity': 'comfortable', 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + '_task_adapter': { + 'task_id': TASK_ID, + 'variant': 'eval', + 'summary_channel': SUMMARY_CHANNEL, + 'won_action_count': len(_won_action), + }, +} +assert not slack_state['messages'].get('delivery') + +APP_STATES = [ + ('http://28.7.184.198:8175', salesforce_state), + ('http://28.7.184.198:8182', trello_state), + ('http://28.7.184.198:8138', gmail_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}') + +print(f'Precomputed: won_action={len(_won_action)} T1={len(_tier1)} ' + f'T2={len(_tier2)} T3={len(_tier3)} skipped={len(_skipped)} ' + f'summary_channel=#{SUMMARY_CHANNEL}') + + +# 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/ae_deal_handoff_002__long/reward.py b/ae_deal_handoff_002__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..0cfbedb41eb184c1b12aef0619a611922d0a1f97 --- /dev/null +++ b/ae_deal_handoff_002__long/reward.py @@ -0,0 +1,825 @@ +""" +Reward Script: T-hard — Hand off qualified opportunities (H16) +Task ID: ae_deal_handoff_002__long +Mocks: salesforce_mock,trello_mock,gmail_mock,slack_mock + +A sales-ops rep hands off newly-qualified Salesforce Closed-Won opportunities +to the delivery team. For each qualifying opp the rep tiers by amount and takes +tier-appropriate actions across SF (owner change, + kickoff task on Tier-1), +Trello (Handoff card w/ tier label + due date), Gmail (label + kickoff email +on Tier-1 only) and Slack (summary post + pin). + +DEVIATION FROM DESIGN SPEC: the salesforce_mock Opportunity.stage enum has NO +'Onboarding' value; per the design's construction note, the graded Salesforce +transition is Owner -> 'Delivery Lead' for every tier. Stage is not graded. + +Answer key (sole source of truth): salesforce.initial_state._task_adapter has +task_opps + expected (list of dicts w/ opp_id, tier, requires_action, +target_owner_name, card_title, card_label, card_due, task_subject, label_name, +email_subject, account_email, ...). The list is precomputed in initial_setup. + +SCORING CONTRACT (HARD_TASK_PIPELINE §5): every component ∈ [0,1], weights sum +to exactly 1.0, NO subtracted penalties. Leak (re-owning an already-handed-off +opp / handing off a not-won opp / spurious Delivery-Queue card / spurious +kickoff activity) is punished by *precision* inside the F1 / decision-set +components — it lowers them toward 0 but total stays in [0,1]. + +Weights (sum = 1.00): + 0.24 SF owner F1 — true = {opp_id : opps requiring action}, pred = + {opp_id : opps whose ownerId != injection ownerId AND + current owner name == 'Delivery Lead'}. FP = re-owning + a not-won or already-handed-off opp. + 0.24 handoff card F1 — NEW Trello cards on 'Delivery Queue' vs the + card_title set (diff by card id; F1). + 0.14 card label+due — among MATCHED cards, frac w/ correct tier-label + (by board-label NAME) AND dueDate == card_due (day). + 0.12 Tier-1 kickoff — F1 over the Tier-1 'Kickoff - ' subject set of + task NEW activities[] entries (diff by id). + 0.10 gmail label — frac of Tier-1 accounts w/ their inbound email + carrying the 'Handoff' label (by NAME). + 0.06 Tier-1 email — frac of Tier-1 with a SENT 'Kickoff for ' email + to the account contact address. + 0.05 slack post — a non-empty #delivery message containing a digit. + 0.05 slack pin — that summary is PINNED (gated on a real posted msg). +do-nothing -> 0.0 ; perfect -> 1.0 ; leak -> < 1.0 (via precision, never < 0). +""" +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 = {'salesforce': 'http://28.7.184.198:8175', 'trello': 'http://28.7.184.198:8182', + 'gmail': 'http://28.7.184.198:8138', '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 helpers === +def _gmail_sent_emails(gmail_state): + """All emails that look 'sent' (folder sent/outbox OR isSent/sentAt flags).""" + out = [] + if not isinstance(gmail_state, dict): + return out + for e in (gmail_state.get('emails', []) or []): + if not isinstance(e, dict): + continue + folder = norm(e.get('folder')) + if folder in ('sent', 'sentitems', 'sent items', 'outbox'): + out.append(e) + continue + if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'): + out.append(e) + if out: + return out + for key in ('sent', 'sentEmails', 'outbox'): + items = gmail_state.get(key, []) + if isinstance(items, list): + out.extend(x for x in items if isinstance(x, dict)) + return out + + +def _email_to_addrs(e): + """Normalized set of recipient email addresses on an email.""" + out = set() + to = e.get('to') + if isinstance(to, list): + for x in to: + if isinstance(x, dict): + a = x.get('email') or x.get('name') + else: + a = x + if a: + out.add(norm(a)) + elif isinstance(to, dict): + a = to.get('email') or to.get('name') + if a: + out.add(norm(a)) + elif to: + out.add(norm(to)) + return out + + +def _email_from_addr(e): + frm = e.get('from') + if isinstance(frm, dict): + return norm(frm.get('email') or frm.get('name')) + return norm(frm) + + +def _raw_date_part(s): + """Literal wall-clock date 'YYYY-MM-DD' (strip Z / tz offset, take date).""" + if not s: + return '' + t = str(s).strip() + if 'T' not in t: + return t[:10] + return t.split('T', 1)[0] + + +def _due_day_matches(due_val, target_day): + """True if the card dueDate falls on target_day ('YYYY-MM-DD') under EITHER the + literal wall-clock reading OR the UTC->UTC+8 conversion (robust to whatever the + trello card-modal date input serialized: naive-local, UTC midnight, or offset).""" + target = norm(target_day) + if not target or not due_val: + return False + if norm(_raw_date_part(due_val)) == target: + return True + if date_key(due_val) == target: # UTC->local (UTC+8) reading + return True + dt = parse_as_utc(due_val) # UTC-as-is reading + if dt is not None and dt.date().isoformat() == target: + return True + return False + + +def _label_name_set(email, label_id_to_name): + """Resolve an email's label ids/names to a set of normalized label NAMES.""" + out = set() + labels = email.get('labels') + if not isinstance(labels, list): + return out + for lab in labels: + if isinstance(lab, dict): + nm = lab.get('name') or lab.get('id') + if nm: + out.add(norm(label_id_to_name.get(nm, nm))) + else: + out.add(norm(label_id_to_name.get(lab, lab))) + return out + + +# === Task-specific reward === +# +# Ground truth lives in salesforce.initial_state._task_adapter.expected (a list +# of dicts, one per opportunity): +# opp_id (str) -> Salesforce Opportunity id +# opp_name (str) -> Opportunity name +# account (str) / account_email (str) +# amount (int) +# stage_at_injection (str) -> 'Closed Won' | 'Negotiation' +# owner_id_at_injection (str) -> ADMIN_OWNER_ID (change) or DELIVERY (skip) +# tier (str|None) -> 'Tier-1'|'Tier-2'|'Tier-3' (only for Won) +# requires_action (bool) -> Won AND owner != Delivery Lead +# target_owner_name (str|None) -> 'Delivery Lead' (all requires_action opps) +# card_title (str|None) -> 'Handoff: ' (all requires_action opps) +# card_label (str|None) -> 'Tier-1'|'Tier-2'|'Tier-3' +# card_due (str|None) -> 'YYYY-MM-DD' (today+3/5/7) +# task_subject (str|None) -> 'Kickoff - ' (Tier-1 only) +# label_name (str|None) -> 'Handoff' (Tier-1 only; Gmail label by NAME) +# email_subject (str|None) -> 'Kickoff for ' (Tier-1 only) + +WEIGHT_OWNER = 0.24 # SF opp owner F1 (opps requiring change vs opps re-owned to Delivery Lead) +WEIGHT_CARD = 0.24 # handoff card F1 (NEW Trello cards on Delivery Queue vs card_title set) +WEIGHT_CARDMETA = 0.14 # among matched cards, correct tier-label (by NAME) + due date +WEIGHT_TASK = 0.12 # Tier-1 kickoff activity F1 (NEW activities[] w/ 'Kickoff -' subject) +WEIGHT_GLABEL = 0.10 # Tier-1 account inbound email carries 'Handoff' label (by NAME) +WEIGHT_EMAIL = 0.06 # Tier-1 SENT 'Kickoff for ' email to account contact +WEIGHT_POST = 0.05 # slack #delivery summary posted +WEIGHT_PIN = 0.05 # that summary pinned +assert abs((WEIGHT_OWNER + WEIGHT_CARD + WEIGHT_CARDMETA + WEIGHT_TASK + + WEIGHT_GLABEL + WEIGHT_EMAIL + WEIGHT_POST + WEIGHT_PIN) - 1.0) < 1e-9 + + +def reward(go): + # === Salesforce state (owner + kickoff task) === + sf = go('salesforce') + sf_i = sf.get('initial_state', {}) or {} + sf_c = sf.get('current_state', {}) or {} + adapter = sf_i.get('_task_adapter', {}) if isinstance(sf_i.get('_task_adapter'), dict) else {} + expected = adapter.get('expected', []) or [] + delivery_owner_name = norm(adapter.get('delivery_owner_name') or 'Delivery Lead') + delivery_list_id = adapter.get('delivery_list_id') + delivery_list_name = norm(adapter.get('delivery_list_name') or 'Delivery Queue') + summary_channel = adapter.get('summary_channel') or 'delivery' + + opps_i_by_id = by_id(sf_i.get('opportunities') or [], 'opportunityId') + opps_c_by_id = by_id(sf_c.get('opportunities') or [], 'opportunityId') + + # After _materialize_salesforce, each opp payload carries an 'ownerName' + # convenience field derived from users[]. Fall back to the users[] map. + owner_name_map = _owner_name_map(sf_c) + + def _owner_name_of(opp): + if not isinstance(opp, dict): + return '' + # Prefer materialized ownerName; else look up. + n = norm(opp.get('ownerName') or '') + if n: + return n + return norm(owner_name_map.get(opp.get('ownerId'), '')) + + require_action = [e for e in expected if e.get('requires_action')] + tier1 = [e for e in require_action if norm(e.get('tier') or '') == 'tier-1'] + skipped = [e for e in expected if not e.get('requires_action')] + n_action = len(require_action) + n_tier1 = len(tier1) + + # --- Component 1 (0.24): SF owner F1 --- + # TRUE = { opp_id : requires_action } + # PRED = { opp_id : opp whose current owner == 'Delivery Lead' AND + # whose ownerId differs from injection ownerId } + true_owner_ids = {e['opp_id'] for e in require_action} + pred_owner_ids = set() + for oid, cur in opps_c_by_id.items(): + init = opps_i_by_id.get(oid) or {} + if norm(_owner_name_of(cur)) == delivery_owner_name and cur.get('ownerId') != init.get('ownerId'): + pred_owner_ids.add(oid) + owner_f1 = f1(true_owner_ids, pred_owner_ids) + s_owner = WEIGHT_OWNER * owner_f1 + + # --- Component 4 (0.12): Tier-1 kickoff activity F1 (NEW activities) --- + acts_i = sf_i.get('activities') or [] + acts_c = sf_c.get('activities') or [] + initial_act_ids = {a.get('activityId') for a in acts_i if isinstance(a, dict)} + new_acts = [a for a in acts_c if isinstance(a, dict) and a.get('activityId') not in initial_act_ids] + true_task_subjects = {norm(e.get('task_subject') or '') for e in tier1 + if e.get('task_subject')} + pred_task_subjects = set() + tier1_ids = {e['opp_id'] for e in tier1} + for a in new_acts: + subj = norm(a.get('subject') or '') + if not subj: + continue + # Only credit activities related to a Tier-1 opp (extra Kickoff cards + # attached to random opps count as false positives via the F1 pred set). + rel_id = a.get('relatedToId') + if rel_id and rel_id not in tier1_ids and rel_id in opps_i_by_id: + # Attached to a non-Tier-1 opp -> spurious. + pred_task_subjects.add(subj + f'@{rel_id}') # tag-different + continue + pred_task_subjects.add(subj) + task_f1 = f1(true_task_subjects, pred_task_subjects) + s_task = WEIGHT_TASK * task_f1 + + # === Trello state (handoff cards) === + trello = go('trello') + tr_i = trello.get('initial_state', {}) or {} + tr_c = trello.get('current_state', {}) or {} + cards_i = tr_i.get('cards', {}) if isinstance(tr_i.get('cards'), dict) else {} + cards_c = tr_c.get('cards', {}) if isinstance(tr_c.get('cards'), dict) else {} + lists_c = tr_c.get('lists', {}) if isinstance(tr_c.get('lists'), dict) else {} + boards_c = tr_c.get('boards', {}) if isinstance(tr_c.get('boards'), dict) else {} + + # Board label NAME -> id (union over all boards). + label_name_to_id = {} + for b in boards_c.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')) + + # Delivery Queue list id — prefer adapter's delivery_list_id; fallback by title. + dq_list_id = None + if delivery_list_id and isinstance(lists_c.get(delivery_list_id), dict): + dq_list_id = delivery_list_id + if dq_list_id is None: + for lid, lst in lists_c.items(): + if isinstance(lst, dict) and norm(lst.get('title') or lst.get('name')) == delivery_list_name: + dq_list_id = lid + break + + initial_card_ids = set(cards_i.keys()) + dq_card_ids = [] + if dq_list_id is not None and isinstance(lists_c.get(dq_list_id), dict): + dq_card_ids = list(lists_c[dq_list_id].get('cardIds') or []) + new_dq_cards = [cards_c[cid] for cid in dq_card_ids + if cid not in initial_card_ids and isinstance(cards_c.get(cid), dict)] + + # --- Component 2 (0.24): handoff card F1 --- + true_titles = {norm(e.get('card_title') or '') for e in require_action + if e.get('card_title')} + pred_titles = {norm(c.get('title') or '') for c in new_dq_cards if c.get('title')} + card_f1 = f1(true_titles, pred_titles) + s_card = WEIGHT_CARD * card_f1 + + # Match new cards back to expected rows by title. + matched = [] # (card, expected_row) + for e in require_action: + want_title = norm(e.get('card_title') or '') + if not want_title: + continue + for c in new_dq_cards: + if norm(c.get('title') or '') == want_title: + matched.append((c, e)) + break + + # --- Component 3 (0.14): matched cards carry correct tier-label + due --- + meta_ok = 0 + meta_flags = [] + for c, e in matched: + want_label = norm(e.get('card_label') or '') + want_label_id = label_name_to_id.get(want_label) + label_hit = bool(want_label_id) and want_label_id in (c.get('labelIds') or []) + want_due = e.get('card_due') + got_due = c.get('dueDate') + due_hit = _due_day_matches(got_due, want_due) + ok = label_hit and due_hit + meta_ok += int(ok) + meta_flags.append(f"{e.get('opp_id')}=L{int(label_hit)}D{int(due_hit)}") + s_cardmeta = WEIGHT_CARDMETA * frac(meta_ok, len(matched)) + + # === Gmail state (Tier-1 label + kickoff email) === + gmail = go('gmail') + gmail_i = gmail.get('initial_state', {}) or {} + gmail_c = gmail.get('current_state', {}) or {} + emails_c = [em for em in (gmail_c.get('emails', []) or []) if isinstance(em, dict)] + gmail_id_to_name = {} + for lab in list(gmail_i.get('labels', []) or []) + list(gmail_c.get('labels', []) or []): + if isinstance(lab, dict) and lab.get('id'): + gmail_id_to_name[lab['id']] = lab.get('name') or lab['id'] + + # --- Component 5 (0.10): Tier-1 account inbound email carries 'Handoff' label --- + glabel_ok = 0 + glabel_flags = [] + for e in tier1: + cust = norm(e.get('account_email') or '') + want_label = norm(e.get('label_name') or '') + ok = bool(cust) and bool(want_label) and any( + _email_from_addr(em) == cust and norm(em.get('folder')) != 'sent' + and want_label in _label_name_set(em, gmail_id_to_name) + for em in emails_c + ) + glabel_ok += int(ok) + glabel_flags.append(f"{e.get('opp_id')}={'Y' if ok else 'N'}") + s_glabel = WEIGHT_GLABEL * frac(glabel_ok, n_tier1) + + # --- Component 6 (0.06): Tier-1 SENT 'Kickoff for ' email --- + sent_emails = _gmail_sent_emails(gmail_c) + email_ok = 0 + email_flags = [] + for e in tier1: + cust = norm(e.get('account_email') or '') + want_subj = norm(e.get('email_subject') or '') + ok = bool(cust) and any( + cust in _email_to_addrs(em) and want_subj in norm(em.get('subject') or '') + for em in sent_emails + ) + email_ok += int(ok) + email_flags.append(f"{e.get('opp_id')}={'Y' if ok else 'N'}") + s_email = WEIGHT_EMAIL * frac(email_ok, n_tier1) + + # === Slack state (post + pin) === + slack = go('slack') + scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + dm_msgs = _slack_channel_messages(scur, summary_channel) + + def _is_summary(m): + text = (_msg_text(m) or '').strip() + return bool(text) and bool(re.search(r'\d', text)) + + post_ok = any(_is_summary(m) for m in dm_msgs if isinstance(m, dict)) + dm_ch = None + for ch in (scur.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel): + dm_ch = ch + break + pinned = (dm_ch.get('pinnedMessages') or []) if isinstance(dm_ch, dict) else [] + pinned_ids = set() + for pm in pinned: + pid = pm.get('messageId') or pm.get('id') if isinstance(pm, dict) else pm + if pid is not None: + pinned_ids.add(norm(pid)) + msg_ids = {norm(m.get('messageId') or m.get('id')) for m in dm_msgs if isinstance(m, dict)} + pin_ok = bool(post_ok and (pinned_ids & msg_ids)) + s_post = WEIGHT_POST * (1.0 if post_ok else 0.0) + s_pin = WEIGHT_PIN * (1.0 if pin_ok else 0.0) + + score = (s_owner + s_card + s_cardmeta + s_task + + s_glabel + s_email + s_post + s_pin) + + print( + 'DEBUG_9e3cf2fc ' + f'expected={len(expected)} require_action={n_action} tier1={n_tier1} ' + f'skipped={len(skipped)} ' + f'true_owners={len(true_owner_ids)} pred_owners={len(pred_owner_ids)} ' + f'owner_f1={round(owner_f1, 4)} ' + f'true_cards={len(true_titles)} pred_cards={len(pred_titles)} ' + f'card_f1={round(card_f1, 4)} ' + f'matched={len(matched)} cardmeta={meta_ok}/{len(matched)}[{",".join(meta_flags)}] ' + f'true_tasks={len(true_task_subjects)} pred_tasks={len(pred_task_subjects)} ' + f'task_f1={round(task_f1, 4)} ' + f'glabel={glabel_ok}/{n_tier1}[{",".join(glabel_flags)}] ' + f'email={email_ok}/{n_tier1}[{",".join(email_flags)}] sent={len(sent_emails)} ' + f'slack_post={post_ok} slack_pin={pin_ok} ' + f's_owner={round(s_owner, 4)} s_card={round(s_card, 4)} ' + f's_cardmeta={round(s_cardmeta, 4)} s_task={round(s_task, 4)} ' + f's_glabel={round(s_glabel, 4)} s_email={round(s_email, 4)} ' + f's_post={round(s_post, 4)} s_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/calc_income_statement_001__long/.PLACEHOLDER b/calc_income_statement_001__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/calc_income_statement_001__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_income_statement_001__long/10da84b0-f0cf-58ff-b185-1c101d3b8b00_IncomeStatement2_1.xlsx b/calc_income_statement_001__long/10da84b0-f0cf-58ff-b185-1c101d3b8b00_IncomeStatement2_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e44fbd80c2c1c581c52fa221d857ce5540a08433 Binary files /dev/null and b/calc_income_statement_001__long/10da84b0-f0cf-58ff-b185-1c101d3b8b00_IncomeStatement2_1.xlsx differ diff --git a/calc_income_statement_001__long/350e50bf-8624-51bc-91b7-a8dd0462e518_IncomeStatement2_2.xlsx b/calc_income_statement_001__long/350e50bf-8624-51bc-91b7-a8dd0462e518_IncomeStatement2_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e44fbd80c2c1c581c52fa221d857ce5540a08433 Binary files /dev/null and b/calc_income_statement_001__long/350e50bf-8624-51bc-91b7-a8dd0462e518_IncomeStatement2_2.xlsx differ diff --git a/calc_income_statement_001__long/4429656d-69b9-58f3-af62-b51df1b7a682_IncomeStatement2_4.xlsx b/calc_income_statement_001__long/4429656d-69b9-58f3-af62-b51df1b7a682_IncomeStatement2_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e44fbd80c2c1c581c52fa221d857ce5540a08433 Binary files /dev/null and b/calc_income_statement_001__long/4429656d-69b9-58f3-af62-b51df1b7a682_IncomeStatement2_4.xlsx differ diff --git a/calc_income_statement_001__long/5_IncomeStatement2_gt1_1.xlsx b/calc_income_statement_001__long/5_IncomeStatement2_gt1_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..bb279455f1dbd77c9c3f2431de9d32097beb04b0 Binary files /dev/null and b/calc_income_statement_001__long/5_IncomeStatement2_gt1_1.xlsx differ diff --git a/calc_income_statement_001__long/5_IncomeStatement2_gt1_2.xlsx b/calc_income_statement_001__long/5_IncomeStatement2_gt1_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..bb279455f1dbd77c9c3f2431de9d32097beb04b0 Binary files /dev/null and b/calc_income_statement_001__long/5_IncomeStatement2_gt1_2.xlsx differ diff --git a/calc_income_statement_001__long/5_IncomeStatement2_gt1_3.xlsx b/calc_income_statement_001__long/5_IncomeStatement2_gt1_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..bb279455f1dbd77c9c3f2431de9d32097beb04b0 Binary files /dev/null and b/calc_income_statement_001__long/5_IncomeStatement2_gt1_3.xlsx differ diff --git a/calc_income_statement_001__long/5_IncomeStatement2_gt1_4.xlsx b/calc_income_statement_001__long/5_IncomeStatement2_gt1_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..bb279455f1dbd77c9c3f2431de9d32097beb04b0 Binary files /dev/null and b/calc_income_statement_001__long/5_IncomeStatement2_gt1_4.xlsx differ diff --git a/calc_income_statement_001__long/5_IncomeStatement2_gt1_5.xlsx b/calc_income_statement_001__long/5_IncomeStatement2_gt1_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..bb279455f1dbd77c9c3f2431de9d32097beb04b0 Binary files /dev/null and b/calc_income_statement_001__long/5_IncomeStatement2_gt1_5.xlsx differ diff --git a/calc_income_statement_001__long/876296d5-884d-51ad-b5dd-285374e43ac4_IncomeStatement2_5.xlsx b/calc_income_statement_001__long/876296d5-884d-51ad-b5dd-285374e43ac4_IncomeStatement2_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e44fbd80c2c1c581c52fa221d857ce5540a08433 Binary files /dev/null and b/calc_income_statement_001__long/876296d5-884d-51ad-b5dd-285374e43ac4_IncomeStatement2_5.xlsx differ diff --git a/calc_income_statement_001__long/93be5864-b16f-5f70-8d80-1a515dedf794_IncomeStatement2_3.xlsx b/calc_income_statement_001__long/93be5864-b16f-5f70-8d80-1a515dedf794_IncomeStatement2_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e44fbd80c2c1c581c52fa221d857ce5540a08433 Binary files /dev/null and b/calc_income_statement_001__long/93be5864-b16f-5f70-8d80-1a515dedf794_IncomeStatement2_3.xlsx differ diff --git a/calc_sales_rep_002__long/.PLACEHOLDER b/calc_sales_rep_002__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/calc_sales_rep_002__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_sales_rep_002__long/0b920aed-a86f-552f-8c4e-4230d20fb019_SalesRep_3.xlsx b/calc_sales_rep_002__long/0b920aed-a86f-552f-8c4e-4230d20fb019_SalesRep_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..81746ae1fd10aa93fc43172b1fe18d0fdff50b15 Binary files /dev/null and b/calc_sales_rep_002__long/0b920aed-a86f-552f-8c4e-4230d20fb019_SalesRep_3.xlsx differ diff --git a/calc_sales_rep_002__long/3_SalesRep_gt1_1.xlsx b/calc_sales_rep_002__long/3_SalesRep_gt1_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0a2e477c87b1ece36299e57b2cefa1bcb8639c94 Binary files /dev/null and b/calc_sales_rep_002__long/3_SalesRep_gt1_1.xlsx differ diff --git a/calc_sales_rep_002__long/3_SalesRep_gt1_2.xlsx b/calc_sales_rep_002__long/3_SalesRep_gt1_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0a2e477c87b1ece36299e57b2cefa1bcb8639c94 Binary files /dev/null and b/calc_sales_rep_002__long/3_SalesRep_gt1_2.xlsx differ diff --git a/calc_sales_rep_002__long/3_SalesRep_gt1_3.xlsx b/calc_sales_rep_002__long/3_SalesRep_gt1_3.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0a2e477c87b1ece36299e57b2cefa1bcb8639c94 Binary files /dev/null and b/calc_sales_rep_002__long/3_SalesRep_gt1_3.xlsx differ diff --git a/calc_sales_rep_002__long/3_SalesRep_gt1_4.xlsx b/calc_sales_rep_002__long/3_SalesRep_gt1_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0a2e477c87b1ece36299e57b2cefa1bcb8639c94 Binary files /dev/null and b/calc_sales_rep_002__long/3_SalesRep_gt1_4.xlsx differ diff --git a/calc_sales_rep_002__long/3_SalesRep_gt1_5.xlsx b/calc_sales_rep_002__long/3_SalesRep_gt1_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0a2e477c87b1ece36299e57b2cefa1bcb8639c94 Binary files /dev/null and b/calc_sales_rep_002__long/3_SalesRep_gt1_5.xlsx differ diff --git a/calc_sales_rep_002__long/5e509850-8212-5d6a-958f-c2d16aee6ceb_SalesRep_4.xlsx b/calc_sales_rep_002__long/5e509850-8212-5d6a-958f-c2d16aee6ceb_SalesRep_4.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..81746ae1fd10aa93fc43172b1fe18d0fdff50b15 Binary files /dev/null and b/calc_sales_rep_002__long/5e509850-8212-5d6a-958f-c2d16aee6ceb_SalesRep_4.xlsx differ diff --git a/calc_sales_rep_002__long/6c32f05d-1532-5354-a3db-ac954dd7d2ca_SalesRep_1.xlsx b/calc_sales_rep_002__long/6c32f05d-1532-5354-a3db-ac954dd7d2ca_SalesRep_1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..81746ae1fd10aa93fc43172b1fe18d0fdff50b15 Binary files /dev/null and b/calc_sales_rep_002__long/6c32f05d-1532-5354-a3db-ac954dd7d2ca_SalesRep_1.xlsx differ diff --git a/calc_sales_rep_002__long/dd7e65b9-bfb4-542a-adf9-13c4153016fc_SalesRep_2.xlsx b/calc_sales_rep_002__long/dd7e65b9-bfb4-542a-adf9-13c4153016fc_SalesRep_2.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..81746ae1fd10aa93fc43172b1fe18d0fdff50b15 Binary files /dev/null and b/calc_sales_rep_002__long/dd7e65b9-bfb4-542a-adf9-13c4153016fc_SalesRep_2.xlsx differ diff --git a/calc_sales_rep_002__long/e5d3b713-bd13-5796-83bc-ab47351ba44c_SalesRep_5.xlsx b/calc_sales_rep_002__long/e5d3b713-bd13-5796-83bc-ab47351ba44c_SalesRep_5.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..81746ae1fd10aa93fc43172b1fe18d0fdff50b15 Binary files /dev/null and b/calc_sales_rep_002__long/e5d3b713-bd13-5796-83bc-ab47351ba44c_SalesRep_5.xlsx differ diff --git a/csm_training_rate_005/_cua_gym_vm_bridge.sh b/csm_training_rate_005/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csm_training_rate_005/_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/csm_training_rate_005/reward_label.json b/csm_training_rate_005/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..5433d18373376a144ff353cedaddb35c58050686 --- /dev/null +++ b/csm_training_rate_005/reward_label.json @@ -0,0 +1,58 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23/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:26:12", + "label": { + "task_id": "csm_training_rate_005", + "domain": "mock_websites", + "summary": "验证用户在 Google Sheets 中计算完成率为75%,在 Salesforce 中将 TechVentures 商机标记为 Closed Won,并在 Slack #general 频道发送新消息及报告75%完成率", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_sheets_mock", + "salesforce_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "completion rate computed as 75%", + "weight": 0.4, + "description": "检查 Google Sheets 单元格 B8 的值或计算结果是否包含75", + "check_logic": "读取 google_sheets_mock 的 sheets[0].data.B8,检查 value 或 computed 字段的字符串表示中是否包含 '75'", + "pass_condition": "B8 单元格的 value 或 computed 包含 '75'" + }, + { + "name": "TechVentures opp -> Closed Won", + "weight": 0.3, + "description": "检查 Salesforce 中 opportunityId 为 o1 的商机阶段是否为 Closed Won", + "check_logic": "在 salesforce_mock 的 opportunities 列表中查找 opportunityId == 'o1' 的对象,检查其 stage 字段是否等于 'Closed Won'", + "pass_condition": "opportunityId 为 'o1' 的商机 stage 为 'Closed Won'" + }, + { + "name": "slack_new_msg", + "weight": 0.1, + "description": "检查 Slack #general 频道是否有 user_1 发送的新消息", + "check_logic": "读取 slack_mock 的 messages.general,排除 SEED 中已有的消息,筛选 senderId == 'user_1' 的消息,检查列表是否非空", + "pass_condition": "#general 中存在 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息" + }, + { + "name": "reports the 75% rate", + "weight": 0.2, + "description": "检查 Slack #general 频道 user_1 的新消息内容是否报告了75%的完成率", + "check_logic": "读取 slack_mock 的 messages.general 中 user_1 的新消息,拼接内容转小写,检查是否包含 '75%'、'75 percent' 或 '75'", + "pass_condition": "user_1 在 #general 发送的新消息内容(小写)包含 '75%'、'75 percent' 或 '75'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到4位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或 sid 为空时打印 CRITICAL 并返回 0.0", + "从任一 mock 服务(google_sheets_mock、salesforce_mock、slack_mock)拉取状态失败时打印 CRITICAL 并返回 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_sheets_mock、salesforce_mock、slack_mock 发送请求获取当前状态。接着按顺序检查四个组件:1)Google Sheets 单元格 B8 是否包含75;2)Salesforce 中 o1 商机是否为 Closed Won;3)Slack #general 是否有 user_1 的新消息;4)该新消息是否提及75%完成率。每个组件通过则累加对应分数,不通过则仅打印 FAIL 不加分。最终总分经 min 钳制和 round 后输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Task ID: f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23(从 docstring 中提取)\n - Domain: mock_websites(从 docstring 中提取)\n - Mocks: google_sheets_mock, salesforce_mock, slack_mock\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:google_sheets_mock, salesforce_mock, slack_mock\n - SEED 用于 slack 消息去重\n\n3. 评分组件:\n - c0: 0.4 分 - google_sheets_mock 中 sheets[0].data.B8 的 value 或 computed 包含 '75'\n - c1: 0.3 分 - salesforce_mock 中 opportunities 里 opportunityId 为 'o1' 的 stage 是 'Closed Won'\n - c2: 0.1 分 - slack_mock 中 #general 频道有 user_1 发送的新消息(不在 seed 中)\n - c3: 0.2 分 - slack_mock 中 #general 频道 user_1 发送的新消息内容包含 '75%' 或 '75 percent' 或 '75'\n\n4. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加逻辑\n\n5. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n6. 是否是占位脚本:\n - 不是,有具体的检查逻辑\n\n7. confidence:\n - 1.0,因为逻辑清晰\n\n现在构建 JSON:\n\ntask_id: \"f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23\"\ndomain: \"mock_websites\"\nsummary: \"验证用户在 Google Sheets 中计算完成率为75%,在 Salesforce 中将 TechVentures 商机标记为 Closed Won,并在 Slack #general 频道发送包含75%完成率的新消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"google_sheets_mock\", \"salesforce_mock\", \"slack_mock\"]\n\nscoring_components:\n1. name: \"completion rate computed as 75%\", weight: 0.4\n description: \"检查 Google Sheets 单元格 B8 的值或计算结果是否包含75\"\n check_logic: \"读取 google_sheets_mock 的 sheets[0].data.B8,检查 value 或 computed 字段的字符串表示中是否包含 '75'\"\n pass_condition: \"B8 单元格的 value 或 computed 包含 '75'\"\n\n2. name: \"TechVentures opp -> Closed Won\", weight: 0.3\n description: \"检查 Salesforce 中 opportunityId 为 o1 的商机阶段是否为 Closed Won\"\n check_logic: \"在 salesforce_mock 的 opportunities 列表中查找 opportunityId == 'o1' 的对象,检查其 stage 字段是否等于 'Closed Won'\"\n pass_condition: \"opportunityId 为 'o1' 的商机 stage 为 'Closed Won'\"\n\n3. name: \"slack_new_msg\", weight: 0.1\n description: \"检查 Slack #general 频道是否有 user_1 发送的新消息\"\n check_logic: \"读取 slack_mock 的 messages.general,排除 SEED 中已有的消息,筛选 senderId == 'user_1' 的消息,检查列表是否非空\"\n pass_condition: \"#general 中存在 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息\"\n\n4. name: \"reports the 75% rate\", weight: 0.2\n description: \"检查 Slack #general 频道 user_1 的新消息内容是否报告了75%的完成率\"\n check_logic: \"读取 slack_mock 的 messages.general 中 user_1 的新消息,拼接内容转小写,检查是否包含 '75%'、'75 percent' 或 '75'\"\n pass_condition: \"user_1 在 #general 发送的新消息内容(小写)包含 '75%'、'75 percent' 或 '75'\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到4位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或 sid 为空时打印 CRITICAL 并返回 0.0\",\n \"从任一 mock 服务(google_sheets_mock、salesforce_mock、slack_mock)拉取状态失败时打印 CRITICAL 并返回 0.0\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_sheets_mock、salesforce_mock、slack_mock 发送请求获取当前状态。接着按顺序检查四个组件:1)Google Sheets 单元格 B8 是否包含75;2)Salesforce 中 o1 商机是否为 Closed Won;3)Slack #general 是否有 user_1 的新消息;4)该新消息是否提及75%完成率。每个组件通过则累加对应分数,不通过则仅打印 FAIL 不加分。最终总分经 min 钳制和 round 后输出。\"\n\nconfidence: 1.0\n\n确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。 {\"task_id\":\"f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Google Sheets 中计算完成率为75%,在 Salesforce 中将 TechVentures 商机标记为 Closed Won,并在 Slack #general 频道发送新消息及报告75%完成率\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock\",\"salesforce_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"completion rate computed as 75%\",\"weight\":0.4,\"description\":\"检查 Google Sheets 单元格 B8 的值或计算结果是否包含75\",\"check_logic\":\"读取 google_sheets_mock 的 sheets[0].data.B8,检查 value 或 computed 字段的字符串表示中是否包含 '75'\",\"pass_condition\":\"B8 单元格的 value 或 computed 包含 '75'\"},{\"name\":\"TechVentures opp -> Closed Won\",\"weight\":0.3,\"description\":\"检查 Salesforce 中 opportunityId 为 o1 的商机阶段是否为 Closed Won\",\"check_logic\":\"在 salesforce_mock 的 opportunities 列表中查找 opportunityId == 'o1' 的对象,检查其 stage 字段是否等于 'Closed Won'\",\"pass_condition\":\"opportunityId 为 'o1' 的商机 stage 为 'Closed Won'\"},{\"name\":\"slack_new_msg\",\"weight\":0.1,\"description\":\"检查 Slack #general 频道是否有 user_1 发送的新消息\",\"check_logic\":\"读取 slack_mock 的 messages.general,排除 SEED 中已有的消息,筛选 senderId == 'user_1' 的消息,检查列表是否非空\",\"pass_condition\":\"#general 中存在 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息\"},{\"name\":\"reports the 75% rate\",\"weight\":0.2,\"description\":\"检查 Slack #general 频道 user_1 的新消息内容是否报告了75%的完成率\",\"check_logic\":\"读取 slack_mock 的 messages.general 中 user_1 的新消息,拼接内容转小写,检查是否包含 '75%'、'75 percent' 或 '75'\",\"pass_condition\":\"user_1 在 #general 发送的新消息内容(小写)包含 '75%'、'75 percent' 或 '75'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到4位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或 sid 为空时打印 CRITICAL 并返回 0.0\",\"从任一 mock 服务(google_sheets_mock、salesforce_mock、slack_mock)拉取状态失败时打印 CRITICAL 并返回 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_sheets_mock、salesforce_mock、slack_mock 发送请求获取当前状态。接着按顺序检查四个组件:1)Google Sheets 单元格 B8 是否包含75;2)Salesforce 中 o1 商机是否为 Closed Won;3)Slack #general 是否有 user_1 的新消息;4)该新消息是否提及75%完成率。每个组件通过则累加对应分数,不通过则仅打印 FAIL 不加分。最终总分经 min 钳制和 round 后输出。\",\"confidence\":1.0}" +} diff --git a/hr_midyear_review_007__long/_cua_gym_vm_bridge.sh b/hr_midyear_review_007__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/hr_midyear_review_007__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_midyear_review_007__long/initial_setup.py b/hr_midyear_review_007__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..adb87c61c969ad32cba85f0f435946370035e6f1 --- /dev/null +++ b/hr_midyear_review_007__long/initial_setup.py @@ -0,0 +1,794 @@ +""" +Initial Setup: W05 — HRBP performance review + conditional raise letters +Task ID: hr_midyear_review_007__long +Persona: HRBP Tara Singh +Mocks: workday_mock,docusign_mock,slack_mock,google_sheets_mock + +Ground-truth embedding (read by reward.py from initial_state): + - Workday reviews[*]._expected_rating on every status=='Pending Manager Review' + review managed by Tara — the 1..5 score the manager-review must submit + (decided by the goal-attainment rule, encoded ONLY as this answer key). + - reviews[*]._expected_envelope (bool) — true iff _expected_rating >= 4 + (Exceeds / Significantly Exceeds): those reports must get a DocuSign raise + letter. The conditional branch. + - reviews[*]._employee_name / _employee_email — the report's identity, so + reward can match the sent envelope's recipient loosely (name OR email). + +Observable outputs kept ABSENT at injection: + - all 10 pending reviews still have status=='Pending Manager Review' with the + DEFAULT ratingScore (3) untouched — the agent must open each and submit a + rating + comment (ADD_REVIEW_COMMENT → status 'Completed'). + - DocuSign has NO raise-letter envelope addressed to any qualifying employee + (only a reusable template + unrelated noise envelopes) — the agent must + create-from-template, set the employee as recipient, and Send. + - Google Sheet 'Performance Review Tracker' Rating column is blank on the 10 + report rows (only a worked example row is filled). + - Slack #hr channel has zero messages. +""" +import os +import shlex +import subprocess +import time +import uuid +import base64 + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# --------------------------------------------------------------------------- +# Builders +# --------------------------------------------------------------------------- +def employee(emp_id, name, title, dept='Engineering', dept_id='dept001', + manager_id='emp_tara', role='Employee'): + first = name.split()[0] + last = name.split()[-1] + uname = f'{first}.{last}'.lower() + return { + 'id': emp_id, 'name': name, + 'email': f'{uname}@acmecorp.com', + 'phone': '+1 (415) 555-0140', 'role': role, 'department': dept, + 'departmentId': dept_id, + 'avatar': f'https://ui-avatars.com/api/?name={first}+{last}&background=0875E1&color=fff&size=128', + 'managerId': manager_id, 'title': title, 'location': 'San Francisco, CA', + 'joinDate': '2021-05-10', 'employeeType': 'Full-Time', + 'birthday': '1990-01-01', 'workAnniversary': '2021-05-10', + } + + +def review(review_id, emp_id, period, status, self_comments, + manager_id='emp_tara', rating_score=None, rating='', + manager_comments='', completed_date=None, + expected_rating=None, expected_envelope=None, + employee_name=None, employee_email=None): + rec = { + 'reviewId': review_id, 'employeeId': emp_id, 'managerId': manager_id, + 'period': period, 'rating': rating, 'ratingScore': rating_score, + 'status': status, 'selfReviewComments': self_comments, + 'managerComments': manager_comments, 'comments': '', + 'completedDate': completed_date, + } + if expected_rating is not None: + rec['_expected_rating'] = expected_rating # hidden answer key + if expected_envelope is not None: + rec['_expected_envelope'] = expected_envelope + if employee_name is not None: + rec['_employee_name'] = employee_name + if employee_email is not None: + rec['_employee_email'] = employee_email + return rec + + +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'}} + + +# --------------------------------------------------------------------------- +# Rating rule (documented in instruction; encoded here ONLY as the embedded +# _expected_rating answer key, NOT re-derived in reward): +# Score each report's mid-year review on the 1..5 scale by goal attainment: +# 5 = significantly exceeded (beat every goal) +# 4 = exceeded (beat most goals) +# 3 = met expectations (delivered the agreed goals) +# 2 = partially met (missed some goals) +# 1 = did not meet (missed most goals) +# Conditional branch: send a DocuSign salary-increase letter ONLY to reports +# rated 4 or 5. +# --------------------------------------------------------------------------- +PERIOD = '2026 Mid-Year Review' + +TARA = { + 'id': 'emp_tara', 'name': 'Tara Singh', 'email': 'tara.singh@acmecorp.com', + 'phone': '+1 (415) 555-0100', 'role': 'Manager', 'department': 'Engineering', + 'departmentId': 'dept001', + 'avatar': 'https://ui-avatars.com/api/?name=Tara+Singh&background=7C3AED&color=fff&size=128', + 'managerId': 'emp_dir', 'title': 'HR Business Partner', + 'location': 'San Francisco, CA', 'joinDate': '2019-02-01', + 'employeeType': 'Full-Time', 'skills': ['Coaching', 'Comp Planning'], + 'birthday': '1986-07-19', 'workAnniversary': '2019-02-01', +} +DIRECTOR = { + 'id': 'emp_dir', 'name': 'Olivia Reyes', 'email': 'olivia.reyes@acmecorp.com', + 'phone': '+1 (415) 555-0101', 'role': 'Director', 'department': 'Engineering', + 'departmentId': 'dept001', + 'avatar': 'https://ui-avatars.com/api/?name=Olivia+Reyes&background=DB2777&color=fff&size=128', + 'managerId': None, 'title': 'Director of Engineering', + 'location': 'San Francisco, CA', 'joinDate': '2017-03-01', + 'employeeType': 'Full-Time', 'birthday': '1982-02-02', + 'workAnniversary': '2017-03-01', +} + +# (emp_id, name, title, expected_rating, self_assessment) +REPORTS = [ + ('emp_r1', 'Daniel Okafor', 'Senior Backend Engineer', 5, + 'Beat every one of my four quarterly goals: shipped the billing rewrite a ' + 'full sprint early, cut p99 latency 40%, and mentored three new hires who ' + 'are all ramped. Took on the on-call redesign on top of my roadmap.'), + ('emp_r2', 'Priya Nair', 'Product Designer', 3, + 'Delivered all of my agreed goals for the half: the design-system refresh ' + 'and two feature flows shipped on schedule. A solid, on-plan half with no ' + 'surprises.'), + ('emp_r3', 'Marcus Bell', 'Data Engineer', 4, + 'Exceeded most of my goals — the warehouse migration landed two weeks ' + 'early and I added the data-quality alerts that were not in scope. One ' + 'stretch goal (self-serve dashboards) slipped to next half.'), + ('emp_r4', 'Hana Kim', 'Frontend Engineer', 2, + 'Partially met my goals. The accessibility audit shipped, but I missed the ' + 'component-library deadline and the perf-budget goal carried over. A rough ' + 'half with the reorg churn.'), + ('emp_r5', 'Tom Becker', 'Staff SRE', 5, + 'Significantly exceeded: led the multi-region failover project to a clean ' + 'finish ahead of plan, drove incident MTTR down by half, and beat all ' + 'reliability targets. Also ran the company-wide game-day.'), + ('emp_r6', 'Grace Liu', 'QA Engineer', 3, + 'Met expectations across the board — cleared the regression backlog and ' + 'stood up the nightly e2e suite exactly as committed. On plan.'), + ('emp_r7', 'Samir Patel', 'Backend Engineer', 4, + 'Exceeded most goals: the payments API v2 shipped on time and I picked up ' + 'the fraud-rules service when a teammate left. Documentation goal was only ' + 'half done.'), + ('emp_r8', 'Elena Vasquez', 'Junior Engineer', 1, + 'Did not meet most of my goals this half. Onboarding took longer than ' + 'expected and two of my three committed features slipped; the third is ' + 'still in review. I need a stronger plan for next half.'), + ('emp_r9', 'Noah Schmidt', 'DevOps Engineer', 3, + 'Met my goals — migrated CI to the new runners and kept the platform ' + 'green. Delivered what was agreed, nothing beyond.'), + ('emp_r10', 'Aisha Mohammed', 'Senior Frontend Engineer', 4, + 'Exceeded most goals: led the design-system adoption across four squads ' + 'ahead of schedule and cut bundle size 30%. The i18n stretch goal slipped ' + 'a few weeks.'), +] + +EMPLOYEES = [TARA, DIRECTOR] +REVIEWS = [] +for emp_id, name, title, exp_rating, self_text in REPORTS: + emp = employee(emp_id, name, title) + EMPLOYEES.append(emp) + REVIEWS.append(review( + f'rev_{emp_id}', emp_id, PERIOD, 'Pending Manager Review', self_text, + manager_id='emp_tara', rating_score=3, # default, agent must set + expected_rating=exp_rating, + expected_envelope=(exp_rating >= 4), + employee_name=name, employee_email=emp['email'], + )) + +# ---- NOISE employees + reviews (no answer key, not scored) ---- +# n1: report of a DIFFERENT manager, still Pending Manager Review -> does NOT +# appear in Tara's "Reviews to give" list (managerId != Tara). Do not touch. +NOISE_EMP_1 = employee('emp_n1', 'Victor Ross', 'Marketing Analyst', + dept='Marketing', dept_id='dept003', + manager_id='emp_dir') +# n2: Tara's report but review ALREADY Completed -> no Complete-Review button. +NOISE_EMP_2 = employee('emp_n2', 'Fatima Zahra', 'Engineering Manager') +# n3: Tara's report but still Pending Self-Review -> not yet in her list. +NOISE_EMP_3 = employee('emp_n3', 'Liam Carter', 'Backend Engineer') +EMPLOYEES += [NOISE_EMP_1, NOISE_EMP_2, NOISE_EMP_3] + +REVIEWS += [ + review('rev_n1', 'emp_n1', PERIOD, 'Pending Manager Review', + 'Crushed the campaign analytics goals this half.', + manager_id='emp_dir'), # NOT Tara's report + review('rev_n2', 'emp_n2', PERIOD, 'Completed', + 'Led the platform team through the reorg and hit all goals.', + manager_id='emp_tara', rating_score=5, rating='Significantly Exceeds', + manager_comments='Outstanding leadership.', + completed_date='2026-06-20'), # already done + review('rev_n3', 'emp_n3', PERIOD, 'Pending Self-Review', + '', manager_id='emp_tara'), # self-review not submitted yet +] + +# Tara's own review (as an employee) — Completed, decoy in "My reviews" list. +REVIEWS.append(review('rev_tara', 'emp_tara', '2025 Annual Review', 'Completed', + 'Strong year partnering with engineering.', + manager_id='emp_dir', rating_score=4, + rating='Exceeds Expectations', + manager_comments='Great partner.', + completed_date='2026-01-15')) + +QUALIFYING = [r for r in REVIEWS if r.get('_expected_envelope')] +QUALIFYING_NAMES = [r['_employee_name'] for r in QUALIFYING] +print(f'Reports pending: {len(REPORTS)}; qualifying for raise letter: ' + f'{len(QUALIFYING)} -> {QUALIFYING_NAMES}') + +WORKDAY_STATE = { + 'currentUser': TARA, + 'employees': EMPLOYEES, + 'departments': [ + {'id': 'dept001', 'name': 'Engineering', 'headcount': 12, 'managerId': 'emp_dir'}, + {'id': 'dept003', 'name': 'Marketing', 'headcount': 4, 'managerId': 'emp_dir'}, + ], + 'timeEntries': [], + 'timeOffRequests': [], + 'timeOffBalance': {'vacation': 120, 'sick': 40, 'personal': 16}, + 'payroll': [], + 'benefits': {'employeeId': 'emp_tara', 'enrollmentStatus': 'Complete', + 'plans': [], 'dependents': []}, + 'reviews': REVIEWS, + 'goals': [], + 'tasks': [ + {'taskId': 't1', 'employeeId': 'emp_tara', 'type': 'Review', + 'subType': 'Performance Review', + 'description': 'Complete mid-year manager reviews for your reports', + 'status': 'Pending', 'dueDate': '2026-07-05', 'createdDate': '2026-06-25', + 'relatedId': None, 'initiator': 'HR System', + 'businessProcess': 'Mid-Year Performance Review', 'priority': 'High', + 'comments': []}, + ], + 'announcements': [ + {'id': 'a1', 'title': 'Mid-Year Reviews Due July 5', + 'date': '2026-06-25', 'content': 'Managers: submit ratings for all reports.', + 'category': 'HR', 'priority': 'High'}, + ], + 'notifications': [ + {'id': 'n1', 'type': 'task', 'title': 'Reviews to give', + 'message': 'You have pending manager reviews.', + 'timestamp': '2026-06-25T12:00:00.000Z', 'read': False, 'link': '/performance'}, + ], + 'clockStatus': {'isClockedIn': False, 'startTime': None}, +} + +# --------------------------------------------------------------------------- +# DocuSign — Tara is the sender. A reusable raise-letter TEMPLATE is provided +# (document + one signer role) so the agent can Use-a-Template -> set the +# employee as recipient -> Send through the 3-step /prepare flow. NO sent +# raise letter to any qualifying employee exists yet (only unrelated noise). +# --------------------------------------------------------------------------- +def _letter_data_url(): + """A self-contained SVG that renders as a real salary-increase letter + (white page, Acme letterhead, body copy, signature line). Used as the + template document's fileUrl so the /prepare canvas shows an actual letter + instead of a random stock photo. No network dependency.""" + svg = ( + "" + "" + "" + "Acme Corporation" + "Salary Increase Confirmation Letter" + "Dear Employee," + "We are pleased to confirm a merit-based increase to your " + "annual base salary," + "in recognition of your strong performance this review " + "cycle. The adjustment" + "takes effect at the start of the next pay period." + "Please review and sign below to acknowledge receipt of " + "this confirmation." + "Sincerely," + "Tara Singh — HR Business Partner" + "" + "Employee Signature" + "" + "Date Signed" + "" + ) + b64 = base64.b64encode(svg.encode('utf-8')).decode('ascii') + return f'data:image/svg+xml;base64,{b64}' + + +DS_USER = { + 'id': 'user_1', 'name': 'Tara Singh', 'email': 'tara.singh@acmecorp.com', + 'title': 'HR Business Partner', 'company': 'Acme Corporation', + 'avatar': '', 'signatureDataUrl': '', 'initialsDataUrl': '', + 'memberSince': '2019-02-01', + 'settings': {'defaultReminderDays': 3, 'defaultExpirationDays': 120, + 'timezone': 'America/Los_Angeles'}, +} + +RAISE_TEMPLATE = { + 'id': 'tmpl_raise', 'name': 'Salary Increase Confirmation Letter', + 'description': 'Standard merit-increase confirmation for a single employee to sign.', + 'createdAt': '2026-01-05T09:00:00Z', 'lastUsedAt': '2026-05-01T09:00:00Z', + 'usageCount': 6, 'ownerId': 'user_1', 'shared': True, + 'documents': [{'id': 'tdoc_1', 'name': 'Salary Increase Letter.pdf', + 'pageCount': 1, 'order': 1, + 'fileUrl': _letter_data_url(), + 'fileType': 'pdf'}], + 'roles': [{'id': 'role_1', 'name': 'Employee', 'role': 'signer', 'routingOrder': 1}], + 'fields': [{'id': 'tf_1', 'type': 'signature', 'roleId': 'role_1', + 'documentId': 'tdoc_1', 'pageNumber': 1, 'x': 80, 'y': 820, + 'width': 200, 'height': 50, 'value': '', 'required': True, + 'label': '', 'readOnly': False, 'fontSize': 14, 'fontColor': '#000000'}], +} + + +def noise_template(tid, name, desc, doc_name, last_used, usage): + """A decoy template (not scored). Its ONLY purpose is to give the Templates + table >= 2 rows: the raise-letter template must NOT be the last/only row, + or its row-action ('...') dropdown — which opens downward with `top-full` — + gets clipped by the table wrapper's `overflow-hidden` and the 'Use' item is + invisible (confirmed in Templates.jsx). With the raise template as row 1 and + decoys below it, its Use/Edit/Delete menu renders inside the container.""" + return { + 'id': tid, 'name': name, 'description': desc, + 'createdAt': '2026-01-05T09:00:00Z', 'lastUsedAt': last_used, + 'usageCount': usage, 'ownerId': 'user_1', 'shared': False, + 'documents': [{'id': f'{tid}_doc', 'name': doc_name, 'pageCount': 1, + 'order': 1, 'fileUrl': _letter_data_url(), 'fileType': 'pdf'}], + 'roles': [{'id': f'{tid}_role', 'name': 'Signer', 'role': 'signer', + 'routingOrder': 1}], + 'fields': [{'id': f'{tid}_f1', 'type': 'signature', 'roleId': f'{tid}_role', + 'documentId': f'{tid}_doc', 'pageNumber': 1, 'x': 80, 'y': 820, + 'width': 200, 'height': 50, 'value': '', 'required': True, + 'label': '', 'readOnly': False, 'fontSize': 14, + 'fontColor': '#000000'}], + } + + +# Decoy templates (not scored) — kept AFTER the raise template so it stays row 1. +NOISE_TEMPLATE_1 = noise_template( + 'tmpl_offer', 'Offer Letter', + 'Standard full-time offer letter for a new hire.', + 'Offer Letter.pdf', '2026-04-12T09:00:00Z', 11) +NOISE_TEMPLATE_2 = noise_template( + 'tmpl_remote', 'Remote Work Agreement', + 'Acknowledgement for employees working remotely.', + 'Remote Work Agreement.pdf', '2026-02-28T09:00:00Z', 3) + + +def ds_envelope(eid, subject, status, recipients, created='2026-06-10T09:00:00Z', + sent_at=None): + return { + 'id': eid, 'subject': subject, 'message': '', 'status': status, + 'createdAt': created, 'sentAt': sent_at, 'completedAt': None, + 'voidedAt': None, 'declinedAt': None, + 'lastActivityAt': sent_at or created, + 'expiresAt': None, 'senderId': 'user_1', 'folderId': None, + 'templateId': None, 'reminderEnabled': False, 'reminderDays': 3, + 'reminderFrequency': 2, + 'documents': [{'id': f'{eid}_doc', 'name': 'Document.pdf', 'pageCount': 1, + 'order': 1, 'fileUrl': 'https://picsum.photos/seed/' + eid + '/800/1100', + 'fileType': 'pdf'}], + 'recipients': recipients, + 'fields': [], + 'history': [{'id': f'{eid}_h1', 'timestamp': created, 'action': 'created', + 'actorName': 'Tara Singh', 'actorEmail': 'tara.singh@acmecorp.com', + 'details': 'Envelope created'}], + } + + +def ds_recipient(rid, name, email, status='sent', role='signer'): + return {'id': rid, 'name': name, 'email': email, 'role': role, + 'routingOrder': 1, 'status': status, 'signedAt': None, + 'viewedAt': None, 'deliveredAt': None, 'declinedAt': None, + 'declineReason': None} + + +# Noise envelopes — unrelated, already sent/completed; NONE address a +# qualifying report's email, so they never satisfy the raise-letter anchor. +DOCUSIGN_STATE = { + 'user': DS_USER, + 'envelopes': [ + ds_envelope('env_n1', 'Q1 Vendor NDA - Acme x Northwind', 'completed', + [ds_recipient('env_n1_r1', 'Brent Cooper', 'brent@northwind.example')], + created='2026-03-01T09:00:00Z', sent_at='2026-03-01T10:00:00Z'), + ds_envelope('env_n2', 'Office Lease Amendment 2026', 'sent', + [ds_recipient('env_n2_r1', 'Karen Diaz', 'karen.diaz@landlord.example')], + created='2026-05-20T09:00:00Z', sent_at='2026-05-20T11:00:00Z'), + ds_envelope('env_n3', 'Contractor Agreement - J. Wu', 'draft', + [ds_recipient('env_n3_r1', 'Jason Wu', 'jason.wu@contractor.example', + status='created')]), + ], + 'templates': [RAISE_TEMPLATE, NOISE_TEMPLATE_1, NOISE_TEMPLATE_2], + 'folders': [{'id': 'fold_1', 'name': 'HR Documents', 'parentFolder': None, + 'createdAt': '2026-01-01T09:00:00Z'}], + 'contacts': [ + {'id': 'c1', 'name': 'Brent Cooper', 'email': 'brent@northwind.example', + 'company': 'Northwind', 'title': 'Counsel'}, + ], + 'auditLog': [], +} + +# --------------------------------------------------------------------------- +# Slack — #hr channel starts empty; decoy chatter elsewhere. +# --------------------------------------------------------------------------- +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': 'people-ops', 'name': 'people-ops', 'description': 'HR ops coordination', 'topic': 'Cycle logistics', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2'], 'createdBy': 'user_1', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'hr', 'name': 'hr', 'description': 'HR announcements and review-cycle summaries', 'topic': 'Post a summary after each review batch', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': {'userId': 'user_1', 'fullName': 'Tara Singh', 'displayName': 'Tara', 'email': 'tara.singh@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'HR Business Partner', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + 'users': [ + {'userId': 'user_1', 'fullName': 'Tara Singh', 'displayName': 'Tara', 'email': 'tara.singh@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'HR Business Partner', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + {'userId': 'user_2', 'fullName': 'Olivia Reyes', 'displayName': 'Olivia', 'email': 'olivia.reyes@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Director of Engineering', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + {'userId': 'user_3', 'fullName': 'Raj Mehta', 'displayName': 'Raj', 'email': 'raj.mehta@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Compensation Lead', 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + ], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': 'Reminder: mid-year ratings are due July 5.', 'timestamp': '2026-06-26T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'people-ops': [ + {'messageId': 'm_p_1', 'senderId': 'user_3', 'content': 'Merit budget is locked; raise letters can go out as reviews close.', 'timestamp': '2026-06-26T15:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'hr': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], +} + +# --------------------------------------------------------------------------- +# Google Sheets — 'Performance Review Tracker' ledger. +# Row 1: header (Employee | Rating | Raise Letter Sent) +# Row 2: a worked EXAMPLE (not scored). +# Rows 3..12: the 10 report names in col A; Rating (col B) + Raise Letter Sent +# (col C) BLANK — the agent fills them. +# --------------------------------------------------------------------------- +_sheet_data = { + 'A1': hcell('Employee'), + 'B1': hcell('Rating'), + 'C1': hcell('Raise Letter Sent'), + 'A2': cell('Sample Employee'), + 'B2': cell('3'), + 'C2': cell('No'), +} +for _i, (_emp_id, _name, _title, _exp, _self) in enumerate(REPORTS): + _r = _i + 3 + _sheet_data[f'A{_r}'] = cell(_name) + _sheet_data[f'B{_r}'] = cell('') # blank — agent fills rating + _sheet_data[f'C{_r}'] = cell('') # blank — agent fills Yes/No + +SHEETS_STATE = { + 'id': 'workbook_perf_review', 'title': 'Performance Review 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': 'Performance Review Tracker', '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:8192', WORKDAY_STATE), # workday_mock (L2 anchor 1) + ('http://28.7.184.198:8130', DOCUSIGN_STATE), # docusign_mock (L2 anchor 2) + ('http://28.7.184.198:8178', SLACK_STATE), # slack_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/hr_midyear_review_007__long/reward.py b/hr_midyear_review_007__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..658b1854bb187fac93590087de47ed64a2fe383b --- /dev/null +++ b/hr_midyear_review_007__long/reward.py @@ -0,0 +1,359 @@ +""" +Reward Script: W05 — HRBP performance review + conditional raise letters +Task ID: hr_midyear_review_007__long +Persona: HRBP Tara Singh +Mocks: workday_mock,docusign_mock,slack_mock,google_sheets_mock + +Answer key (embedded in initial_state): + - Workday reviews[*]._expected_rating on every status=='Pending Manager Review' + review managed by Tara (the 1..5 score the manager-review must submit). + - reviews[*]._expected_envelope (bool): true iff rating >= 4 -> a DocuSign + raise letter must be sent to that report. + - reviews[*]._employee_name / _employee_email: the report's identity for + loose recipient matching on the sent envelope. + +Scoring (sub-weights sum to 1.0): + 0.35 Workday ratings (L2 anchor 1): per pending review, current ratingScore + == _expected_rating AND status == 'Completed'. Reachable only via the + gated Complete-Review action (rendered only for managerId==currentUser + && status=='Pending Manager Review'). + 0.25 DocuSign raise letters (L2 anchor 2, recall, loose): for each + qualifying report (_expected_envelope), an envelope with status in + {sent,delivered,completed,signed} addressed to that report (recipient + name OR email match). score = hits / should-send. Extra/wrong envelopes + are NEVER penalised. + 0.20 Google Sheet tracker: per report row, Rating column == expected rating + (the example row is ignored). + 0.20 Slack #hr summary: a message naming how many reviews were completed and + how many raise letters were sent (loose number match + 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', + 'docusign': 'http://28.7.184.198:8130', + 'slack': 'http://28.7.184.198:8178', + '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 _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +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, {}) + sheets = state.get('sheets', {}) + if isinstance(sheets, dict): + sheet = sheets.get(sheet_name, {}) + rows = sheet.get('rows', []) + if isinstance(rows, list) and rows: + return rows + data_rows = _parse_rows_from_sheet_data(sheet.get('data', {})) + if data_rows: + return data_rows + if isinstance(sheets, list): + for sheet in sheets: + if norm(sheet.get('name')) != norm(sheet_name): + continue + rows = sheet.get('rows', []) + if isinstance(rows, list) and rows: + return rows + data_rows = _parse_rows_from_sheet_data(sheet.get('data', {})) + if data_rows: + return data_rows + for sheet in sheets: + data_rows = _parse_rows_from_sheet_data(sheet.get('data', {})) + if data_rows: + return data_rows + return [] + + +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 _first_last(name): + parts = norm(name).split() + return (parts[0] if parts else '', parts[-1] if parts else '') + + +# ============================================================================= +# Task-specific reward +# ============================================================================= +def reward(go): + wd_i = go('workday').get('initial_state', {}) or {} + wd_c = go('workday').get('current_state', {}) or {} + ds_c = go('docusign').get('current_state', {}) or {} + slack_c = go('slack').get('current_state', {}) or {} + + reviews_i = wd_i.get('reviews', []) or [] + reviews_c = wd_c.get('reviews', []) or [] + reviews_c_by_id = {r.get('reviewId'): r for r in reviews_c if isinstance(r, dict)} + + # ---- Answer key: pending reviews with an embedded expected rating ---- + pendings = [r for r in reviews_i + if r.get('_expected_rating') is not None + and norm(r.get('status')) == 'pending manager review'] + n = len(pendings) + if n == 0: + print('DEBUG_W05 no pending reviews with embedded rating; nothing to score') + return 0.0 + + qualifying = [r for r in pendings if r.get('_expected_envelope')] + n_qual = len(qualifying) + n_completed_expected = n # every pending review should be completed + + # ---- 1) Workday ratings (L2 anchor 1) — 0.35 ---- + wd_match = 0 + try: + for r in pendings: + rid = r.get('reviewId') + exp = r.get('_expected_rating') + cur = reviews_c_by_id.get(rid, {}) + try: + cur_score = int(cur.get('ratingScore')) if cur.get('ratingScore') is not None else None + except (TypeError, ValueError): + cur_score = None + if cur_score == int(exp) and norm(cur.get('status')) == 'completed': + wd_match += 1 + except Exception as e: + print(f'DEBUG_W05 workday ratings component error: {e!r}') + wd_score = frac(wd_match, n) + + # ---- 2) DocuSign raise letters (L2 anchor 2, recall, loose) — 0.25 ---- + SENT_STATES = {'sent', 'delivered', 'completed', 'signed'} + ds_match = 0 + try: + envelopes = ds_c.get('envelopes', []) or [] + sent_envs = [e for e in envelopes if norm(e.get('status')) in SENT_STATES] + for r in qualifying: + emp_name = norm(r.get('_employee_name')) + emp_email = norm(r.get('_employee_email')) + efirst, elast = _first_last(r.get('_employee_name')) + hit = False + for env in sent_envs: + for rec in (env.get('recipients') or []): + rname = norm(rec.get('name')) + remail = norm(rec.get('email')) + if emp_email and remail and emp_email == remail: + hit = True + break + if emp_name and rname and emp_name == rname: + hit = True + break + # loose: first+last both present in recipient name + if efirst and elast and efirst in rname and elast in rname: + hit = True + break + if hit: + break + if hit: + ds_match += 1 + except Exception as e: + print(f'DEBUG_W05 docusign component error: {e!r}') + ds_score = frac(ds_match, n_qual) if n_qual else 1.0 + + # ---- 3) Google Sheet tracker — 0.20 ---- + # Per report row: Rating column == expected rating. Example row ignored + # (its name does not match any report). + name_to_rating = {norm(r.get('_employee_name')): str(int(r.get('_expected_rating'))) + for r in pendings} + sheet_match = 0 + try: + rows_c = _sheet_rows(go('google_sheets'), 'current_state', + 'Performance Review Tracker') + + def _row_field(row, *aliases): + for a in aliases: + if a in row: + return row[a] + return '' + + for name, exp_rating in name_to_rating.items(): + for row in rows_c: + if norm(_row_field(row, 'employee', 'name', 'employee name')) == name: + cur = norm(_row_field(row, 'rating', 'score')) + # accept '4', '4.0', or a digit anywhere in the cell + m = re.search(r'\d', cur) + if m and m.group(0) == exp_rating: + sheet_match += 1 + break + except Exception as e: + print(f'DEBUG_W05 sheet component error: {e!r}') + sheet_score = frac(sheet_match, n) + + # ---- 4) Slack #hr summary — 0.20 ---- + slack_ok = 0.0 + try: + chan = _slack_channel_messages(slack_c, 'hr') + for msg in chan: + txt = norm(_msg_text(msg)) + if not txt.strip(): + continue + # find numbers near review/letter keywords + rev_m = re.search(r'(\d+)\s*(?:manager\s+)?reviews?', txt) + let_m = re.search(r'(\d+)\s*(?:raise\s+|salary\s+|increase\s+)?(?:letters?|envelopes?)', txt) + if (rev_m and int(rev_m.group(1)) == n_completed_expected + and let_m and int(let_m.group(1)) == n_qual): + slack_ok = 1.0 + break + if slack_ok == 0.0: + # fallback: any non-empty message mentioning both reviews and letters + for msg in chan: + txt = norm(_msg_text(msg)) + if ('review' in txt and + ('letter' in txt or 'raise' in txt or 'increase' in txt)): + slack_ok = 0.5 + break + except Exception as e: + print(f'DEBUG_W05 slack component error: {e!r}') + + # ---- Combine ---- + s_wd = 0.35 * wd_score + s_ds = 0.25 * ds_score + s_sheet = 0.20 * sheet_score + s_slack = 0.20 * slack_ok + score = s_wd + s_ds + s_sheet + s_slack + + print( + 'DEBUG_W05 ' + f'n_pending={n} n_qualifying={n_qual} ' + f'wd_match={wd_match}/{n} wd_score={round(wd_score, 4)} ' + f'ds_match={ds_match}/{n_qual} ds_score={round(ds_score, 4)} ' + f'sheet_match={sheet_match}/{n} sheet_score={round(sheet_score, 4)} ' + f'slack_ok={slack_ok} ' + f'w_wd={round(s_wd, 4)} w_ds={round(s_ds, 4)} ' + f'w_sheet={round(s_sheet, 4)} w_slack={round(s_slack, 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/itops_access_approval_001/_cua_gym_vm_bridge.sh b/itops_access_approval_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/itops_access_approval_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/itops_access_approval_001/initial_setup.py b/itops_access_approval_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..18c5d64cd346e311397bf8fd8f59cc10d130d33e --- /dev/null +++ b/itops_access_approval_001/initial_setup.py @@ -0,0 +1,307 @@ +""" +Initial Setup: Access Request Approval Log (prof26_access_approval_001) +Task ID: itops_access_approval_001 +Domain: mock_websites +Mocks: jira_mock, workday_mock, google_sheets_mock + +Resets the three mock apps to their initial pre-task state and writes a +canonical JSON snapshot of the Approvals sheet to /home/user/prof26_access_approval_001.json. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +JIRA_URL = "http://28.7.184.198:8153" +WORKDAY_URL = "http://28.7.184.198:8192" +SHEETS_URL = "http://28.7.184.198:8145" + +WORKDIR = "/home/user" +TASK_ID = "prof26_access_approval_001" +SNAPSHOT = f"{WORKDIR}/{TASK_ID}.json" + +# --- Generate and persist sid --- +sid = str(uuid.uuid4()) +with open("/tmp/task_web_sid", "w") as f: + f.write(sid) + +# --------------------------------------------------------------------------- +# Build initial state for each mock +# --------------------------------------------------------------------------- + +HEADER_STYLE = {"bold": True, "bg": "#E8EAED"} + + +def cell(value, style=None): + c = {"value": value, "formula": value} + if style: + c["style"] = style + return c + + +def build_sheets_state(): + """Access Control Register workbook with 'Approvals' sheet: header + 3 records.""" + headers = ["Request ID", "Date", "Requester", "System", "Access Level", + "Department", "Manager Approval", "SysAdmin Decision", "Notes"] + data = {} + for col_idx, h in enumerate(headers): + col = chr(ord("A") + col_idx) # A..I + data[f"{col}1"] = cell(h, HEADER_STYLE) + + records = [ + ["IAR-309", "2026-06-27", "Nina Cole", "HubSpot", "Edit", "Marketing", + "Approved", "Approved", + "Department verified in Workday (E-10410). Edit access compliant for Marketing."], + ["IAR-310", "2026-06-29", "Omar Diaz", "Google Sheets", "Edit", "Finance", + "Approved", "Approved", + "Department verified in Workday (E-10455). Edit access compliant for Finance."], + ["IAR-311", "2026-06-30", "Priya Sen", "Salesforce", "Read-only", "Sales Operations", + "Approved", "Approved", + "Department verified in Workday (E-10477). Read-only access compliant for Sales Operations."], + ] + for r, rec in enumerate(records, start=2): + for col_idx, val in enumerate(rec): + col = chr(ord("A") + col_idx) + data[f"{col}{r}"] = cell(val) + + sheet = { + "id": "sh_apr_01", + "name": "Approvals", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": None, + "isHidden": False, + "data": data, + } + return { + "id": "wb_acr_01", + "title": "Access Control Register", + "activeSheetId": "sh_apr_01", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [sheet], + } + + +def build_jira_state(): + return { + "currentUser": {"id": "u1", "name": "Business Systems Admin", + "email": "sysadmin@meridianlabs.io", + "avatar": "https://picsum.photos/100/100?random=u1"}, + "users": [ + {"id": "u1", "name": "Business Systems Admin", "email": "sysadmin@meridianlabs.io", + "avatar": "https://picsum.photos/100/100?random=u1"}, + {"id": "u2", "name": "Linda Hess", "email": "l.hess@meridianlabs.io", + "avatar": "https://picsum.photos/100/100?random=u2"}, + ], + "projects": [ + {"id": "p_iar", "key": "IAR", "name": "IT Access Requests", "leadId": "u1", + "category": "IT", "icon": "https://picsum.photos/64/64?random=iar"}, + ], + "sprints": [ + {"id": "s1", "projectId": "p_iar", "name": "Sprint 1", + "goal": "Process access requests", "startDate": "2026-06-22T12:00:00.000Z", + "endDate": "2026-07-06T12:00:00.000Z", "state": "active"}, + ], + "issues": [ + { + "id": "i_iar_312", "key": "IAR-312", "projectId": "p_iar", + "summary": "Access request: Salesforce read-only for onboarding rep", + "description": ("Requester: Tom Becker (tom.becker@meridianlabs.io). " + "Requested system: Salesforce. Access level: Read-only. " + "Purpose: Support onboarding-campaign reporting. " + "Manager approval: Approved by Linda Hess (l.hess@meridianlabs.io)."), + "type": "Task", "status": "To Do", "priority": "Medium", "storyPoints": 1, + "reporterId": "u2", "assigneeId": "u1", "sprintId": "s1", "epicId": None, + "labels": ["access-request"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-07-01T09:00:00.000Z", "updatedAt": "2026-07-01T09:00:00.000Z", + }, + ], + "comments": [], + "workflows": [{"id": "w1", "name": "IT Access Workflow", + "transitions": [{"from": "To Do", "to": ["In Progress", "Done"]}, + {"from": "In Progress", "to": ["Done", "To Do"]}, + {"from": "Done", "to": ["To Do"]}]}], + "notifications": [], + } + + +def build_workday_state(): + return { + "currentUser": { + "id": "emp001", "name": "Business Systems Admin", + "email": "sysadmin@meridianlabs.io", "phone": "+1 (415) 555-0100", + "role": "Manager", "department": "IT Operations", "departmentId": "dept001", + "avatar": "https://ui-avatars.com/api/?name=Business+Systems+Admin&background=0875E1&color=fff&size=128", + "managerId": None, "title": "Business Systems Administrator", + "location": "Remote", "joinDate": "2021-03-15", "employeeType": "Full-Time", + "skills": ["Identity Management", "Access Governance"], + "birthday": "1990-04-12", "workAnniversary": "2021-03-15", + }, + "employees": [ + { + "id": "E-10482", "name": "Tom Becker", "email": "tom.becker@meridianlabs.io", + "phone": "+1 (415) 555-0182", "role": "Employee", "department": "Sales Operations", + "departmentId": "dept003", "avatar": "https://ui-avatars.com/api/?name=Tom+Becker&background=0875E1&color=fff&size=128", + "managerId": "emp001", "title": "Onboarding Representative", + "location": "Remote", "joinDate": "2024-01-15", "employeeType": "Full-Time", + "skills": ["Sales", "Onboarding"], "birthday": "1992-08-22", + "workAnniversary": "2024-01-15", + }, + ], + "departments": [ + {"id": "dept001", "name": "IT Operations", "headcount": 1, "managerId": None}, + {"id": "dept003", "name": "Sales Operations", "headcount": 1, "managerId": "emp001"}, + ], + "timeEntries": [], + "timeOffRequests": [], + "timeOffBalance": {"vacation": 120, "sick": 40, "personal": 16}, + "payroll": [], + "benefits": {"employeeId": "E-10482", "enrollmentStatus": "Complete", "plans": [], "dependents": []}, + "reviews": [], + "goals": [], + "tasks": [], + "announcements": [], + "notifications": [], + "clockStatus": {"isClockedIn": False, "startTime": None}, + } + + +# --------------------------------------------------------------------------- +# Inject state into each mock +# --------------------------------------------------------------------------- +mocks = { + "jira_mock": JIRA_URL, + "workday_mock": WORKDAY_URL, + "google_sheets_mock": SHEETS_URL, +} + +states = { + "jira_mock": build_jira_state(), + "workday_mock": build_workday_state(), + "google_sheets_mock": build_sheets_state(), +} + +for name, url in mocks.items(): + resp = requests.post( + f"{url}/post?sid={sid}", + json={"action": "set", "state": states[name]}, + timeout=30, + ) + assert resp.status_code == 200, f"{name} state injection failed: {resp.text}" + print(f"State injected: {name} (sid={sid})") + +# --------------------------------------------------------------------------- +# Verify initial_state is served +# --------------------------------------------------------------------------- +for name, url in mocks.items(): + 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 after injection" +print("Verified: all three mocks have initial_state set") + +# --------------------------------------------------------------------------- +# Write canonical JSON snapshot of the Approvals sheet (initial state) +# --------------------------------------------------------------------------- +sheets_state = build_sheets_state() +apr = next(s for s in sheets_state["sheets"] if s["id"] == "sh_apr_01") +snapshot = { + "task_id": TASK_ID, + "sid": sid, + "workbook_id": sheets_state["id"], + "workbook_title": sheets_state["title"], + "sheet_id": apr["id"], + "sheet_name": apr["name"], + "cells": apr["data"], + "row_count": apr["rowCount"], + "col_count": apr["colCount"], +} +with open(SNAPSHOT, "w") as f: + json.dump(snapshot, f, indent=2) +print(f"Initial snapshot written: {SNAPSHOT}") + +# --------------------------------------------------------------------------- +# Launch Chrome for each mock (GUI-ready state) +# --------------------------------------------------------------------------- +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) + + +for name, url in mocks.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.5) +print(f"Launched Chrome for {len(mocks)} mocks") + + +# --------------------------------------------------------------------------- +# Wait until every mock serves injected state AND renders (Phase 1 + Phase 2) +# --------------------------------------------------------------------------- +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)") + print(f"[{name}] rendered OK ({len(html)} bytes)") + finally: + page.close() + finally: + browser.close() + + +wait_for_mocks_loaded(mocks, sid) +print(f"GUI_READY: all {len(mocks)} mocks launched and verified (sid={sid})") diff --git a/itops_access_approval_001/reward.py b/itops_access_approval_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..074488bab875a8eb06119a8a39b2cc9c60a76619 --- /dev/null +++ b/itops_access_approval_001/reward.py @@ -0,0 +1,184 @@ +""" +Reward Script: Access Request Approval Log — record IAR-312 in Google Sheets +Task ID: itops_access_approval_001 +Domain: mock_websites +Mock: google_sheets_mock +Scoring: Verify the 'Approvals' sheet has exactly one new row (row 5) added + with the exact ground-truth values, no extra rows, and no duplicate + IAR-312 request id. + +State source: The agent edits the Google Sheets mock through the browser, +which updates the mock's in-memory state keyed by the task session id. We +read the live current_state from the mock's /go endpoint (using the sid in +/tmp/task_web_sid) so the reward reflects the agent's actual changes. The +sid is task-private (initial_setup.py mints a fresh uuid.uuid4() per run), +so /go returns only this task's state. +""" +import json +import sys + +import requests + +# Mock base URL (from task_config.json). +SHEETS_URL = "http://28.7.184.198:8145" # google_sheets_mock + +# Ground-truth values for the new row 5 (from task_config.json context). +EXPECTED_ROW5 = { + 'A': 'IAR-312', + 'B': '2026-07-01', + 'C': 'Tom Becker', + 'D': 'Salesforce', + 'E': 'Read-only', + 'F': 'Sales Operations', + 'G': 'Approved', + 'H': 'Approved', + 'I': 'Department verified in Workday (E-10482). Read-only access compliant for Sales Operations.', +} + +# Ground-truth values for the pre-existing rows 2-4 (must remain unchanged). +EXPECTED_ROWS_2_4 = { + 'A2': 'IAR-309', 'B2': '2026-06-27', 'C2': 'Nina Cole', 'D2': 'HubSpot', + 'E2': 'Edit', 'F2': 'Marketing', 'G2': 'Approved', 'H2': 'Approved', + 'I2': 'Department verified in Workday (E-10410). Edit access compliant for Marketing.', + 'A3': 'IAR-310', 'B3': '2026-06-29', 'C3': 'Omar Diaz', 'D3': 'Google Sheets', + 'E3': 'Edit', 'F3': 'Finance', 'G3': 'Approved', 'H3': 'Approved', + 'I3': 'Department verified in Workday (E-10455). Edit access compliant for Finance.', + 'A4': 'IAR-311', 'B4': '2026-06-30', 'C4': 'Priya Sen', 'D4': 'Salesforce', + 'E4': 'Read-only', 'F4': 'Sales Operations', 'G4': 'Approved', 'H4': 'Approved', + 'I4': 'Department verified in Workday (E-10477). Read-only access compliant for Sales Operations.', +} + +# Expected Request ID column values (rows 2-5). IAR-312 must appear exactly once. +EXPECTED_REQUEST_IDS = ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'] + + +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 + + +def _load_cells(): + """Fetch the Approvals sheet cells from the google_sheets_mock live state. + + Reads /tmp/task_web_sid for the session id, queries the mock's /go + endpoint, and returns the data dict of the 'sh_apr_01' sheet. Returns + None on any failure. + """ + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + except Exception as e: + print(f'CRITICAL: cannot read /tmp/task_web_sid: {e}') + return None + try: + resp = requests.get(f'{SHEETS_URL}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch sheets mock state: {e}') + return None + try: + cur = data['current_state'] + sheet = next(s for s in cur['sheets'] if s['id'] == 'sh_apr_01') + cells = sheet['data'] + except Exception as e: + print(f'CRITICAL: cannot locate sh_apr_01 in current_state: {e}') + return None + if not isinstance(cells, dict): + print('CRITICAL: sheet data is not a dict') + return None + return cells + + +def check_component_1(cells): + """New row 5 fully populated with the exact 9 ground-truth values. + Pass condition: cells A5..I5 all exist and equal EXPECTED_ROW5 exactly. + """ + missing = [f'{col}5' for col in 'ABCDEFGHI' + if cells.get(f'{col}5', {}).get('value') != EXPECTED_ROW5[col]] + if not missing: + return True, 0.70, 'row 5 has all 9 correct values (A5=IAR-312 ... I5=notes)' + return False, 0.0, f'row 5 missing/incorrect cells: {missing}' + + +def check_component_2(cells): + """Exactly one new row added, no extra rows, and rows 2-4 preserved intact. + Pass condition: snapshot has exactly 45 cells (rows 1-5 x 9 cols) AND rows + 2-4 still match EXPECTED_ROWS_2_4 in every field. Fails on initial (36 cells). + """ + n = len(cells) + if n != 45: + return False, 0.0, f'expected exactly 45 cells (rows 1-5), found {n}' + wrong = [] + for addr, exp in EXPECTED_ROWS_2_4.items(): + got = cells.get(addr, {}).get('value') + if got != exp: + wrong.append(f'{addr}={got!r}(exp {exp!r})') + if not wrong: + return True, 0.20, 'exactly 45 cells and rows 2-4 unchanged in all 27 fields' + return False, 0.0, f'rows 2-4 mismatch: {wrong[:5]}' + + +def check_component_3(cells): + """No duplicate IAR-312 request id; IAR-312 appears exactly once in col A. + Pass condition: Request IDs A2..A5 equal ['IAR-309','IAR-310','IAR-311', + 'IAR-312'] and there is no A6+ request id (no extra rows). + """ + actual_ids = [] + for r in range(2, 6): + v = cells.get(f'A{r}', {}).get('value') + if v is None: + break + actual_ids.append(v) + if actual_ids != EXPECTED_REQUEST_IDS: + return False, 0.0, f'request-id column A = {actual_ids} (exp {EXPECTED_REQUEST_IDS})' + # Ensure no stray row 6 (would indicate an extra/duplicate row was added). + if cells.get('A6', {}).get('value') is not None: + return False, 0.0, 'extra row 6 present — A6 is not empty' + return True, 0.10, 'IAR-312 appears exactly once (at A5); no extra rows' + + +def verify_task(): + cells = _load_cells() + if cells is None: + print('REWARD: 0.0') + return 0.0 + + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'Row 5 added with exact ground-truth values', 0.70, + check_component_1, (cells,)), + (2, 'Exactly one row added + rows 2-4 preserved', 0.20, + check_component_2, (cells,)), + (3, 'No duplicate IAR-312 / no extra rows', 0.10, + check_component_3, (cells,)), + ]: + _, 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/itops_access_approval_001/reward_label.json b/itops_access_approval_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..0bc94d81b2409a127df975c0103099df87a2a5de --- /dev/null +++ b/itops_access_approval_001/reward_label.json @@ -0,0 +1,52 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof26_access_approval_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:57", + "label": { + "task_id": "itops_access_approval_001", + "domain": "mock_websites", + "summary": "验证在 Google Sheets 的 Approvals 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复或额外行", + "is_placeholder": false, + "data_sources": [ + "/home/user/prof26_access_approval_001.json" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.7, + "description": "检查新添加的第5行是否完全填充了9个预期值", + "check_logic": "遍历列 A 到 I,检查 cells.get(f'{col}5', {}).get('value') 是否等于 EXPECTED_ROW5 中对应列的值;若全部匹配则通过,否则列出缺失或不匹配的单元格", + "pass_condition": "A5 到 I5 全部存在且值与 EXPECTED_ROW5 完全一致" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "检查是否只新增了一行且第2-4行保持原样", + "check_logic": "先检查 len(cells) 是否等于 45;再遍历 EXPECTED_ROWS_2_4 中每个地址和预期值,检查 cells.get(addr, {}).get('value') 是否匹配", + "pass_condition": "快照中恰好有 45 个单元格(行1-5 × 9列),且第2-4行的全部 27 个字段与 EXPECTED_ROWS_2_4 完全一致" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "检查 IAR-312 在 A 列只出现一次且无额外行", + "check_logic": "遍历 A2 到 A5,提取值组成 actual_ids,检查是否等于 EXPECTED_REQUEST_IDS;再检查 A6 的值是否为 None(即无第6行)", + "pass_condition": "A2 到 A5 的请求 ID 恰好为 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限,并四舍五入保留4位小数", + "failure_modes": [ + "快照文件 /home/user/prof26_access_approval_001.json 不存在", + "快照文件解析失败或内容不是有效的 JSON", + "快照中的 cells 字段不是字典类型", + "第5行有任何单元格缺失或与 EXPECTED_ROW5 不匹配(组件1失败,得0分)", + "单元格总数不是45,或第2-4行有任何字段被修改(组件2失败,得0分)", + "A2-A5 请求 ID 列表不匹配,或 A6 不为空(组件3失败,得0分)" + ], + "scoring_logic_explanation": "脚本首先在 VM 上加载本地快照文件 /home/user/prof26_access_approval_001.json。若加载失败(文件不存在、解析错误或 cells 不是字典),直接输出 CRITICAL 并返回 0.0。加载成功后,依次执行三个组件检查:组件1验证第5行(A5-I5)的9个单元格是否完全匹配预期的 IAR-312 记录,权重0.70;组件2验证快照中恰好有45个单元格(即只有1-5行)且第2-4行的全部27个字段保持原样,权重0.20;组件3验证A列请求ID从A2到A5依次为IAR-309到IAR-312,且A6为空以确保无重复或额外行,权重0.10。每个组件通过时获得对应权重分数,失败则得0分。三个组件得分累加后,用 min(total_score, 1.0) 钳制上限,四舍五入到4位小数作为最终 REWARD 返回。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. **Task ID**: prof26_access_approval_001(从 docstring 中明确提取)\n2. **Domain**: mock_websites(从 docstring 中明确提取)\n3. **Summary**: 验证在 Google Sheets 的 'Approvals' 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复/额外行。\n4. **is_placeholder**: false(这是一个真正的评分脚本,不是占位符)\n5. **data_sources**: 脚本从 `/home/user/prof26_access_approval_001.json`(VM 上的状态快照文件)获取状态。docstring 提到 mock 是 google_sheets_mock,但实际验证的是快照文件。\n6. **Scoring components**:\n - Component 1: weight 0.70, 检查 A5..I5 是否完全匹配 EXPECTED_ROW5\n - Component 2: weight 0.20, 检查总单元格数是否为 45(行1-5 × 9列),且行2-4完全匹配 EXPECTED_ROWS_2_4\n - Component 3: weight 0.10, 检查 A2..A5 的请求 ID 是否完全匹配 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空(无额外行)\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,然后取 min(total_score, 1.0) 并四舍五入到4位小数\n9. **failure_modes**:\n - 快照文件不存在\n - 快照文件无法解析\n - cells 不是 dict\n - 任何组件检查失败(返回 0.0 分)\n - 组件1:A5-I5 有任何缺失或不匹配\n - 组件2:单元格数不是 45,或行2-4有任何字段不匹配\n - 组件3:A2-A5 请求 ID 不匹配,或 A6 不为空\n10. **scoring_logic_explanation**: 按执行顺序:\n - 从 `/home/user/prof26_access_approval_001.json` 加载快照\n - 如果加载失败,打印 CRITICAL 并返回 0.0\n - 依次运行三个组件检查:\n 1. 检查第5行9个单元格是否完全匹配预期值(0.7分)\n 2. 检查总单元格数是否为45(即只有1-5行)且第2-4行27个字段完全不变(0.2分)\n 3. 检查A列请求ID是否为预期列表且A6为空,确保IAR-312只出现一次且无额外行(0.1分)\n - 各组件得分累加,最终钳制在1.0并四舍五入\n11. **confidence**: 1.0(源码完整清晰)\n\n需要确保:\n- 只输出 JSON,无 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- 不要臆测\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"prof26_access_approval_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Google Sheets 的 Approvals 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复或额外行\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/home/user/prof26_access_approval_001.json\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.70,\n \"description\": \"检查新添加的第5行是否完全填充了9个预期值\",\n \"check_logic\": \"遍历列 A 到 I,检查 cells.get(f'{col}5', {}).get('value') 是否等于 EXPECTED_ROW5 中对应列的值;若全部匹配则通过\",\n \"pass_condition\": \"A5 到 I5 全部存在且值与 EXPECTED_ROW5 完全一致\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.20,\n \"description\": \"检查是否只新增了一行且第2-4行保持原样\",\n \"check_logic\": \"先检查 len(cells) 是否等于 45;再遍历 EXPECTED_ROWS_2_4 中每个地址和预期值,检查 cells.get(addr, {}).get('value') 是否匹配\",\n \"pass_condition\": \"快照中恰好有 45 个单元格(行1-5 × 9列),且第2-4行的全部 27 个字段与 EXPECTED_ROWS_2_4 完全一致\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.10,\n \"description\": \"检查 IAR-312 在 A 列只出现一次且无额外行\",\n \"check_logic\": \"遍历 A2 到 A5,提取值组成 actual_ids,检查是否等于 EXPECTED_REQUEST_IDS;再检查 A6 的值是否为 None\",\n \"pass_condition\": \"A2 到 A5 的请求 ID 恰好为 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空(无第6行)\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限,并四舍五入保留4位小数\",\n \"failure_modes\": [\n \"快照文件 /home/user/prof26_access_approval_001.json 不存在\",\n \"快照文件解析失败或内容不是有效的 JSON\",\n \"快照中的 cells 字段不是字典类型\",\n \"第5行有任何单元格缺失或与 EXPECTED_ROW5 不匹配(组件1失败,得0分)\",\n \"单元格总数不是45,或第2-4行有任何字段被修改(组件2失败,得0分)\",\n \"A2-A5 请求 ID 列表不匹配,或 A6 不为空(组件3失败,得0分)\"\n ],\n \"scoring_logic_explanation\": \"脚本首先在 VM 上加载本地快照文件 /home/user/prof26_access_approval_001.json。若加载失败(文件不存在、解析错误或格式不对),直接输出 CRITICAL 并返回 0.0。加载成功后,依次执行三个组件检查:组件1验证第5行(A5-I5)的9个单元格是否完全匹配预期的 IAR-312 记录,权重0.70;组件2验证快照中恰好有45个单元格(即只有1-5行)且第2-4行的全部27个字段保持原样,权重0.20;组件3验证A列请求ID从A2到A5依次为IAR-309到IAR-312,且A6为空以确保无重复或额外行,权重0.10。每个组件通过时获得对应权重分数,失败则得0分。三个组件得分累加后,用 min(total_score, 1.0) 钳制上限,四舍五入到4位小数作为最终 REWARD 返回。\",\n \"confidence\": 1.0\n}\n```\n\n检查格式要求:\n- 只输出 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n看起来都符合。 {\"task_id\":\"prof26_access_approval_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Google Sheets 的 Approvals 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复或额外行\",\"is_placeholder\":false,\"data_sources\":[\"/home/user/prof26_access_approval_001.json\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.7,\"description\":\"检查新添加的第5行是否完全填充了9个预期值\",\"check_logic\":\"遍历列 A 到 I,检查 cells.get(f'{col}5', {}).get('value') 是否等于 EXPECTED_ROW5 中对应列的值;若全部匹配则通过,否则列出缺失或不匹配的单元格\",\"pass_condition\":\"A5 到 I5 全部存在且值与 EXPECTED_ROW5 完全一致\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"检查是否只新增了一行且第2-4行保持原样\",\"check_logic\":\"先检查 len(cells) 是否等于 45;再遍历 EXPECTED_ROWS_2_4 中每个地址和预期值,检查 cells.get(addr, {}).get('value') 是否匹配\",\"pass_condition\":\"快照中恰好有 45 个单元格(行1-5 × 9列),且第2-4行的全部 27 个字段与 EXPECTED_ROWS_2_4 完全一致\"},{\"name\":\"Component 3\",\"weight\":0.1,\"description\":\"检查 IAR-312 在 A 列只出现一次且无额外行\",\"check_logic\":\"遍历 A2 到 A5,提取值组成 actual_ids,检查是否等于 EXPECTED_REQUEST_IDS;再检查 A6 的值是否为 None(即无第6行)\",\"pass_condition\":\"A2 到 A5 的请求 ID 恰好为 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限,并四舍五入保留4位小数\",\"failure_modes\":[\"快照文件 /home/user/prof26_access_approval_001.json 不存在\",\"快照文件解析失败或内容不是有效的 JSON\",\"快照中的 cells 字段不是字典类型\",\"第5行有任何单元格缺失或与 EXPECTED_ROW5 不匹配(组件1失败,得0分)\",\"单元格总数不是45,或第2-4行有任何字段被修改(组件2失败,得0分)\",\"A2-A5 请求 ID 列表不匹配,或 A6 不为空(组件3失败,得0分)\"],\"scoring_logic_explanation\":\"脚本首先在 VM 上加载本地快照文件 /home/user/prof26_access_approval_001.json。若加载失败(文件不存在、解析错误或 cells 不是字典),直接输出 CRITICAL 并返回 0.0。加载成功后,依次执行三个组件检查:组件1验证第5行(A5-I5)的9个单元格是否完全匹配预期的 IAR-312 记录,权重0.70;组件2验证快照中恰好有45个单元格(即只有1-5行)且第2-4行的全部27个字段保持原样,权重0.20;组件3验证A列请求ID从A2到A5依次为IAR-309到IAR-312,且A6为空以确保无重复或额外行,权重0.10。每个组件通过时获得对应权重分数,失败则得0分。三个组件得分累加后,用 min(total_score, 1.0) 钳制上限,四舍五入到4位小数作为最终 REWARD 返回。\",\"confidence\":1.0}" +} diff --git a/ops_board_agenda_008/_cua_gym_vm_bridge.sh b/ops_board_agenda_008/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_board_agenda_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/ops_board_agenda_008/initial_setup.py b/ops_board_agenda_008/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ac950ee2fa3422ea12247456873761fa79bd666f --- /dev/null +++ b/ops_board_agenda_008/initial_setup.py @@ -0,0 +1,256 @@ +""" +Initial Setup: ea_board_prep_b101 +Task ID: ops_board_agenda_008 +Domain: mock_websites +Mocks: google_docs_mock, notion_mock, google_calendar_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a project lead. Your tools for this task are: shared documents, the Notion workspace, the team calendar, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Google Docs with documents 'Board Agenda - May'; Notion workspace with pages 'Board Brief Template'; an empty Google Calendar; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: new June board agenda doc (+0.2); agenda has the template's 3 sections (+0.3); cal_new_event (+0.1); Board Meeting event (+0.1); on June 30 (+0.2); slack_new_msg (+0.1). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "google_docs_mock": "http://28.7.184.198:8142", + "notion_mock": "http://28.7.184.198:8166", + "google_calendar_mock": "http://28.7.184.198:8141", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8142' + +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_docs_mock': { 'currentUser': { 'id': 'user-1', + 'name': 'Demo User', + 'email': 'demo@example.com', + 'avatar': ''}, + 'users': [ { 'id': 'user-1', + 'name': 'Demo User', + 'email': 'demo@example.com', + 'avatar': ''}, + { 'id': 'user-2', + 'name': 'Alice Chen', + 'email': 'alice@example.com', + 'avatar': ''}, + { 'id': 'user-3', + 'name': 'Bob Smith', + 'email': 'bob@example.com', + 'avatar': ''}], + 'documents': { 'd-prev': { 'id': 'd-prev', + 'title': 'Board Agenda - May', + 'content': '

old

', + 'ownerId': 'user-1', + 'starred': False, + 'created': '2026-05-01T10:00:00Z', + 'updated': '2026-06-01T10: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': ''}}, + 'notion_mock': { 'user': { 'id': 'user-1', + 'name': 'Sarah Chen', + 'email': 'sarah.chen@acme.com', + 'avatar': ''}, + 'workspace': { 'id': 'ws-1', + 'name': 'Acme Product', + 'icon': '', + 'members': ['user-1']}, + 'pages': { 'page-tmpl': { 'id': 'page-tmpl', + 'title': 'Board Brief Template', + 'icon': '', + 'cover': None, + 'parentId': None, + 'blockIds': ['blk-t1'], + 'favorite': False, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-06-05T00:00:00.000Z', + 'properties': {}}}, + 'blocks': { 'blk-t1': { 'id': 'blk-t1', + 'type': 'text', + 'content': 'Standard agenda sections: ' + 'Approvals, Financials, Risks.', + 'properties': {}, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-05-20T00:00:00.000Z'}}, + 'trash': [], + 'comments': {}, + 'settings': { 'appearance': 'light', + 'startWeekMonday': False, + 'fontSize': 'default'}, + 'notifications': [], + 'pageOrder': ['page-tmpl'], + 'focusBlockId': None}, + '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}}, + '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 the board agenda ready?', + '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/ops_board_agenda_008/reward.py b/ops_board_agenda_008/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..d178c3f890982feab2fcb36fd42496652efa1242 --- /dev/null +++ b/ops_board_agenda_008/reward.py @@ -0,0 +1,124 @@ +""" +Reward Script: ea_board_prep_b101 +Task ID: ops_board_agenda_008 +Domain: mock_websites +Mocks: google_docs_mock, notion_mock, google_calendar_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.2] new June board agenda doc + - [0.3] agenda has the template's 3 sections + - [0.1] cal_new_event + - [0.1] Board Meeting event + - [0.2] on June 30 + - [0.1] slack_new_msg +""" +import re +import sys + +import requests + +MOCK_URLS = { + "google_docs_mock": "http://28.7.184.198:8142", + "notion_mock": "http://28.7.184.198:8166", + "google_calendar_mock": "http://28.7.184.198:8141", + "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: a new google doc titled about (new June board agenda doc) +c0_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys()) +c0_docs = cur('google_docs_mock').get('documents') or {} +c0_new = [d for did, d in c0_docs.items() if did not in c0_init and any(t in _lc(d.get('title','')) for t in ['board meeting agenda', 'board meeting agenda - june', 'board agenda - june'])] +if c0_new: + print('PASS: new June board agenda doc (0.2)') + total += 0.2 +else: + print('FAIL: new June board agenda doc') + +# c1: new google doc body (agenda has the template\'s 3 sections) +c1_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys()) +c1_docs = cur('google_docs_mock').get('documents') or {} +c1_new = [d for did, d in c1_docs.items() if did not in c1_init and any(t in _lc(d.get('title','')) for t in ['board meeting agenda', 'board agenda - june'])] +c1_txt = _lc(' '.join(d.get('content','') for d in c1_new)) +if c1_new and all(t in c1_txt for t in ['approvals', 'financials', 'risks']): + print('PASS: agenda has the template\'s 3 sections (0.3)') + total += 0.3 +else: + print('FAIL: agenda has the template\'s 3 sections') + +# c2: a new calendar event was created +c2_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])} +c2_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c2_init_ids] +globals()['cal_new_events'] = c2_new +if c2_new: + print('PASS: new calendar event (0.1)') + total += 0.1 +else: + print('FAIL: no new calendar event') + +# c3: new event title (Board Meeting event) +c3_new = globals().get('cal_new_events', []) +if any(any(t in _lc(e.get('title','')) for t in ['board meeting']) for e in c3_new): + print('PASS: Board Meeting event (0.1)') + total += 0.1 +else: + print('FAIL: Board Meeting event') + +# c4: new event date contains '2026-06-30' +c4_new = globals().get('cal_new_events', []) +if any('2026-06-30' in (e.get('start','') or '') for e in c4_new): + print('PASS: on June 30 (0.2)') + total += 0.2 +else: + print('FAIL: on June 30') + +# c5: new message by user_1 in #general +c5_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c5_seed = set(SEED.get('slack_mock:general', [])) +c5_new = [m for m in c5_msgs if m.get('messageId') not in c5_seed and m.get('senderId') == 'user_1'] +c5_blob = _lc(' '.join((m.get('content') or '') for m in c5_new)) +if c5_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') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/ops_board_agenda_008/reward_label.json b/ops_board_agenda_008/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..5ad8d003f896b7ae885b5ae947d3422ed9d70d0e --- /dev/null +++ b/ops_board_agenda_008/reward_label.json @@ -0,0 +1,74 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/2ae6814e-a7b8-5f0e-b574-5dd99095d0bf/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:18:50", + "label": { + "task_id": "ops_board_agenda_008", + "domain": "mock_websites", + "summary": "验证用户是否创建了6月董事会会议议程文档、在日历中创建了6月30日的董事会会议事件,并在Slack #general频道发送了新消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_docs_mock", + "notion_mock", + "google_calendar_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "c0: new June board agenda doc", + "weight": 0.2, + "description": "检查是否在 Google Docs 中创建了新的6月董事会会议议程文档", + "check_logic": "对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,筛选出新增文档(id 不在初始集合中),并检查其标题(不区分大小写)是否包含 'board meeting agenda'、'board meeting agenda - june' 或 'board agenda - june'", + "pass_condition": "存在新增文档且标题匹配上述任一关键词" + }, + { + "name": "c1: agenda has the template's 3 sections", + "weight": 0.3, + "description": "检查新创建的议程文档是否包含模板的三个部分", + "check_logic": "在新增文档中筛选标题(不区分大小写)包含 'board meeting agenda' 或 'board agenda - june' 的文档,将其 content 拼接并转小写,检查是否同时包含 'approvals'、'financials'、'risks'", + "pass_condition": "存在新增议程文档且其内容同时包含 approvals、financials、risks 三个关键词" + }, + { + "name": "c2: cal_new_event", + "weight": 0.1, + "description": "检查是否在 Google Calendar 中创建了新事件", + "check_logic": "对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,按事件 id 判断是否有新增事件,并将新事件列表存入全局变量 cal_new_events", + "pass_condition": "存在至少一个 id 不在初始状态中的新事件" + }, + { + "name": "c3: Board Meeting event", + "weight": 0.1, + "description": "检查新创建的事件标题是否为董事会会议", + "check_logic": "读取 cal_new_events 中的新事件,检查任一事件的标题(不区分大小写)是否包含 'board meeting'", + "pass_condition": "至少一个新事件的标题包含 'board meeting'" + }, + { + "name": "c4: on June 30", + "weight": 0.2, + "description": "检查新事件是否安排在2026年6月30日", + "check_logic": "读取 cal_new_events 中的新事件,检查任一事件的 start 字段字符串是否包含 '2026-06-30'", + "pass_condition": "至少一个新事件的 start 字段包含 '2026-06-30'" + }, + { + "name": "c5: slack_new_msg", + "weight": 0.1, + "description": "检查 user_1 是否在 Slack #general 频道发送了新消息", + "check_logic": "获取 slack_mock current_state 中 general 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 集合中),筛选 senderId 为 'user_1' 的消息", + "pass_condition": "存在至少一条 senderId 为 'user_1' 且 messageId 不在初始 SEED 中的新消息" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数作为最终 REWARD", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空时,打印 CRITICAL 并输出 REWARD: 0.0 后退出", + "请求任一 mock 服务(google_docs_mock、notion_mock、google_calendar_mock、slack_mock)的 current_state 失败时,打印 CRITICAL 并输出 REWARD: 0.0 后退出", + "各评分组件检查失败仅导致该组件不得分,不会提前退出或导致总分归零" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务请求当前状态。若 sid 读取失败或任一 mock 状态获取失败,脚本立即输出 0.0 并退出。获取状态后,脚本按顺序执行 6 项评分检查:1)检查 Google Docs 中是否新增了标题匹配董事会会议议程的文档(0.2分);2)检查该新文档内容是否同时包含 approvals、financials、risks 三个部分(0.3分);3)检查 Google Calendar 是否新增了事件(0.1分);4)检查新事件标题是否包含 Board Meeting(0.1分);5)检查新事件日期是否为 2026-06-30(0.2分);6)检查 Slack #general 频道是否有 user_1 发送的新消息(0.1分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Reward Script: ea_board_prep_b101\n - Task ID: 2ae6814e-a7b8-5f0e-b574-5dd99095d0bf\n - Domain: mock_websites\n - Mocks: google_docs_mock, notion_mock, google_calendar_mock, slack_mock\n - Scoring total = 1.0\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从 MOCK_URLS 获取各个 mock 的 current_state:\n - google_docs_mock\n - notion_mock (虽然获取了状态,但评分中似乎没有用到)\n - google_calendar_mock\n - slack_mock\n\n3. 评分组件:\n - c0: 0.2 - new June board agenda doc\n - 检查 google_docs_mock 中是否有新文档(不在 initial_state 中)\n - 标题包含 'board meeting agenda', 'board meeting agenda - june', 'board agenda - june'\n - c1: 0.3 - agenda has the template's 3 sections\n - 检查新 Google Doc(标题包含 'board meeting agenda' 或 'board agenda - june')\n - 内容包含 'approvals', 'financials', 'risks'\n - c2: 0.1 - cal_new_event\n - 检查 google_calendar_mock 中是否有新事件(id 不在 initial_state 中)\n - c3: 0.1 - Board Meeting event\n - 检查新事件标题包含 'board meeting'\n - c4: 0.2 - on June 30\n - 检查新事件 start 日期包含 '2026-06-30'\n - c5: 0.1 - slack_new_msg\n - 检查 slack_mock #general 频道中 user_1 发送的新消息(不在 SEED 中)\n\n4. 分数汇总:\n - 各组件分数相加\n - 最后 min(total, 1.0) 并 round 到 4 位小数\n\n5. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取任何 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n6. 是否是占位脚本:\n - 不是,有详细的检查逻辑\n\n7. confidence:\n - 1.0,代码逻辑清晰\n\n现在构建 JSON:\n\ntask_id: \"2ae6814e-a7b8-5f0e-b574-5dd99095d0bf\"\ndomain: \"mock_websites\"\nsummary: \"验证用户是否创建了6月董事会会议议程文档、在日历中创建了6月30日的董事会会议事件,并在Slack #general频道发送了新消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"google_docs_mock\", \"google_calendar_mock\", \"slack_mock\", \"notion_mock\"]\nscoring_components: [\n {\n \"name\": \"c0: new June board agenda doc\",\n \"weight\": 0.2,\n \"description\": \"检查是否在 Google Docs 中创建了新的6月董事会会议议程文档\",\n \"check_logic\": \"对比 initial_state 和 current_state 的 documents,找出新增文档,检查标题(不区分大小写)是否包含 'board meeting agenda'、'board meeting agenda - june' 或 'board agenda - june'\",\n \"pass_condition\": \"存在新增文档且标题匹配上述关键词之一\"\n },\n {\n \"name\": \"c1: agenda has the template's 3 sections\",\n \"weight\": 0.3,\n \"description\": \"检查新创建的议程文档是否包含模板的三个部分\",\n \"check_logic\": \"在新增议程文档(标题匹配 c0 条件)的内容中,不区分大小写地检查是否同时包含 'approvals'、'financials' 和 'risks'\",\n \"pass_condition\": \"存在新增议程文档且其内容同时包含 approvals、financials、risks 三个关键词\"\n },\n {\n \"name\": \"c2: cal_new_event\",\n \"weight\": 0.1,\n \"description\": \"检查是否在 Google Calendar 中创建了新事件\",\n \"check_logic\": \"对比 initial_state 和 current_state 的 events,按事件 id 判断是否新增事件\",\n \"pass_condition\": \"存在 id 不在初始状态中的新事件\"\n },\n {\n \"name\": \"c3: Board Meeting event\",\n \"weight\": 0.1,\n \"description\": \"检查新创建的事件标题是否为董事会会议\",\n \"check_logic\": \"在 c2 识别出的新事件中,检查标题(不区分大小写)是否包含 'board meeting'\",\n \"pass_condition\": \"至少一个新事件的标题包含 'board meeting'\"\n },\n {\n \"name\": \"c4: on June 30\",\n \"weight\": 0.2,\n \"description\": \"检查新事件是否安排在2026年6月30日\",\n \"check_logic\": \"在 c2 识别出的新事件中,检查 start 字段是否包含 '2026-06-30'\",\n \"pass_condition\": \"至少一个新事件的 start 字段包含 '2026-06-30'\"\n },\n {\n \"name\": \"c5: slack_new_msg\",\n \"weight\": 0.1,\n \"description\": \"检查 user_1 是否在 Slack #general 频道发送了新消息\",\n \"check_logic\": \"获取 slack_mock current_state 中 general 频道的消息,排除 SEED 中预置的消息(messageId 不在 seed 中),检查 senderId 是否为 'user_1'\",\n \"pass_condition\": \"存在至少一条 senderId 为 'user_1' 且 messageId 不在 seed 中的新消息\"\n }\n]\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"请求任一 mock 服务(google_docs_mock、notion_mock、google_calendar_mock、slack_mock)的 current_state 失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"各评分组件检查失败仅导致该组件不得分,不会提前退出\"\n]\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_docs_mock、notion_mock、google_calendar_mock、slack_mock 四个 mock 服务请求当前状态。若 sid 读取失败或任一 mock 状态获取失败,脚本立即输出 0.0 并退出。获取状态后,脚本按顺序执行 6 项评分检查:1)检查 Google Docs 中是否新增了标题匹配董事会会议议程的文档(0.2分);2)检查该新文档内容是否同时包含 approvals、financials、risks 三个部分(0.3分);3)检查 Google Calendar 是否新增了事件(0.1分);4)检查新事件标题是否包含 Board Meeting(0.1分);5)检查新事件日期是否为 2026-06-30(0.2分);6)检查 Slack #general 频道是否有 user_1 发送的新消息(0.1分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 钳制并四舍五入后作为 REWARD 输出。\"\nconfidence: 1.0\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n让我再检查一下 notion_mock 是否在评分中被使用。代码中确实获取了 notion_mock 的状态,但评分逻辑中没有使用它。不过 data_sources 应该列出脚本获取状态的数据源,所以应该包含 notion_mock。\n\n再检查一下 c1 的标题匹配条件:代码中是 `['board meeting agenda', 'board agenda - june']`,比 c0 少了一个 'board meeting agenda - june'。我需要准确反映这一点。\n\nc0: `['board meeting agenda', 'board meeting agenda - june', 'board agenda - june']`\nc1: `['board meeting agenda', 'board agenda - june']`\n\nc5 的 SEED 检查:代码中 `c5_seed = set(SEED.get('slack_mock:general', []))`,然后 `m.get('messageId') not in c5_seed`。\n\n最终输出应该是一个纯 JSON。 {\"task_id\":\"2ae6814e-a7b8-5f0e-b574-5dd99095d0bf\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否创建了6月董事会会议议程文档、在日历中创建了6月30日的董事会会议事件,并在Slack #general频道发送了新消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_docs_mock\",\"notion_mock\",\"google_calendar_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"c0: new June board agenda doc\",\"weight\":0.2,\"description\":\"检查是否在 Google Docs 中创建了新的6月董事会会议议程文档\",\"check_logic\":\"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,筛选出新增文档(id 不在初始集合中),并检查其标题(不区分大小写)是否包含 'board meeting agenda'、'board meeting agenda - june' 或 'board agenda - june'\",\"pass_condition\":\"存在新增文档且标题匹配上述任一关键词\"},{\"name\":\"c1: agenda has the template's 3 sections\",\"weight\":0.3,\"description\":\"检查新创建的议程文档是否包含模板的三个部分\",\"check_logic\":\"在新增文档中筛选标题(不区分大小写)包含 'board meeting agenda' 或 'board agenda - june' 的文档,将其 content 拼接并转小写,检查是否同时包含 'approvals'、'financials'、'risks'\",\"pass_condition\":\"存在新增议程文档且其内容同时包含 approvals、financials、risks 三个关键词\"},{\"name\":\"c2: cal_new_event\",\"weight\":0.1,\"description\":\"检查是否在 Google Calendar 中创建了新事件\",\"check_logic\":\"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,按事件 id 判断是否有新增事件,并将新事件列表存入全局变量 cal_new_events\",\"pass_condition\":\"存在至少一个 id 不在初始状态中的新事件\"},{\"name\":\"c3: Board Meeting event\",\"weight\":0.1,\"description\":\"检查新创建的事件标题是否为董事会会议\",\"check_logic\":\"读取 cal_new_events 中的新事件,检查任一事件的标题(不区分大小写)是否包含 'board meeting'\",\"pass_condition\":\"至少一个新事件的标题包含 'board meeting'\"},{\"name\":\"c4: on June 30\",\"weight\":0.2,\"description\":\"检查新事件是否安排在2026年6月30日\",\"check_logic\":\"读取 cal_new_events 中的新事件,检查任一事件的 start 字段字符串是否包含 '2026-06-30'\",\"pass_condition\":\"至少一个新事件的 start 字段包含 '2026-06-30'\"},{\"name\":\"c5: slack_new_msg\",\"weight\":0.1,\"description\":\"检查 user_1 是否在 Slack #general 频道发送了新消息\",\"check_logic\":\"获取 slack_mock current_state 中 general 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 集合中),筛选 senderId 为 'user_1' 的消息\",\"pass_condition\":\"存在至少一条 senderId 为 'user_1' 且 messageId 不在初始 SEED 中的新消息\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数作为最终 REWARD\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空时,打印 CRITICAL 并输出 REWARD: 0.0 后退出\",\"请求任一 mock 服务(google_docs_mock、notion_mock、google_calendar_mock、slack_mock)的 current_state 失败时,打印 CRITICAL 并输出 REWARD: 0.0 后退出\",\"各评分组件检查失败仅导致该组件不得分,不会提前退出或导致总分归零\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务请求当前状态。若 sid 读取失败或任一 mock 状态获取失败,脚本立即输出 0.0 并退出。获取状态后,脚本按顺序执行 6 项评分检查:1)检查 Google Docs 中是否新增了标题匹配董事会会议议程的文档(0.2分);2)检查该新文档内容是否同时包含 approvals、financials、risks 三个部分(0.3分);3)检查 Google Calendar 是否新增了事件(0.1分);4)检查新事件标题是否包含 Board Meeting(0.1分);5)检查新事件日期是否为 2026-06-30(0.2分);6)检查 Slack #general 频道是否有 user_1 发送的新消息(0.1分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。\",\"confidence\":1.0}" +} diff --git a/ops_catalog_update_003__long/_cua_gym_vm_bridge.sh b/ops_catalog_update_003__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_catalog_update_003__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_catalog_update_003__long/initial_setup.py b/ops_catalog_update_003__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..60f05daf80fdb3d199e03acfc9452425407e9a67 --- /dev/null +++ b/ops_catalog_update_003__long/initial_setup.py @@ -0,0 +1,634 @@ +""" +Initial Setup: Product-listing review with a must-read listing standard & completeness bonus +Task ID: ops_catalog_update_003__long (output/0707 #25, cluster F / commerce) +Mocks: shopify_admin_mock, google_docs_mock, google_sheets_mock, slack_mock + +The agent is a catalog manager reviewing draft products and publishing the ready ones in +Shopify Admin per a LISTING STANDARD -- NOT in the instruction: + + * lever g/j (MUST-READ doc): the publish checklist + the product-type -> collection mapping + live in the google_docs 'Product Listing Standard' page (the Slack #catalog pin points to + it). A draft product may be published (status active) only if it has an image, a non-empty + description, at least one variant priced > 0, and a productType. When publishing, the item + is assigned to a collection by the doc's product-type -> collection mapping. + * lever i (bulk + keep-group): 12 products. 7 draft & ready-to-publish; 3 draft but FAIL the + checklist (missing image / description / price -> leave draft); 2 already active (keep). + Publishing an incomplete/keep product, or logging a wrong collection, lowers F1 / field + correctness. Denominator = the 7. + * lever j (completeness bonus): a 0.10 bonus awarded ONLY if the core review subtotal >= 0.60 + (like OSW2 070), rewarding full coverage of the ready set. + +Publish = set product.status 'active'. The agent logs a "Listing Log" register +(Product, ProductType, Collection) and posts a summary to #catalog. + +GROUND TRUTH: google_sheets._task_adapter (expected_log, ready_ids, type_by_id, collection_by_id, +incomplete_ids, keep_ids, completeness_*) + shopify.products[*]._lst. +Observable results ship ABSENT (Rule 3): ready products status 'draft', Listing Log header-only, +no summary. + +SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't publish incomplete/keep" is an F1 +PRECISION denominator; the completeness bonus is a POSITIVE add gated on a subtotal (like OSW2 +070), NOT a penalty; total stays in [0,1]. No hard gate, no LLM judge. +""" +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}') + + +COMPLETENESS_THRESHOLD = 0.60 +COMPLETENESS_BONUS = 0.10 + +# product-type -> collection mapping (lives in the google_docs standard) +TYPE_TO_COLLECTION = { + 'Shirts': 'Apparel', + 'Hoodies': 'Apparel', + 'Mugs': 'Drinkware', + 'Bottles': 'Drinkware', + 'Bags': 'Accessories', + 'Hats': 'Accessories', + 'Stationery': 'Office', +} + + +# --------------------------------------------------------------------------- +# Product spec: (pid, title, ptype, has_image, has_desc, price, kind) +# kind: 'ready' (draft, passes checklist -> publish) / +# 'incomplete' (draft, fails checklist -> leave draft) / +# 'keep' (already active) +# --------------------------------------------------------------------------- +_PROD_SPEC = [ + # --- 7 draft & ready to publish (image + desc + price>0 + type) --- + ('prod_1', 'Classic Tee - Black', 'Shirts', True, True, 24.99, 'ready'), + ('prod_2', 'Classic Tee - White', 'Shirts', True, True, 24.99, 'ready'), + ('prod_3', 'Zip Hoodie - Grey', 'Hoodies', True, True, 49.00, 'ready'), + ('prod_4', 'Ceramic Mug 12oz', 'Mugs', True, True, 14.00, 'ready'), + ('prod_5', 'Steel Bottle 24oz', 'Bottles', True, True, 28.00, 'ready'), + ('prod_6', 'Canvas Tote', 'Bags', True, True, 18.00, 'ready'), + ('prod_7', 'Dad Cap - Navy', 'Hats', True, True, 22.00, 'ready'), + # --- 3 draft but FAIL the checklist (leave draft) --- + ('prod_8', 'Beanie (no image yet)', 'Hats', False, True, 20.00, 'incomplete'), # no image + ('prod_9', 'Notebook (no desc)', 'Stationery', True, False, 9.00, 'incomplete'), # no description + ('prod_10', 'Sticker Pack (no price)', 'Stationery', True, True, 0.0, 'incomplete'), # price 0 + # --- 2 already active (keep) --- + ('prod_11', 'Enamel Pin', 'Accessories-legacy', True, True, 8.00, 'keep'), + ('prod_12', 'Lanyard', 'Accessories-legacy', True, True, 6.00, 'keep'), +] + + +def _collection_of(ptype): + return TYPE_TO_COLLECTION.get(ptype, '') + + +def _passes_checklist(has_image, has_desc, price, ptype): + return bool(has_image and has_desc and price and price > 0 and ptype) + + +# --------------------------------------------------------------------------- +# Precompute answer key. +# --------------------------------------------------------------------------- +EXPECTED_LOG = [] +READY_IDS = [] +TYPE_BY_ID = {} +COLLECTION_BY_ID = {} +for (pid, title, ptype, has_image, has_desc, price, kind) in _PROD_SPEC: + if kind != 'ready': + continue + coll = _collection_of(ptype) + READY_IDS.append(pid) + TYPE_BY_ID[pid] = ptype + COLLECTION_BY_ID[pid] = coll + EXPECTED_LOG.append({'Product': title, 'ProductType': ptype, 'Collection': coll}) + +INCOMPLETE_IDS = [p[0] for p in _PROD_SPEC if p[6] == 'incomplete'] +KEEP_IDS = [p[0] for p in _PROD_SPEC if p[6] == 'keep'] +TITLE_BY_ID = {p[0]: p[1] for p in _PROD_SPEC} + +assert len(READY_IDS) == 7, READY_IDS +assert len(INCOMPLETE_IDS) == 3 and len(KEEP_IDS) == 2, (INCOMPLETE_IDS, KEEP_IDS) +# every ready product passes the checklist; every incomplete fails it +for (pid, title, ptype, hi, hd, pr, kind) in _PROD_SPEC: + passes = _passes_checklist(hi, hd, pr, ptype) + if kind == 'ready': + assert passes, (pid, 'ready but fails checklist') + elif kind == 'incomplete': + assert not passes, (pid, 'incomplete but passes checklist') +print(f'Ready: {READY_IDS}; incomplete(leave draft): {INCOMPLETE_IDS}; keep: {KEEP_IDS}') + + +# --------------------------------------------------------------------------- +# Shopify Admin — draft products (ready in 'draft', keep in 'active') + inventory. +# NOTE (review #4): product images previously pointed at https://placehold.co/... which needs +# network access and shows broken thumbnails offline. Image URLs do NOT affect scoring (reward +# judges only status draft->active), but for offline robustness + realism we embed a tiny inline +# SVG data: URI so a real thumbnail renders with no network. +# --------------------------------------------------------------------------- +import base64 as _b64 + + +def _img_data_uri(label): + svg = ( + "" + "" + "" + label + "" + ) + return 'data:image/svg+xml;base64,' + _b64.b64encode(svg.encode('utf-8')).decode('ascii') + + +def _build_product(pid, title, ptype, has_image, has_desc, price, kind): + status = 'active' if kind == 'keep' else 'draft' + images = ([{'id': f'img_{pid}', 'src': _img_data_uri(title), 'alt': title, 'position': 1}] + if has_image else []) + body = f'

{title} — premium quality.

' if has_desc else '' + return { + 'id': pid, 'title': title, 'bodyHtml': body, 'vendor': 'Evergreen', + 'productType': ptype, 'handle': pid, 'status': status, 'tags': [], 'images': images, + 'variants': [{'id': f'var_{pid}', 'productId': pid, 'title': 'Default', + 'price': f'{price:.2f}', 'compareAtPrice': None, 'sku': pid.upper(), + 'inventoryQuantity': 50, 'option1': 'Default', 'option2': None, 'position': 1}], + 'options': [{'id': f'opt_{pid}', 'name': 'Title', 'position': 1, 'values': ['Default']}], + 'collections': [], 'createdAt': '2026-04-20T10:00:00Z', 'updatedAt': '2026-04-29T14:30:00Z', + '_lst': {'kind': kind, 'title': title, 'ptype': ptype, + 'collection': _collection_of(ptype) if kind == 'ready' else ''}, + } + + +_PRODUCTS = [_build_product(*spec) for spec in _PROD_SPEC] + +_SHOPIFY_STATE = { + 'store': {'id': 'store_1', 'name': 'Evergreen Goods', 'email': 'admin@evergreengoods.com', + 'phone': '', 'domain': 'evergreengoods.myshopify.com', 'customDomain': '', + 'address': '', 'currency': 'USD', 'timezone': '(GMT-08:00) Pacific Time', + 'weightUnit': 'lb', 'plan': 'Basic Shopify', + 'owner': {'firstName': 'Nadia', 'lastName': 'Farouk', 'email': 'nadia@evergreengoods.com'}, + 'createdAt': '2024-01-01T00:00:00Z'}, + 'products': _PRODUCTS, + 'collections': [ + {'id': 'col_apparel', 'title': 'Apparel', 'bodyHtml': '', 'handle': 'apparel', + 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual', + 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None}, + {'id': 'col_drinkware', 'title': 'Drinkware', 'bodyHtml': '', 'handle': 'drinkware', + 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual', + 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None}, + {'id': 'col_accessories', 'title': 'Accessories', 'bodyHtml': '', 'handle': 'accessories', + 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual', + 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None}, + {'id': 'col_office', 'title': 'Office', 'bodyHtml': '', 'handle': 'office', + 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual', + 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None}, + ], + 'orders': [], 'customers': [], 'discounts': [], 'draftOrders': [], 'giftCards': [], + 'analytics': {'dailyMetrics': [], 'totalSalesThisMonth': 0, 'totalOrdersThisMonth': 0, + 'totalSessionsThisMonth': 0}, + 'pages': [], 'blogPosts': [], 'navigationMenus': [], + 'settings': {'storeName': 'Evergreen Goods', 'storeEmail': 'admin@evergreengoods.com', + 'currency': 'USD', 'timezone': '(GMT-08:00) Pacific Time', 'weightUnit': 'lb'}, + '_task_adapter': {'source_schema': 'listing_review', + 'task_id': 'b8d2ef43-0c4a-4e9f-da71-0707ddee7788'}, +} + + +# --------------------------------------------------------------------------- +# google_docs — the must-read 'Product Listing Standard' (lever j) + a decoy. +# NOTE (review #2): google_docs_mock renders each doc card via +# format(new Date(doc.updated), ...) and sorts on doc.created/doc.updated. If those fields are +# absent (we previously used createdAt/modifiedAt), date-fns throws "Invalid time value" and the +# whole document list crashes to a blank screen -> search finds nothing. So use created/updated. +# --------------------------------------------------------------------------- +def _standard_html(): + rows = ''.join(f'
  • {t} → {c}
  • ' for t, c in TYPE_TO_COLLECTION.items()) + return ( + '

    Product Listing Standard

    ' + '

    Publish checklist

    ' + '

    A draft product may be published (set status Active) ONLY if it has ALL of:

    ' + '
    • at least one product image
    • ' + '
    • a non-empty description
    • ' + '
    • at least one variant with a price greater than 0
    • ' + '
    • a product type assigned
    ' + '

    If any item is missing, leave the product as a draft.

    ' + '

    Collection assignment (by product type)

    ' + f'
      {rows}
    ' + '

    When you publish a product, assign it to the collection its product type maps to above.

    ' + ) + + +_DOCS_STATE = { + 'user': {'id': 'user-1', 'name': 'Nadia Farouk', 'email': 'nadia@evergreengoods.com'}, + 'documents': { + 'doc-standard': {'id': 'doc-standard', 'title': 'Product Listing Standard', + 'content': _standard_html(), 'ownerId': 'user-1', 'starred': True, + 'created': '2026-01-05T09:00:00Z', 'updated': '2026-03-01T09:00:00Z', + 'sharedWith': [], 'linkSharing': {'enabled': False}}, + 'doc-decoy': {'id': 'doc-decoy', 'title': 'Brand Voice Guide', + 'content': '

    Brand Voice

    Friendly and concise.

    ', + 'ownerId': 'user-1', 'starred': False, 'created': '2026-02-01T09:00:00Z', + 'updated': '2026-02-01T09:00:00Z', 'sharedWith': [], + 'linkSharing': {'enabled': False}}, + }, + 'comments': [], + 'ui': {'currentDocId': None, 'documentListView': 'grid', 'searchQuery': ''}, +} + + +# --------------------------------------------------------------------------- +# Google Sheet — 'Listing Log' register (header only) + answer key. +# --------------------------------------------------------------------------- +REG_HEADERS = ['Product', 'ProductType', 'Collection'] +_HEADER_STYLE = {'bold': True, 'bg': '#F3F3F3', 'align': 'center'} + + +def _header_cell(text): + return {'value': text, 'formula': text, 'computed': text, 'style': dict(_HEADER_STYLE)} + + +_reg_data = {} +for col_idx, header in enumerate(REG_HEADERS): + _reg_data[f'{chr(ord("A") + col_idx)}1'] = _header_cell(header) + + +_SHEET_STATE = { + 'id': 'workbook_listing', 'title': 'Catalog Workbook', + 'activeSheetId': 'sheet_reg', 'selectedCell': 'A1', 'selectionRange': None, + 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [], + 'namedRanges': [], 'conditionalFormats': [], 'charts': [], 'showGridlines': True, + 'showFormulas': False, 'zoom': 100, + 'sheets': [{ + 'id': 'sheet_reg', 'name': 'Listing Log', 'data': _reg_data, + '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': 'listing_review', + 'task_id': 'b8d2ef43-0c4a-4e9f-da71-0707ddee7788', + 'variant': 'eval', + 'target_sheet': 'Listing Log', + 'headers': REG_HEADERS, + 'headers_by_sheet': {'Listing Log': REG_HEADERS}, + 'sheet_names': ['Listing Log'], + 'published_status': 'active', + # ---- ANSWER KEY ---- + 'expected_log': EXPECTED_LOG, + 'ready_ids': READY_IDS, + 'type_by_id': TYPE_BY_ID, + 'collection_by_id': COLLECTION_BY_ID, + 'title_by_id': TITLE_BY_ID, + 'incomplete_ids': INCOMPLETE_IDS, + 'keep_ids': KEEP_IDS, + 'type_to_collection': TYPE_TO_COLLECTION, + 'completeness_threshold': COMPLETENESS_THRESHOLD, + 'completeness_bonus': COMPLETENESS_BONUS, + 'catalog_channel': 'catalog', + }, +} + + +# --------------------------------------------------------------------------- +# Slack — #catalog pin pointing to the listing standard (lever j pointer). +# Review #1: give every user fullName+displayName (slack_mock renders authors via +# users[].userId -> fullName else displayName else "Unknown User"); add extra channels + +# harmless chatter so #catalog looks active and the pinned note sits above real backlog. +# --------------------------------------------------------------------------- +_PIN_TEXT = ( + ':pushpin: CATALOG: before publishing draft products, follow the "Product Listing Standard" ' + 'doc in Google Docs — it has the publish checklist and the product-type to collection mapping. ' + 'Log every product you publish in the Listing Log sheet.' +) + + +def _slack_user(uid, first, last): + full = f'{first} {last}' + return {'userId': uid, 'firstName': first, 'lastName': last, 'name': full, + 'fullName': full, 'displayName': full} + + +_SLACK_USERS = [ + _slack_user('user_1', 'Nadia', 'Farouk'), # catalog manager (current user) + _slack_user('user_2', 'Dana', 'Cole'), # ops lead (posts the pin) + _slack_user('user_3', 'Theo', 'Marsh'), # merchandiser + _slack_user('user_4', 'Priya', 'Raman'), # content +] + + +def _smsg(mid, ch, sender, content, ts): + return {'messageId': mid, 'senderId': sender, 'content': content, 'timestamp': ts, + 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False} + + +_CATALOG_HISTORY = [ + _smsg('msg_pin', 'catalog', 'user_2', _PIN_TEXT, '2026-04-01T09:00:00Z'), + _smsg('msg_c1', 'catalog', 'user_3', 'New spring drop photos are in the shared drive — 7 products staged as drafts.', '2026-04-28T10:00:00Z'), + _smsg('msg_c2', 'catalog', 'user_4', 'Descriptions written for all but the beanie; that one still needs copy.', '2026-04-29T11:15:00Z'), + _smsg('msg_c3', 'catalog', 'user_2', '@Nadia can you review the drafts and publish the ones that pass the standard today?', '2026-04-30T08:30:00Z'), + _smsg('msg_c4', 'catalog', 'user_1', 'On it — going through Shopify drafts now and will log what I publish.', '2026-04-30T08:45:00Z'), +] + +_GENERAL_HISTORY = [ + _smsg('msg_g1', 'general', 'user_2', 'Welcome to Evergreen Goods :wave:', '2026-04-15T09:00:00Z'), + _smsg('msg_g2', 'general', 'user_3', 'Reminder: warehouse inventory count this Friday.', '2026-04-27T14:00:00Z'), + _smsg('msg_g3', 'general', 'user_4', 'Q2 marketing calendar is published in Docs.', '2026-04-29T16:30:00Z'), +] + +_SLACK_STATE = { + 'currentUser': _slack_user('user_1', 'Nadia', 'Farouk'), + 'users': _SLACK_USERS, + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide', + 'topic': 'General', 'isPrivate': False, 'isStarred': True, + 'members': [u['userId'] for u in _SLACK_USERS], 'createdBy': 'user_2', + 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'catalog', 'name': 'catalog', 'description': 'Catalog management', + 'topic': 'Listings', 'isPrivate': False, 'isStarred': True, + 'members': [u['userId'] for u in _SLACK_USERS], 'createdBy': 'user_2', + 'createdAt': '2026-01-01T10:00:00Z', 'pinnedMessages': ['msg_pin'], 'unreadCount': 0}, + ], + 'messages': { + 'general': _GENERAL_HISTORY, + 'catalog': _CATALOG_HISTORY, + }, + 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [], 'notifications': [], +} + + +# --------------------------------------------------------------------------- +# Inject. +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8177', _SHOPIFY_STATE), # shopify_admin_mock + ('http://28.7.184.198:8142', _DOCS_STATE), # google_docs_mock + ('http://28.7.184.198:8145', _SHEET_STATE), # google_sheets_mock + ('http://28.7.184.198:8178', _SLACK_STATE), # slack_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/ops_catalog_update_003__long/reward.py b/ops_catalog_update_003__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..cba3802366559c3d6f8d9c60f171bcfbe87c9eb2 --- /dev/null +++ b/ops_catalog_update_003__long/reward.py @@ -0,0 +1,326 @@ +""" +Reward Script: Product-listing review with a must-read listing standard & completeness bonus +Task ID: ops_catalog_update_003__long (output/0707 #25, cluster F / commerce) +Mocks: shopify_admin_mock, google_docs_mock, google_sheets_mock, slack_mock + +Scoring — ALL positive; every component in [0,1]; core weights sum to 0.90 and ONE +completeness bonus (0.10) gated on the core subtotal >= 0.60. NO penalties, NO hard gate. + + CORE (0.90): + 0.30 publish decision-set F1: true={7 ready products}; pred={products set to status active} + (publishing an incomplete/keep product = precision FP) + 0.20 product-type correctness in the log: frac of the 7 logged with correct ProductType + 0.15 collection correctness: frac of the 7 logged with correct Collection (per doc mapping) + 0.20 listing-log F1 over (Product, ProductType, Collection) for the 7 + 0.05 slack #catalog summary post + BONUS (0.10), gated: + 0.10 completeness bonus, awarded ONLY if core subtotal >= 0.60 (like OSW2 070). Positive add. + +Answer key: google_sheets.initial_state._task_adapter (expected_log, ready_ids, type_by_id, +collection_by_id, title_by_id, incomplete_ids, keep_ids, completeness_*, published_status) + +shopify.products[*]._lst. +""" +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 = { + 'shopify': 'http://28.7.184.198:8177', + 'google_sheets': 'http://28.7.184.198:8145', + '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 norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _s(v): + return '' if v is None else str(v).strip() + + +def _msg_text(m): + return m.get('content') or m.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + 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) or 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 _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 _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 _cell_disp(cell): + 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 _raw_sheet(state, name): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + for sh in sheets: + if isinstance(sh, dict) and (norm(sh.get('name')) == norm(name) or norm(sh.get('id')) == norm(name)): + return sh + if len(sheets) == 1 and isinstance(sheets[0], dict): + return sheets[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 + grid.setdefault(r, {})[c] = _cell_disp(cell) + return grid + + +# =========================================================================== +def reward(go): + W_PUBF1 = 0.30 + W_TYPE = 0.20 + W_COLL = 0.15 + W_LOGF1 = 0.20 + W_POST = 0.05 + + # ---- 1) answer key ---- + 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_log = adapter.get('expected_log') if isinstance(adapter.get('expected_log'), list) else [] + ready_ids = list(adapter.get('ready_ids') or []) + type_by_id = {norm(k): norm(v) for k, v in (adapter.get('type_by_id') or {}).items()} + collection_by_id = {norm(k): norm(v) for k, v in (adapter.get('collection_by_id') or {}).items()} + title_by_id = {norm(k): norm(v) for k, v in (adapter.get('title_by_id') or {}).items()} + published_status = norm(adapter.get('published_status') or 'active') + comp_threshold = adapter.get('completeness_threshold', 0.60) + comp_bonus = adapter.get('completeness_bonus', 0.10) + channel = adapter.get('catalog_channel') or 'catalog' + target_sheet = adapter.get('target_sheet') or 'Listing Log' + n_ready = len(ready_ids) + if n_ready == 0: + print('DEBUG_SHOP_LISTING fatal=no_ready_ids total=0.0') + return 0.0 + + # ---- 2) shopify: diff product status; only NEWLY-published (draft->active) count ---- + gh = go('shopify') + gh_init = gh.get('initial_state', {}) if isinstance(gh.get('initial_state'), dict) else {} + gh_cur = gh.get('current_state', {}) if isinstance(gh.get('current_state'), dict) else {} + + def _prod_map(state): + out = {} + for p in (state.get('products') or []): + if isinstance(p, dict): + out[p.get('id')] = p + return out + + init_p = _prod_map(gh_init) + cur_p = _prod_map(gh_cur) + newly_pub = {pid for pid, p in cur_p.items() + if norm(p.get('status')) == published_status + and norm(init_p.get(pid, {}).get('status')) != published_status} + + true_ids = {norm(i) for i in ready_ids} + pub_ids = {norm(i) for i in newly_pub} + pub_f1 = f1(true_ids, pub_ids) + s_pubf1 = W_PUBF1 * pub_f1 + + # ---- 3) parse Listing Log rows; index by title ---- + sheet = _raw_sheet(gs_cur, target_sheet) + grid = _grid(sheet) if sheet is not None else {} + log_rows = [] + for r in sorted(grid.keys()): + if r <= 1: + continue + row = grid[r] + prod = _s(row.get(0)) + ptype = _s(row.get(1)) + coll = _s(row.get(2)) + if not prod and not ptype and not coll: + continue + log_rows.append({'Product': prod, 'ProductType': ptype, 'Collection': coll}) + + # map title(lower) -> id(lower) for the ready set + id_by_title = {t: i for i, t in title_by_id.items()} + logged_by_id = {} + for r in log_rows: + pid = id_by_title.get(norm(r['Product'])) + if pid and pid not in logged_by_id: + logged_by_id[pid] = r + + # ---- 4) product-type correctness over the 7 ---- + type_ok = 0 + for pid in true_ids: + r = logged_by_id.get(pid) + if r and norm(r.get('ProductType')) == type_by_id.get(pid): + type_ok += 1 + type_score = frac(type_ok, n_ready) + s_type = W_TYPE * type_score + + # ---- 5) collection correctness over the 7 ---- + coll_ok = 0 + for pid in true_ids: + r = logged_by_id.get(pid) + if r and norm(r.get('Collection')) == collection_by_id.get(pid): + coll_ok += 1 + coll_score = frac(coll_ok, n_ready) + s_coll = W_COLL * coll_score + + # ---- 6) listing-log F1 over (Product, ProductType, Collection) ---- + def _log_key(prod, ptype, coll): + return (norm(prod), norm(ptype), norm(coll)) + + true_log = {_log_key(d['Product'], d['ProductType'], d['Collection']) for d in expected_log} + pred_log = {_log_key(r['Product'], r['ProductType'], r['Collection']) for r in log_rows + if _s(r['Product'])} + log_f1 = f1(true_log, pred_log) + s_logf1 = W_LOGF1 * log_f1 + + # ---- 7) slack summary post ---- + slack = go('slack') + scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + sinit = slack.get('initial_state', {}) if isinstance(slack.get('initial_state'), dict) else {} + init_msg = {(m.get('messageId') or m.get('id')) + for m in _slack_channel_messages(sinit, channel) if isinstance(m, dict)} + _catalog_kw = ('publish', 'product', 'catalog', 'listing', 'collection') + def _is_catalog_summary(m): + t = (_msg_text(m) or '').lower() + return any(k in t for k in _catalog_kw) + new_msgs = [m for m in _slack_channel_messages(scur, channel) + if isinstance(m, dict) + and (m.get('messageId') or m.get('id')) not in init_msg + and (_msg_text(m) or '').strip()] + post_ok = any(_is_catalog_summary(m) for m in new_msgs) + s_post = W_POST * (1.0 if post_ok else 0.0) + + # ---- 8) core subtotal + completeness bonus ---- + core = s_pubf1 + s_type + s_coll + s_logf1 + s_post + bonus = comp_bonus if core >= comp_threshold else 0.0 + score = clamp01(core + bonus) + + print( + 'DEBUG_SHOP_LISTING ' + f'n_ready={n_ready} published={len(pub_ids)} pub_f1={round(pub_f1, 4)} ' + f'type_ok={type_ok}/{n_ready} coll_ok={coll_ok}/{n_ready} log_f1={round(log_f1, 4)} ' + f'post={post_ok} core={round(core, 4)} bonus={bonus} ' + f'w_pubf1={round(s_pubf1, 4)} w_type={round(s_type, 4)} w_coll={round(s_coll, 4)} ' + f'w_logf1={round(s_logf1, 4)} w_post={round(s_post, 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/ops_inbox_meeting_007/_cua_gym_vm_bridge.sh b/ops_inbox_meeting_007/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_inbox_meeting_007/_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_inbox_meeting_007/initial_setup.py b/ops_inbox_meeting_007/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3f6ee45c122d74bfa5e253340443c092bf5c093d --- /dev/null +++ b/ops_inbox_meeting_007/initial_setup.py @@ -0,0 +1,257 @@ +""" +Initial Setup: ea_meeting_from_inbox_b100 +Task ID: ops_inbox_meeting_007 +Domain: mock_websites +Mocks: gmail_mock, google_calendar_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as an operations associate. Your tools for this task are: the shared email inbox, the team calendar, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Gmail inbox with 3 email(s): "Your industry roundup" from news@digest.com; "Prep call before the board meeting?" from chair@board.org; "FYI: office closed July 4" from facilities@company.com; an empty Google Calendar; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: cal_new_event (+0.2); event titled Board Prep Call (+0.2); on June 26 (+0.2); gmail_new_sent (+0.1); replied to the board chair (+0.2); slack_new_msg (+0.1). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "gmail_mock": "http://28.7.184.198:8138", + "google_calendar_mock": "http://28.7.184.198:8141", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8138' + +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 = { 'gmail_mock': { 'user': { 'userId': 'u1', + 'username': 'John Smith', + 'email': 'john.smith@company.com', + 'avatar': ''}, + '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'}], + 'emails': [ { 'id': 'email_1', + 'threadId': 'thread_email_1', + 'from': { 'name': 'Weekly Digest', + 'email': 'news@digest.com', + 'avatar': ''}, + 'to': [ { 'name': 'John Smith', + 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'subject': 'Your industry roundup', + 'body': '

    Top 10 stories this week.

    ', + 'snippet': 'Top 10 stories.', + 'timestamp': '2026-06-08T08:15:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'updates', + 'folder': 'inbox', + 'attachments': []}, + { 'id': 'email_2', + 'threadId': 'thread_email_2', + 'from': { 'name': 'Eleanor Vance', + 'email': 'chair@board.org', + 'avatar': ''}, + 'to': [ { 'name': 'John Smith', + 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'subject': 'Prep call before the board meeting?', + 'body': '

    Could we do a 30-minute prep call on June 26 ' + 'at 10:00 AM? Want to align on the agenda.

    ', + 'snippet': '30-min prep call June 26 10am?', + 'timestamp': '2026-06-08T08:15:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'folder': 'inbox', + 'attachments': []}, + { 'id': 'email_3', + 'threadId': 'thread_email_3', + 'from': { 'name': 'Facilities', + 'email': 'facilities@company.com', + 'avatar': ''}, + 'to': [ { 'name': 'John Smith', + 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'subject': 'FYI: office closed July 4', + 'body': '

    Reminder the office is closed July 4.

    ', + 'snippet': 'Office closed July 4.', + 'timestamp': '2026-06-08T08:15:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'updates', + 'folder': 'inbox', + 'attachments': []}], + 'drafts': []}, + '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}}, + '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': 'did the board prep call get ' + 'scheduled?', + '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/ops_inbox_meeting_007/reward.py b/ops_inbox_meeting_007/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..5b91697a7f314846d97be5bbb0d517544bf5c26b --- /dev/null +++ b/ops_inbox_meeting_007/reward.py @@ -0,0 +1,107 @@ +""" +Reward Script: ea_meeting_from_inbox_b100 +Task ID: ops_inbox_meeting_007 +Domain: mock_websites +Mocks: gmail_mock, google_calendar_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.2] cal_new_event + - [0.2] event titled Board Prep Call + - [0.2] on June 26 + - [0.2] gmail_new_sent + - [0.2] replied to the board chair +""" +import re +import sys + +import requests + +MOCK_URLS = { + "gmail_mock": "http://28.7.184.198:8138", + "google_calendar_mock": "http://28.7.184.198:8141" +} + +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.2)') + total += 0.2 +else: + print('FAIL: no new calendar event') + +# c1: new event title (event titled Board Prep Call) +c1_new = globals().get('cal_new_events', []) +if any(any(t in _lc(e.get('title','')) for t in ['board prep call', 'board prep', 'prep call']) for e in c1_new): + print('PASS: event titled Board Prep Call (0.2)') + total += 0.2 +else: + print('FAIL: event titled Board Prep Call') + +# c2: new event date contains '2026-06-26' +c2_new = globals().get('cal_new_events', []) +if any('2026-06-26' in (e.get('start','') or '') for e in c2_new): + print('PASS: on June 26 (0.2)') + total += 0.2 +else: + print('FAIL: on June 26') + +# c3: a new email was sent (folder sent) or saved as draft +c3_init = (STATES['gmail_mock'].get('initial_state') or {}) +c3_cur = cur('gmail_mock') +c3_init_ids = {e.get('id') for e in (c3_init.get('emails') or [])} +c3_sent = [e for e in (c3_cur.get('emails') or []) if e.get('id') not in c3_init_ids and e.get('folder') in ('sent', 'drafts')] +c3_sent += [d for d in (c3_cur.get('drafts') or []) if d.get('id') not in {x.get('id') for x in (c3_init.get('drafts') or [])}] +if c3_sent: + print('PASS: new email sent/drafted (0.2)') + total += 0.2 +else: + print('FAIL: no new sent/draft email') + +# c4: sent/draft email addressed to (replied to the board chair) +c4_init = (STATES['gmail_mock'].get('initial_state') or {}) +c4_cur = cur('gmail_mock') +c4_init_ids = {e.get('id') for e in (c4_init.get('emails') or [])} +c4_pool = [e for e in (c4_cur.get('emails') or []) if e.get('id') not in c4_init_ids and e.get('folder') in ('sent','drafts')] + (c4_cur.get('drafts') or []) +c4_tos = _lc(' '.join(t.get('email','') for e in c4_pool for t in (e.get('to') or []))) +if any(t in c4_tos for t in ['chair@board.org']): + print('PASS: replied to the board chair (0.2)') + total += 0.2 +else: + print('FAIL: replied to the board chair') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/ops_inbox_meeting_007/reward_label.json b/ops_inbox_meeting_007/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..88f63e92a113ab1187ed5e900b2ca87907f8a648 --- /dev/null +++ b/ops_inbox_meeting_007/reward_label.json @@ -0,0 +1,78 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/c4ce61fa-20a5-563d-8bba-542633ab52bc/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:47", + "label": { + "task_id": "ops_inbox_meeting_007", + "domain": "mock_websites", + "summary": "验证用户是否在Google Calendar新建了6月26日的Board Prep Call会议、通过Gmail向董事会主席发送/草拟了邮件,并在Slack的#general频道以user_1身份发送了新消息", + "is_placeholder": false, + "data_sources": [ + "gmail_mock", + "google_calendar_mock", + "slack_mock", + "/tmp/task_web_sid" + ], + "scoring_components": [ + { + "name": "cal_new_event", + "weight": 0.2, + "description": "检查Google Calendar是否创建了新的日历事件", + "check_logic": "对比google_calendar_mock的initial_state.events与current_state.events,收集id不在初始集合中的事件存入cal_new_events;若cal_new_events非空则通过", + "pass_condition": "current_state.events中存在id不在initial_state.events中的新事件" + }, + { + "name": "event titled Board Prep Call", + "weight": 0.2, + "description": "检查新建日历事件的标题是否包含Board Prep Call相关关键词", + "check_logic": "遍历cal_new_events,将title转小写后检查是否包含'board prep call'、'board prep'或'prep call'任一子串", + "pass_condition": "新事件的title字段(忽略大小写)包含上述任一关键词" + }, + { + "name": "on June 26", + "weight": 0.2, + "description": "检查新建日历事件的开始日期是否为2026-06-26", + "check_logic": "遍历cal_new_events,检查start字段(字符串)中是否包含'2026-06-26'", + "pass_condition": "至少一个新事件的start字段包含'2026-06-26'" + }, + { + "name": "gmail_new_sent", + "weight": 0.1, + "description": "检查Gmail是否有新发送的邮件或新保存的草稿", + "check_logic": "收集current_state.emails中id不在initial_state.emails且folder为'sent'或'drafts'的邮件,并收集current_state.drafts中id不在initial_state.drafts的草稿;若合并后列表非空则通过", + "pass_condition": "存在新的sent邮件或新的draft" + }, + { + "name": "replied to the board chair", + "weight": 0.2, + "description": "检查新邮件/草稿的收件人是否包含董事会主席邮箱", + "check_logic": "构建c4_pool(新sent/drafts邮件加上current_state.drafts),提取所有to列表中的email字段拼接为小写字符串,检查是否包含'chair@board.org'", + "pass_condition": "新邮件/草稿的收件人邮箱中包含'chair@board.org'" + }, + { + "name": "slack_new_msg", + "weight": 0.1, + "description": "检查Slack #general频道是否有user_1发送的新消息", + "check_logic": "获取current_state.messages.general,排除SEED中预置的messageId(如'g1'),筛选senderId为'user_1'的消息;若存在则通过", + "pass_condition": "#general频道中存在messageId不在SEED且senderId为'user_1'的新消息" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加求和,最终通过min(total, 1.0)将总分钳制在1.0上限,并四舍五入保留4位小数", + "failure_modes": [ + "读取/tmp/task_web_sid失败或内容为空时打印CRITICAL并返回0.0", + "任一mock服务(gmail_mock、google_calendar_mock、slack_mock)状态拉取失败时打印CRITICAL并返回0.0", + "未创建新日历事件导致c0失败,无法获得后续c1、c2的分数", + "新事件标题不匹配关键词导致c1失败", + "新事件start字段不含'2026-06-26'导致c2失败", + "无新sent/draft邮件导致c3失败", + "新邮件未发送给chair@board.org导致c4失败", + "user_1未在#general发送新消息导致c5失败" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向gmail_mock、google_calendar_mock、slack_mock发送请求拉取各自的current_state和initial_state。若任何一步失败则直接退出并返回0.0。评分按顺序执行6个组件:先通过对比initial_state与current_state的events列表识别新日历事件(0.2分);再检查这些新事件的标题是否包含Board Prep Call相关关键词(0.2分)以及start字段是否包含2026-06-26(0.2分);接着检查Gmail中是否有新的sent邮件或drafts(0.1分),并进一步检查这些新邮件的收件人是否包含chair@board.org(0.2分);最后检查Slack #general频道中是否有user_1发送的新消息(0.1分)。每个组件独立判断,通过则累加对应分值,不通过则仅打印FAIL不扣分也不中断。最终总分经min(total, 1.0)钳制后四舍五入到4位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Task ID: c4ce61fa-20a5-563d-8bba-542633ab52bc\n - Domain: mock_websites\n - Mocks: gmail_mock, google_calendar_mock, slack_mock\n - Scoring total = 1.0\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:gmail_mock, google_calendar_mock, slack_mock\n\n3. 评分组件:\n - c0: cal_new_event (0.2) - 检查是否有新的日历事件创建\n - c1: event titled Board Prep Call (0.2) - 检查新事件标题是否包含 'board prep call', 'board prep', 或 'prep call'\n - c2: on June 26 (0.2) - 检查新事件日期是否包含 '2026-06-26'\n - c3: gmail_new_sent (0.1) - 检查是否有新邮件发送或保存为草稿\n - c4: replied to the board chair (0.2) - 检查发送/草稿邮件是否发送给 chair@board.org\n - c5: slack_new_msg (0.1) - 检查 user_1 是否在 #general 频道发送了新消息\n\n4. 失败模式:\n - 读取 sid 失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取 mock 状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出\n\n5. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加汇总,然后钳制到 1.0\n\n6. is_placeholder:\n - false,因为脚本有详细的检查逻辑\n\n7. confidence:\n - 1.0,因为代码逻辑清晰完整\n\n现在构建 JSON:\n\ntask_id: \"c4ce61fa-20a5-563d-8bba-542633ab52bc\"\ndomain: \"mock_websites\"\nsummary: \"验证用户是否通过Gmail回复董事会主席、在Google Calendar创建6月26日的Board Prep Call会议,并在Slack #general频道发送新消息\"\nis_placeholder: false\ndata_sources: [\"gmail_mock\", \"google_calendar_mock\", \"slack_mock\", \"/tmp/task_web_sid\"]\n\nscoring_components:\n1. cal_new_event (0.2): 对比 initial_state 和 current_state 的 events,检查是否有新事件\n2. event titled Board Prep Call (0.2): 检查新事件标题是否包含指定关键词\n3. on June 26 (0.2): 检查新事件 start 字段是否包含 '2026-06-26'\n4. gmail_new_sent (0.1): 检查 Gmail 是否有新的 sent 或 drafts 邮件\n5. replied to the board chair (0.2): 检查新邮件的 to 字段是否包含 chair@board.org\n6. slack_new_msg (0.1): 检查 Slack #general 频道是否有 user_1 的新消息\n\nscore_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到4位小数\"\n\nfailure_modes:\n- 读取 /tmp/task_web_sid 失败或为空\n- 任一 mock 服务状态获取失败\n- 无新日历事件(c0失败)\n- 新日历事件标题不匹配(c1失败)\n- 新日历事件日期不是2026-06-26(c2失败)\n- 无新发送/草稿邮件(c3失败)\n- 新邮件未发送给 chair@board.org(c4失败)\n- user_1 未在 #general 发送新消息(c5失败)\n\nscoring_logic_explanation: 详细按执行顺序说明...\n\n让我确保所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\n检查代码细节:\n- c0: c0_init_ids 来自 initial_state.events,c0_new 是 current_state.events 中 id 不在 c0_init_ids 的事件\n- c1: 检查 cal_new_events 中任一事件 title 包含 'board prep call', 'board prep', 或 'prep call'\n- c2: 检查 cal_new_events 中任一事件 start 包含 '2026-06-26'\n- c3: 检查 emails 中 folder 为 sent 或 drafts 且 id 不在 initial emails 中的邮件,或 drafts 中 id 不在 initial drafts 中的草稿\n- c4: 类似 c3 构建 pool,提取所有 to.email 字段,检查是否包含 'chair@board.org'\n- c5: 检查 slack_mock current_state.messages.general 中 messageId 不在 SEED 中且 senderId 为 'user_1' 的消息\n\n注意 c4 的代码有一个小问题:c4_pool 的构建中,第二部分直接加了 (c4_cur.get('drafts') or []),没有排除初始草稿。但代码确实是这样写的,我如实描述。\n\n等等,c4 代码:\nc4_pool = [e for e in (c4_cur.get('emails') or []) if e.get('id') not in c4_init_ids and e.get('folder') in ('sent','drafts')] + (c4_cur.get('drafts') or [])\n这里确实没有过滤掉初始草稿。但 c3 中过滤了。这是代码实际逻辑,如实记录。\n\nc5: SEED 是 {\"slack_mock:general\": [\"g1\"], \"slack_mock:random\": []},所以 c5_seed = {\"g1\"},排除 messageId 为 \"g1\" 的种子消息。\n\n好,现在写 JSON。 {\"task_id\":\"c4ce61fa-20a5-563d-8bba-542633ab52bc\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否在Google Calendar新建了6月26日的Board Prep Call会议、通过Gmail向董事会主席发送/草拟了邮件,并在Slack的#general频道以user_1身份发送了新消息\",\"is_placeholder\":false,\"data_sources\":[\"gmail_mock\",\"google_calendar_mock\",\"slack_mock\",\"/tmp/task_web_sid\"],\"scoring_components\":[{\"name\":\"cal_new_event\",\"weight\":0.2,\"description\":\"检查Google Calendar是否创建了新的日历事件\",\"check_logic\":\"对比google_calendar_mock的initial_state.events与current_state.events,收集id不在初始集合中的事件存入cal_new_events;若cal_new_events非空则通过\",\"pass_condition\":\"current_state.events中存在id不在initial_state.events中的新事件\"},{\"name\":\"event titled Board Prep Call\",\"weight\":0.2,\"description\":\"检查新建日历事件的标题是否包含Board Prep Call相关关键词\",\"check_logic\":\"遍历cal_new_events,将title转小写后检查是否包含'board prep call'、'board prep'或'prep call'任一子串\",\"pass_condition\":\"新事件的title字段(忽略大小写)包含上述任一关键词\"},{\"name\":\"on June 26\",\"weight\":0.2,\"description\":\"检查新建日历事件的开始日期是否为2026-06-26\",\"check_logic\":\"遍历cal_new_events,检查start字段(字符串)中是否包含'2026-06-26'\",\"pass_condition\":\"至少一个新事件的start字段包含'2026-06-26'\"},{\"name\":\"gmail_new_sent\",\"weight\":0.1,\"description\":\"检查Gmail是否有新发送的邮件或新保存的草稿\",\"check_logic\":\"收集current_state.emails中id不在initial_state.emails且folder为'sent'或'drafts'的邮件,并收集current_state.drafts中id不在initial_state.drafts的草稿;若合并后列表非空则通过\",\"pass_condition\":\"存在新的sent邮件或新的draft\"},{\"name\":\"replied to the board chair\",\"weight\":0.2,\"description\":\"检查新邮件/草稿的收件人是否包含董事会主席邮箱\",\"check_logic\":\"构建c4_pool(新sent/drafts邮件加上current_state.drafts),提取所有to列表中的email字段拼接为小写字符串,检查是否包含'chair@board.org'\",\"pass_condition\":\"新邮件/草稿的收件人邮箱中包含'chair@board.org'\"},{\"name\":\"slack_new_msg\",\"weight\":0.1,\"description\":\"检查Slack #general频道是否有user_1发送的新消息\",\"check_logic\":\"获取current_state.messages.general,排除SEED中预置的messageId(如'g1'),筛选senderId为'user_1'的消息;若存在则通过\",\"pass_condition\":\"#general频道中存在messageId不在SEED且senderId为'user_1'的新消息\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终通过min(total, 1.0)将总分钳制在1.0上限,并四舍五入保留4位小数\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或内容为空时打印CRITICAL并返回0.0\",\"任一mock服务(gmail_mock、google_calendar_mock、slack_mock)状态拉取失败时打印CRITICAL并返回0.0\",\"未创建新日历事件导致c0失败,无法获得后续c1、c2的分数\",\"新事件标题不匹配关键词导致c1失败\",\"新事件start字段不含'2026-06-26'导致c2失败\",\"无新sent/draft邮件导致c3失败\",\"新邮件未发送给chair@board.org导致c4失败\",\"user_1未在#general发送新消息导致c5失败\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向gmail_mock、google_calendar_mock、slack_mock发送请求拉取各自的current_state和initial_state。若任何一步失败则直接退出并返回0.0。评分按顺序执行6个组件:先通过对比initial_state与current_state的events列表识别新日历事件(0.2分);再检查这些新事件的标题是否包含Board Prep Call相关关键词(0.2分)以及start字段是否包含2026-06-26(0.2分);接着检查Gmail中是否有新的sent邮件或drafts(0.1分),并进一步检查这些新邮件的收件人是否包含chair@board.org(0.2分);最后检查Slack #general频道中是否有user_1发送的新消息(0.1分)。每个组件独立判断,通过则累加对应分值,不通过则仅打印FAIL不扣分也不中断。最终总分经min(total, 1.0)钳制后四舍五入到4位小数输出。\",\"confidence\":1.0}" +} diff --git a/ops_risk_log_006/_cua_gym_vm_bridge.sh b/ops_risk_log_006/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_risk_log_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/ops_risk_log_006/initial_setup.py b/ops_risk_log_006/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..64da7bbf045dd491cb20e71e6f178ea779cf3fc2 --- /dev/null +++ b/ops_risk_log_006/initial_setup.py @@ -0,0 +1,327 @@ +""" +Initial Setup: pmo_risk_log_b103 +Task ID: ops_risk_log_006 +Domain: mock_websites +Mocks: asana_mock, google_sheets_mock, google_calendar_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a marketing program manager. Your tools for this task are: the Asana project, shared spreadsheets, the team calendar, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Asana 'Q1 Product Launch' project with 3 task(s); a Google Sheet with seeded tabular data; an empty Google Calendar; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: risk log lists the overdue task (+0.3); risk log has its due date (+0.2); cal_new_event (+0.1); SteerCo on June 24 (+0.1); slack_new_msg (+0.1); reports one overdue item (+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 = { + "asana_mock": "http://28.7.184.198:8114", + "google_sheets_mock": "http://28.7.184.198:8145", + "google_calendar_mock": "http://28.7.184.198:8141", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8114' + +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 = { 'asana_mock': { 'currentUser': { 'userId': 'user-0', + 'name': 'Alex Johnson', + 'email': 'alex.johnson@company.com', + 'avatar': 'https://picsum.photos/100/100?random=user0', + 'title': 'Product Manager', + 'department': 'Product', + 'location': 'SF', + 'timezone': 'PST', + 'theme': 'light'}, + 'users': [ { 'userId': 'user-0', + 'name': 'Alex Johnson', + 'email': 'alex.johnson@company.com'}, + { 'userId': 'user-1', + 'name': 'Sarah Chen', + 'email': 'sarah.chen@company.com'}, + { 'userId': 'user-2', + 'name': 'Mike Rodriguez', + 'email': 'mike.r@company.com'}], + 'teams': [ { 'teamId': 'team-1', + 'name': 'Product', + 'description': '', + 'memberIds': ['user-0', 'user-1', 'user-2'], + 'ownerId': 'user-0', + 'privacy': 'public', + 'createdDate': '2026-01-01T00:00:00Z'}], + 'projects': [ { 'projectId': 'project-1', + 'name': 'Q1 Product Launch', + 'teamId': 'team-1', + 'description': '', + 'color': 'blue', + 'icon': 'rocket', + 'ownerId': 'user-0', + 'memberIds': ['user-0', 'user-1', 'user-2'], + 'sections': [ { 'sectionId': 'section-1-1', + 'name': 'To Do', + 'collapsed': False}, + { 'sectionId': 'section-1-2', + 'name': 'In Progress', + 'collapsed': False}], + 'customFields': [], + 'privacy': 'public', + 'startDate': None, + 'dueDate': None, + 'archived': False, + 'starred': False, + 'createdDate': '2026-01-01T00:00:00Z', + 'modifiedDate': '2026-01-01T00:00:00Z'}], + 'tasks': [ { 'taskId': 't1', + 'name': 'Vendor contract signoff', + 'projectId': 'project-1', + 'sectionId': 'section-1-2', + 'description': '', + 'assigneeId': None, + 'creatorId': 'user-0', + 'dueDate': '2026-06-18', + 'startDate': None, + 'completed': False, + 'completedDate': None, + 'parentTaskId': None, + 'dependencies': [], + 'tags': [], + 'attachmentIds': [], + 'customFieldValues': {}, + 'likeCount': 0, + 'createdDate': '2026-06-01T00:00:00Z', + 'modifiedDate': '2026-06-01T00:00:00Z'}, + { 'taskId': 't2', + 'name': 'Kickoff deck', + 'projectId': 'project-1', + 'sectionId': 'section-1-2', + 'description': '', + 'assigneeId': None, + 'creatorId': 'user-0', + 'dueDate': '2026-06-10', + 'startDate': None, + 'completed': True, + 'completedDate': None, + 'parentTaskId': None, + 'dependencies': [], + 'tags': [], + 'attachmentIds': [], + 'customFieldValues': {}, + 'likeCount': 0, + 'createdDate': '2026-06-01T00:00:00Z', + 'modifiedDate': '2026-06-01T00:00:00Z'}, + { 'taskId': 't3', + 'name': 'Phase 2 scoping', + 'projectId': 'project-1', + 'sectionId': 'section-1-1', + 'description': '', + 'assigneeId': None, + 'creatorId': 'user-0', + 'dueDate': '2026-07-15', + 'startDate': None, + 'completed': False, + 'completedDate': None, + 'parentTaskId': None, + 'dependencies': [], + 'tags': [], + 'attachmentIds': [], + 'customFieldValues': {}, + 'likeCount': 0, + 'createdDate': '2026-06-01T00:00:00Z', + 'modifiedDate': '2026-06-01T00:00:00Z'}], + 'comments': [], + 'portfolios': [], + 'goals': [], + 'notifications': [], + 'attachments': []}, + 'google_sheets_mock': { 'id': 'workbook_1', + 'title': 'Project Risk Log', + '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': 'Project Risk Log', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'data': { 'A1': { 'value': 'Task', + 'formula': 'Task', + 'style': {'bold': True}}, + 'B1': { 'value': 'Due Date', + 'formula': 'Due Date', + 'style': {'bold': True}}}}]}, + '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}}, + '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': 'how many overdue items for ' + 'steerco?', + '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/ops_risk_log_006/reward.py b/ops_risk_log_006/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..2c8a745f0a10e05e772ab00451944d99da8cdb89 --- /dev/null +++ b/ops_risk_log_006/reward.py @@ -0,0 +1,171 @@ +""" +Reward Script: pmo_risk_log_b103 +Task ID: ops_risk_log_006 +Domain: mock_websites +Mocks: asana_mock, google_sheets_mock, google_calendar_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.3] risk log lists the overdue task + - [0.2] risk log has its due date + - [0.1] cal_new_event + - [0.1] SteerCo on June 24 + - [0.1] slack_new_msg + - [0.2] reports one overdue item +""" +import re +import sys + +import requests + +MOCK_URLS = { + "asana_mock": "http://28.7.184.198:8114", + "google_sheets_mock": "http://28.7.184.198:8145", + "google_calendar_mock": "http://28.7.184.198:8141", + "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() + + +# Accept any unambiguous rendering of the same calendar date. The task only says +# "log its due date" without fixing a format, so 2026-06-18, 6/18/2026, +# 06/18/2026, 2026/6/18, "June 18, 2026", "18 Jun 2026" etc. are all correct. +_MONTHS = { + 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, + 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, +} + + +def _date_tuples(s): + """Return the set of (year, month, day) tuples that string ``s`` could denote. + + Handles ISO (YYYY-MM-DD / YYYY/M/D), US slash (M/D/YYYY), and month-name + forms. Ambiguous numeric forms yield multiple candidates so an equivalent + date still matches.""" + s = str(s or '').strip().lower() + out = set() + if not s: + return out + # Month-name forms: "june 18, 2026" / "18 jun 2026" + m = re.search(r'([a-z]{3,9})\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})', s) + if m and m.group(1)[:3] in _MONTHS: + out.add((int(m.group(3)), _MONTHS[m.group(1)[:3]], int(m.group(2)))) + m = re.search(r'(\d{1,2})(?:st|nd|rd|th)?\s+([a-z]{3,9})\.?,?\s+(\d{4})', s) + if m and m.group(2)[:3] in _MONTHS: + out.add((int(m.group(3)), _MONTHS[m.group(2)[:3]], int(m.group(1)))) + # ISO: YYYY-MM-DD or YYYY/MM/DD + m = re.search(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})', s) + if m: + out.add((int(m.group(1)), int(m.group(2)), int(m.group(3)))) + # US slash / dash: M/D/YYYY or M-D-YYYY (also add D/M/YYYY as a candidate) + m = re.search(r'(\d{1,2})[-/](\d{1,2})[-/](\d{4})', s) + if m: + a, b, y = int(m.group(1)), int(m.group(2)), int(m.group(3)) + out.add((y, a, b)) + out.add((y, b, a)) + return out + + +def _same_date(value, expected): + """True if ``value`` denotes the same calendar date as ``expected``.""" + exp = _date_tuples(expected) + got = _date_tuples(value) + return bool(exp and got and (exp & got)) + + +total = 0.0 + +# c0: sheet cell A2 value contains 'Vendor contract signoff' +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('A2') or {} +if 'Vendor contract signoff' in str(c0_cd.get('value','')) or 'Vendor contract signoff' in str(c0_cd.get('computed','')): + print('PASS: risk log lists the overdue task (0.3)') + total += 0.3 +else: + print('FAIL: risk log lists the overdue task') + +# c1: sheet cell B2 denotes the due date 2026-06-18 (any unambiguous format) +c1_sheets = cur('google_sheets_mock').get('sheets') or [] +c1_data = (c1_sheets[0].get('data') if c1_sheets else {}) or {} +c1_cd = c1_data.get('B2') or {} +if _same_date(c1_cd.get('value', ''), '2026-06-18') or _same_date(c1_cd.get('computed', ''), '2026-06-18'): + print('PASS: risk log has its due date (0.2)') + total += 0.2 +else: + print('FAIL: risk log has its due date') + +# c2: a new calendar event was created +c2_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])} +c2_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c2_init_ids] +globals()['cal_new_events'] = c2_new +if c2_new: + print('PASS: new calendar event (0.1)') + total += 0.1 +else: + print('FAIL: no new calendar event') + +# c3: new event date contains '2026-06-24' +c3_new = globals().get('cal_new_events', []) +if any('2026-06-24' in (e.get('start','') or '') for e in c3_new): + print('PASS: SteerCo on June 24 (0.1)') + total += 0.1 +else: + print('FAIL: SteerCo on June 24') + +# c4: new message by user_1 in #general +c4_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c4_seed = set(SEED.get('slack_mock:general', [])) +c4_new = [m for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1'] +c4_blob = _lc(' '.join((m.get('content') or '') for m in c4_new)) +if c4_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') + +# c5: slack #general contains (reports one overdue item) +c5_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c5_seed = set(SEED.get('slack_mock:general', [])) +c5_blob = _lc(' '.join((m.get('content') or '') for m in c5_msgs if m.get('messageId') not in c5_seed and m.get('senderId') == 'user_1')) +if any(t in c5_blob for t in ['1', 'one']): + print('PASS: reports one overdue item (0.2)') + total += 0.2 +else: + print('FAIL: reports one overdue item') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/ops_risk_log_006/reward_label.json b/ops_risk_log_006/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..a15e77fce3ec11badcb90b978ccc86836b4a1bfe --- /dev/null +++ b/ops_risk_log_006/reward_label.json @@ -0,0 +1,77 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/0954ae0f-6462-5fb3-95a4-8b44f759c153/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:18:50", + "label": { + "task_id": "ops_risk_log_006", + "domain": "mock_websites", + "summary": "验证 PMO 风险日志任务:在 Google Sheets 记录逾期任务及日期,在 Google Calendar 创建 SteerCo 会议,并在 Slack 汇报逾期事项", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "asana_mock", + "google_sheets_mock", + "google_calendar_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "c0", + "weight": 0.3, + "description": "风险日志列出逾期任务", + "check_logic": "检查 google_sheets_mock 的 sheets[0].data.A2 的 value 或 computed 字段是否包含字符串 'Vendor contract signoff'", + "pass_condition": "A2 单元格的 value 或 computed 包含 'Vendor contract signoff'" + }, + { + "name": "c1", + "weight": 0.2, + "description": "风险日志包含逾期任务的截止日期", + "check_logic": "检查 google_sheets_mock 的 sheets[0].data.B2 的 value 或 computed 字段是否包含 '2026-06-18'", + "pass_condition": "B2 单元格的 value 或 computed 包含 '2026-06-18'" + }, + { + "name": "c2", + "weight": 0.1, + "description": "创建新的日历事件", + "check_logic": "比较 google_calendar_mock 的 current_state.events 与 initial_state.events,检查是否存在 id 不在初始事件中的新事件", + "pass_condition": "存在至少一个新创建的日历事件" + }, + { + "name": "c3", + "weight": 0.1, + "description": "SteerCo 会议安排在6月24日", + "check_logic": "检查 c2 中识别出的新事件的 start 字段是否包含 '2026-06-24'", + "pass_condition": "新日历事件的 start 字段包含 '2026-06-24'" + }, + { + "name": "c4", + "weight": 0.1, + "description": "Slack #general 频道有 user_1 的新消息", + "check_logic": "检查 slack_mock 的 current_state.messages.general 中是否存在 messageId 不在 SEED 中且 senderId 为 'user_1' 的新消息", + "pass_condition": "user_1 在 #general 发送了至少一条新消息" + }, + { + "name": "c5", + "weight": 0.2, + "description": "Slack 消息汇报一项逾期事项", + "check_logic": "将 user_1 在 #general 发送的所有新消息内容转为小写并拼接,检查是否包含 '1' 或 'one'", + "pass_condition": "消息内容(小写)包含 '1' 或 'one'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终通过 min(total, 1.0) 钳制到上限 1.0,再四舍五入到4位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并返回 0.0 退出", + "任一 mock 服务状态拉取失败时,打印 CRITICAL 并返回 0.0 退出", + "Google Sheets A2 不包含指定文本时,c0 不得分", + "Google Sheets B2 不包含指定日期时,c1 不得分", + "未创建新日历时,c2 和 c3 均不得分", + "Slack #general 无 user_1 新消息时,c4 和 c5 均不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 asana_mock、google_sheets_mock、google_calendar_mock、slack_mock 拉取当前状态。若 sid 读取或任一 mock 拉取失败,立即输出 0.0 并退出。成功后,脚本按顺序检查6个评分组件:1) Google Sheets A2 是否包含 'Vendor contract signoff';2) B2 是否包含 '2026-06-18';3) Google Calendar 是否有新增事件;4) 新增事件是否安排在 2026-06-24;5) Slack #general 是否有 user_1 的新消息;6) 该消息内容是否提及 '1' 或 'one'。各组件独立计分,累加得到总分,最终用 min 函数钳制在 1.0 以内并四舍五入到4位小数作为 REWARD 输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. 文件头 docstring:\n - Reward Script: pmo_risk_log_b103\n - Task ID: 0954ae0f-6462-5fb3-95a4-8b44f759c153\n - Domain: mock_websites\n - Mocks: asana_mock, google_sheets_mock, google_calendar_mock, slack_mock\n - Scoring 说明:\n - [0.3] risk log lists the overdue task\n - [0.2] risk log has its due date\n - [0.1] cal_new_event\n - [0.1] SteerCo on June 24\n - [0.1] slack_new_msg\n - [0.2] reports one overdue item\n\n2. 代码逻辑:\n - 读取 /tmp/task_web_sid 获取 sid,失败则输出 REWARD: 0.0 并退出\n - 从 MOCK_URLS 获取各个 mock 的 current_state,失败则输出 REWARD: 0.0 并退出\n - 定义 cur() 辅助函数获取 current_state\n - 定义 _lc() 辅助函数转小写\n\n 评分组件:\n - c0 (0.3): google_sheets_mock 的 sheets[0].data.A2 的 value 或 computed 包含 'Vendor contract signoff'\n - c1 (0.2): google_sheets_mock 的 sheets[0].data.B2 的 value 或 computed 包含 '2026-06-18'\n - c2 (0.1): google_calendar_mock 的 current_state.events 中有不在 initial_state.events 中的新事件\n - c3 (0.1): 新事件中任意一个的 start 字段包含 '2026-06-24'\n - c4 (0.1): slack_mock 的 current_state.messages.general 中有 messageId 不在 seed 中且 senderId == 'user_1' 的新消息\n - c5 (0.2): slack #general 中 user_1 发送的新消息内容(小写后)包含 '1' 或 'one'\n\n 最终分数:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 输出 REWARD: final\n\n3. 数据源:\n - /tmp/task_web_sid\n - asana_mock (虽然定义了 URL,但代码中似乎没有实际使用 cur('asana_mock'),不过 docstring 提到了,且 STATES 会拉取)\n - google_sheets_mock\n - google_calendar_mock\n - slack_mock\n\n4. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 拉取 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n5. is_placeholder: false,因为脚本有详细的检查逻辑。\n\n6. confidence: 1.0,因为逻辑非常清晰。\n\n现在构建 JSON:\n\ntask_id: \"0954ae0f-6462-5fb3-95a4-8b44f759c153\"\ndomain: \"mock_websites\"\nsummary: \"验证 PMO 风险日志任务:在 Google Sheets 记录逾期任务及日期,在 Google Calendar 创建 SteerCo 会议,并在 Slack 汇报逾期事项。\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"asana_mock\", \"google_sheets_mock\", \"google_calendar_mock\", \"slack_mock\"]\n\nscoring_components:\n1. name: \"c0\", weight: 0.3, description: \"风险日志列出逾期任务\", check_logic: \"检查 google_sheets_mock 的 sheets[0].data.A2 的 value 或 computed 字段是否包含字符串 'Vendor contract signoff'\", pass_condition: \"A2 单元格的 value 或 computed 包含 'Vendor contract signoff'\"\n2. name: \"c1\", weight: 0.2, description: \"风险日志包含逾期任务的截止日期\", check_logic: \"检查 google_sheets_mock 的 sheets[0].data.B2 的 value 或 computed 字段是否包含 '2026-06-18'\", pass_condition: \"B2 单元格的 value 或 computed 包含 '2026-06-18'\"\n3. name: \"c2\", weight: 0.1, description: \"创建新的日历事件\", check_logic: \"比较 google_calendar_mock 的 current_state.events 与 initial_state.events,检查是否存在 id 不在初始事件中的新事件\", pass_condition: \"存在至少一个新创建的日历事件\"\n4. name: \"c3\", weight: 0.1, description: \"SteerCo 会议安排在6月24日\", check_logic: \"检查 c2 中识别出的新事件的 start 字段是否包含 '2026-06-24'\", pass_condition: \"新日历事件的 start 字段包含 '2026-06-24'\"\n5. name: \"c4\", weight: 0.1, description: \"Slack #general 频道有新消息\", check_logic: \"检查 slack_mock 的 current_state.messages.general 中是否存在 messageId 不在 SEED 中且 senderId 为 'user_1' 的新消息\", pass_condition: \"user_1 在 #general 发送了至少一条新消息\"\n6. name: \"c5\", weight: 0.2, description: \"Slack 消息汇报一项逾期事项\", check_logic: \"将 user_1 在 #general 发送的所有新消息内容转为小写并拼接,检查是否包含 '1' 或 'one'\", pass_condition: \"消息内容(小写)包含 '1' 或 'one'\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数累加,最终通过 min(total, 1.0) 钳制到上限 1.0,再四舍五入到4位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"任 mock 服务(asana_mock、google_sheets_mock、google_calendar_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"Google Sheets A2 不包含指定文本时,c0 不得分\",\n \"Google Sheets B2 不包含指定日期时,c1 不得分\",\n \"未创建新日历时,c2 和 c3 均不得分\",\n \"Slack #general 无 user_1 新消息时,c4 和 c5 均不得分\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 asana_mock、google_sheets_mock、google_calendar_mock、slack_mock 拉取当前状态。若 sid 读取或任一 mock 拉取失败,立即输出 0.0 并退出。成功后,脚本按顺序检查6个评分组件:1) Google Sheets A2 是否包含 'Vendor contract signoff';2) B2 是否包含 '2026-06-18';3) Google Calendar 是否有新增事件;4) 新增事件是否安排在 2026-06-24;5) Slack #general 是否有 user_1 的新消息;6) 该消息内容是否提及 '1' 或 'one'。各组件独立计分,累加得到总分,最终用 min 函数钳制在 1.0 以内并四舍五入到4位小数作为 REWARD 输出。\"\n\nconfidence: 1.0\n\n检查格式要求:\n- 只输出 JSON 对象\n- 不要 Markdown 代码块\n- 不要额外解释\n- 不要思考过程\n- 不要 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n\n让我再确认一下 data_sources。虽然 asana_mock 在代码中被拉取了状态,但评分逻辑中没有使用它。不过 docstring 明确列出了它,且 STATES 确实会获取它。所以应该包含。\n\n再检查 c5 的逻辑:c5_msgs 是所有 general 消息,c5_seed 是 seed,然后过滤 messageId 不在 seed 且 senderId == 'user_1',然后取 content 转小写拼接,检查是否包含 '1' 或 'one'。是的。\n\nc4 和 c5 有细微差别:c4 检查 c4_new 是否非空;c5 检查 c5_blob 是否包含 '1' 或 'one'。注意 c4_blob 被计算了但似乎没用到?等等,看代码:\nc4_blob = _lc(' '.join(...)) # 计算了但后面 if 用的是 c4_new\nc5_blob = _lc(' '.join(...)) # 计算了并用于 if\n\n是的,c4 只看有没有新消息,c5 看内容。\n\nJSON 需要合法,注意转义引号等。\n\n让我直接写出最终 JSON。 {\"task_id\":\"0954ae0f-6462-5fb3-95a4-8b44f759c153\",\"domain\":\"mock_websites\",\"summary\":\"验证 PMO 风险日志任务:在 Google Sheets 记录逾期任务及日期,在 Google Calendar 创建 SteerCo 会议,并在 Slack 汇报逾期事项\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"asana_mock\",\"google_sheets_mock\",\"google_calendar_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"c0\",\"weight\":0.3,\"description\":\"风险日志列出逾期任务\",\"check_logic\":\"检查 google_sheets_mock 的 sheets[0].data.A2 的 value 或 computed 字段是否包含字符串 'Vendor contract signoff'\",\"pass_condition\":\"A2 单元格的 value 或 computed 包含 'Vendor contract signoff'\"},{\"name\":\"c1\",\"weight\":0.2,\"description\":\"风险日志包含逾期任务的截止日期\",\"check_logic\":\"检查 google_sheets_mock 的 sheets[0].data.B2 的 value 或 computed 字段是否包含 '2026-06-18'\",\"pass_condition\":\"B2 单元格的 value 或 computed 包含 '2026-06-18'\"},{\"name\":\"c2\",\"weight\":0.1,\"description\":\"创建新的日历事件\",\"check_logic\":\"比较 google_calendar_mock 的 current_state.events 与 initial_state.events,检查是否存在 id 不在初始事件中的新事件\",\"pass_condition\":\"存在至少一个新创建的日历事件\"},{\"name\":\"c3\",\"weight\":0.1,\"description\":\"SteerCo 会议安排在6月24日\",\"check_logic\":\"检查 c2 中识别出的新事件的 start 字段是否包含 '2026-06-24'\",\"pass_condition\":\"新日历事件的 start 字段包含 '2026-06-24'\"},{\"name\":\"c4\",\"weight\":0.1,\"description\":\"Slack #general 频道有 user_1 的新消息\",\"check_logic\":\"检查 slack_mock 的 current_state.messages.general 中是否存在 messageId 不在 SEED 中且 senderId 为 'user_1' 的新消息\",\"pass_condition\":\"user_1 在 #general 发送了至少一条新消息\"},{\"name\":\"c5\",\"weight\":0.2,\"description\":\"Slack 消息汇报一项逾期事项\",\"check_logic\":\"将 user_1 在 #general 发送的所有新消息内容转为小写并拼接,检查是否包含 '1' 或 'one'\",\"pass_condition\":\"消息内容(小写)包含 '1' 或 'one'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终通过 min(total, 1.0) 钳制到上限 1.0,再四舍五入到4位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并返回 0.0 退出\",\"任一 mock 服务状态拉取失败时,打印 CRITICAL 并返回 0.0 退出\",\"Google Sheets A2 不包含指定文本时,c0 不得分\",\"Google Sheets B2 不包含指定日期时,c1 不得分\",\"未创建新日历时,c2 和 c3 均不得分\",\"Slack #general 无 user_1 新消息时,c4 和 c5 均不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 asana_mock、google_sheets_mock、google_calendar_mock、slack_mock 拉取当前状态。若 sid 读取或任一 mock 拉取失败,立即输出 0.0 并退出。成功后,脚本按顺序检查6个评分组件:1) Google Sheets A2 是否包含 'Vendor contract signoff';2) B2 是否包含 '2026-06-18';3) Google Calendar 是否有新增事件;4) 新增事件是否安排在 2026-06-24;5) Slack #general 是否有 user_1 的新消息;6) 该消息内容是否提及 '1' 或 'one'。各组件独立计分,累加得到总分,最终用 min 函数钳制在 1.0 以内并四舍五入到4位小数作为 REWARD 输出。\",\"confidence\":1.0}" +} diff --git a/qa_bug_escalate_004/_cua_gym_vm_bridge.sh b/qa_bug_escalate_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/qa_bug_escalate_004/_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/qa_bug_escalate_004/initial_setup.py b/qa_bug_escalate_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8eee96e1a2c7fff0f30cc9867b663e37e8abffe6 --- /dev/null +++ b/qa_bug_escalate_004/initial_setup.py @@ -0,0 +1,712 @@ +""" +Initial Setup: se_jira_gitlab_notion_b109 +Task ID: qa_bug_escalate_004 +Domain: mock_websites +Mocks: jira_mock, gitlab_mock, notion_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a software engineer. Your tools for this task are: the Jira project board, the GitLab projects, the Notion workspace, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Jira Kanban project with issues KAN-1(Done), KAN-8(To Do), KAN-9(To Do), KAN-10(To Do); GitLab with 6 issues, 2 MRs across projects; Notion workspace with pages 'Payments Runbook'; Slack workspace with channels #general, #engineering, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: KAN-9 (payment timeout) moved to In Progress (+0.25); matching GitLab issue in backend-api (+0.2); runbook gains a concrete remediation step (+0.25); runbook pointer pasted back on KAN-9 (+0.2); Slack names KAN-9 exactly (+0.1). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "jira_mock": "http://28.7.184.198:8153", + "gitlab_mock": "http://28.7.184.198:8137", + "notion_mock": "http://28.7.184.198:8166", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8153' + +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 = { '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 CI 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': 'i8', + 'key': 'KAN-8', + 'projectId': 'p1', + 'summary': 'Dashboard chart legend overlaps', + 'description': '', + 'type': 'Bug', + 'status': 'To Do', + 'priority': 'Low', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u2', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}, + { 'id': 'i9', + 'key': 'KAN-9', + 'projectId': 'p1', + 'summary': 'Payment checkout times out under load', + 'description': '', + 'type': 'Bug', + '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'}, + { 'id': 'i10', + 'key': 'KAN-10', + 'projectId': 'p1', + 'summary': 'Email receipts have wrong timezone', + 'description': '', + 'type': 'Bug', + 'status': 'To Do', + 'priority': 'Medium', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u4', + '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': []}, + 'gitlab_mock': { 'currentUser': { 'id': 1, + 'name': 'Admin User', + 'username': 'admin', + 'avatarUrl': 'https://picsum.photos/100/100?random=user1'}, + 'projects': [ { 'id': 1, + 'name': 'frontend-monorepo', + 'description': 'Main frontend repository for the ' + 'enterprise application.', + 'visibility': 'private', + 'stars': 12, + 'forks': 4, + 'updatedAt': '2026-06-08T09:54:15.658Z', + 'branches': [ 'main', + 'develop', + 'fix/login-mobile', + 'feat/dark-mode', + 'fix/header-style'], + 'files': [ { 'name': 'src', + 'type': 'folder', + 'children': [ { 'name': 'components', + 'type': 'folder', + 'children': [ { 'name': 'Button.jsx', + 'type': 'file', + 'content': 'export ' + 'const ' + 'Button ' + '= ' + '() ' + '=> ' + ';'}, + { 'name': 'Header.jsx', + 'type': 'file', + 'content': 'export ' + 'const ' + 'Header ' + '= ' + '() ' + '=> ' + '
    Logo
    ;'}]}, + { 'name': 'App.jsx', + 'type': 'file', + 'content': 'import ' + '{ ' + 'Button ' + '} from ' + "'./components/Button';\n" + '\n' + 'export ' + 'default ' + 'function ' + 'App() ' + '{\n' + ' ' + 'return ' + '
    ;\n' + '}'}, + { 'name': 'index.css', + 'type': 'file', + 'content': 'body { ' + 'background: ' + '#fff; ' + '}'}]}, + { 'name': 'package.json', + 'type': 'file', + 'content': '{\n' + ' "name": "frontend",\n' + ' "version": "1.0.0"\n' + '}'}, + { 'name': 'README.md', + 'type': 'file', + 'content': '# Frontend Monorepo\n' + '\n' + 'This is the main ' + 'repository.\n' + '\n' + '## Getting Started\n' + '\n' + '1. `npm install`\n' + '2. `npm start`\n' + '\n' + '## Features\n' + '- React\n' + '- Vite\n' + '- Tailwind'}]}, + { 'id': 2, + 'name': 'backend-api', + 'description': 'Go-based microservices API gateway.', + 'visibility': 'internal', + 'stars': 8, + 'forks': 1, + 'updatedAt': '2026-06-07T09:54:15.658Z', + 'branches': ['main', 'dev', 'feat/auth-service'], + 'files': [ { 'name': 'main.go', + 'type': 'file', + 'content': 'package main\n' + '\n' + 'func main() {\n' + ' println("Hello World")\n' + '}'}, + { 'name': 'go.mod', + 'type': 'file', + 'content': 'module backend-api\n' + '\n' + 'go 1.20'}]}], + 'pipelines': [ { 'id': 101, + 'projectId': 1, + 'status': 'success', + 'branch': 'main', + 'commit': 'a1b2c3d', + 'message': 'fix: update dependency versions', + 'duration': '4m 12s', + 'createdAt': '2026-06-08T08:54:15.658Z', + 'stages': [ { 'id': 1, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 1, + 'name': 'build-app', + 'status': 'success', + 'duration': '1m'}]}, + { 'id': 2, + 'name': 'test', + 'status': 'success', + 'jobs': [ { 'id': 2, + 'name': 'unit-tests', + 'status': 'success', + 'duration': '2m'}, + { 'id': 3, + 'name': 'lint', + 'status': 'success', + 'duration': '30s'}]}, + { 'id': 3, + 'name': 'deploy', + 'status': 'success', + 'jobs': [ { 'id': 4, + 'name': 'deploy-staging', + 'status': 'success', + 'duration': '42s'}]}]}, + { 'id': 102, + 'projectId': 1, + 'status': 'failed', + 'branch': 'feature/login-page', + 'commit': 'e5f6g7h', + 'message': 'feat: add login form', + 'duration': '2m 10s', + 'createdAt': '2026-06-08T07:54:15.658Z', + 'stages': [ { 'id': 4, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 5, + 'name': 'build-app', + 'status': 'success', + 'duration': '1m'}]}, + { 'id': 5, + 'name': 'test', + 'status': 'failed', + 'jobs': [ { 'id': 6, + 'name': 'unit-tests', + 'status': 'failed', + 'duration': '1m 10s', + 'logs': 'Error: Test ' + 'failed in ' + 'Login.test.js\n' + 'Expected ' + 'true to be ' + 'false.'}]}]}, + { 'id': 103, + 'projectId': 1, + 'status': 'running', + 'branch': 'fix/header-style', + 'commit': 'i8j9k0l', + 'message': 'style: fix header padding', + 'duration': '45s', + 'createdAt': '2026-06-08T09:54:15.658Z', + 'stages': [ { 'id': 6, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 7, + 'name': 'build-app', + 'status': 'success', + 'duration': '40s'}]}, + { 'id': 7, + 'name': 'test', + 'status': 'running', + 'jobs': [ { 'id': 8, + 'name': 'unit-tests', + 'status': 'running', + 'duration': '5s'}]}, + { 'id': 8, + 'name': 'deploy', + 'status': 'pending', + 'jobs': [ { 'id': 9, + 'name': 'deploy-staging', + 'status': 'pending', + 'duration': '0s'}]}]}, + { 'id': 201, + 'projectId': 2, + 'status': 'success', + 'branch': 'main', + 'commit': 'z9y8x7w', + 'message': 'init: project structure', + 'duration': '1m 05s', + 'createdAt': '2026-06-07T09:54:15.658Z', + 'stages': [ { 'id': 21, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 21, + 'name': 'go-build', + 'status': 'success', + 'duration': '45s'}]}, + { 'id': 22, + 'name': 'test', + 'status': 'success', + 'jobs': [ { 'id': 22, + 'name': 'go-test', + 'status': 'success', + 'duration': '20s'}]}]}, + { 'id': 202, + 'projectId': 2, + 'status': 'failed', + 'branch': 'feat/auth-service', + 'commit': 'b2c3d4e', + 'message': 'feat: add auth middleware', + 'duration': '45s', + 'createdAt': '2026-06-08T08:54:15.658Z', + 'stages': [ { 'id': 23, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 23, + 'name': 'go-build', + 'status': 'success', + 'duration': '40s'}]}, + { 'id': 24, + 'name': 'test', + 'status': 'failed', + 'jobs': [ { 'id': 24, + 'name': 'go-test', + 'status': 'failed', + 'duration': '5s', + 'logs': 'FAIL: ' + 'TestAuthMiddleware\n' + 'Expected ' + '401, got ' + '200'}]}]}, + { 'id': 203, + 'projectId': 2, + 'status': 'running', + 'branch': 'main', + 'commit': 'f5g6h7i', + 'message': 'chore: update dependencies', + 'duration': '10s', + 'createdAt': '2026-06-08T09:54:15.658Z', + 'stages': [ { 'id': 25, + 'name': 'build', + 'status': 'running', + 'jobs': [ { 'id': 25, + 'name': 'go-build', + 'status': 'running', + 'duration': '10s'}]}, + { 'id': 26, + 'name': 'test', + 'status': 'pending', + 'jobs': [ { 'id': 26, + 'name': 'go-test', + 'status': 'pending', + 'duration': '0s'}]}]}], + 'issues': [ { 'id': 1, + 'projectId': 1, + 'title': 'Login button not working on mobile', + 'description': 'The login button is unresponsive on iOS ' + 'devices.', + 'status': 'open', + 'labels': ['bug', 'high-priority'], + 'assignee': 'Admin User'}, + { 'id': 2, + 'projectId': 1, + 'title': 'Update documentation', + 'description': 'Readme needs to be updated with new build ' + 'steps.', + 'status': 'closed', + 'labels': ['docs'], + 'assignee': 'Admin User'}, + { 'id': 3, + 'projectId': 1, + 'title': 'Refactor user context', + 'description': 'Move user state to global context.', + 'status': 'in_progress', + 'labels': ['refactor'], + 'assignee': None}, + { 'id': 4, + 'projectId': 2, + 'title': 'Implement JWT Auth', + 'description': 'Add JWT token generation and validation.', + 'status': 'open', + 'labels': ['feature', 'security'], + 'assignee': 'Admin User'}, + { 'id': 5, + 'projectId': 2, + 'title': 'Fix database connection timeout', + 'description': 'Connection drops after 5 minutes of ' + 'inactivity.', + 'status': 'in_progress', + 'labels': ['bug'], + 'assignee': None}, + { 'id': 6, + 'projectId': 2, + 'title': 'Setup CI pipeline', + 'description': 'Configure XitLab CI for Go project.', + 'status': 'closed', + 'labels': ['devops'], + 'assignee': 'Admin User'}], + 'mergeRequests': [ { 'id': 1, + 'projectId': 1, + 'title': 'Resolve login issues', + 'sourceBranch': 'fix/login-mobile', + 'targetBranch': 'main', + 'status': 'open', + 'author': 'Admin User', + 'createdAt': '2026-06-08T09:54:15.658Z', + 'reviewers': []}, + { 'id': 2, + 'projectId': 1, + 'title': 'Add dark mode', + 'sourceBranch': 'feat/dark-mode', + 'targetBranch': 'main', + 'status': 'merged', + 'author': 'Admin User', + 'createdAt': '2026-06-07T09:54:15.658Z', + 'reviewers': []}], + 'registry': [ { 'id': 1, + 'projectId': 1, + 'name': 'frontend-monorepo/app', + 'tags': ['latest', 'v1.0.1', 'v1.0.0'], + 'size': '45MB', + 'updatedAt': '2026-06-08T09:54:15.658Z'}, + { 'id': 2, + 'projectId': 2, + 'name': 'backend-api/server', + 'tags': ['latest', 'v0.1.0'], + 'size': '12MB', + 'updatedAt': '2026-06-08T08:54:15.658Z'}], + 'snippets': [ { 'id': 1, + 'title': 'Useful Regex for Email', + 'code': 'const emailRegex = ' + '/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;', + 'language': 'javascript', + 'author': 'Admin User'}], + 'wiki': [ { 'id': 1, + 'projectId': 1, + 'title': 'Home', + 'content': '# Welcome to the Wiki\n' + '\n' + 'This is the home page of the project wiki.'}, + { 'id': 2, + 'projectId': 1, + 'title': 'Deployment Guide', + 'content': '# Deployment\n\n1. Build\n2. Test\n3. Push'}], + 'vulnerabilities': [ { 'id': 1, + 'projectId': 1, + 'severity': 'critical', + 'name': 'SQL Injection in Login', + 'status': 'detected'}, + { 'id': 2, + 'projectId': 1, + 'severity': 'medium', + 'name': 'Outdated Dependency: lodash', + 'status': 'resolved'}, + { 'id': 3, + 'projectId': 1, + 'severity': 'low', + 'name': 'Missing X-Frame-Options Header', + 'status': 'detected'}], + 'milestones': [ { 'id': 1, + 'projectId': 1, + 'title': 'v1.0 Launch', + 'dueDate': '2024-12-31', + 'progress': 75}], + 'releases': [ { 'id': 1, + 'projectId': 1, + 'tagName': 'v1.0.0', + 'name': 'Initial Release', + 'description': 'First major release with all core ' + 'features.', + 'createdAt': '2026-05-29T09:54:15.658Z', + 'author': 'Admin User'}]}, + 'notion_mock': { 'user': { 'id': 'user-1', + 'name': 'Sarah Chen', + 'email': 'sarah.chen@acme.com', + 'avatar': ''}, + 'workspace': { 'id': 'ws-1', + 'name': 'Acme Product', + 'icon': '', + 'members': ['user-1']}, + 'pages': { 'page-rb': { 'id': 'page-rb', + 'title': 'Payments Runbook', + 'icon': '', + 'cover': None, + 'parentId': None, + 'blockIds': ['blk-rb1'], + 'favorite': False, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-06-05T00:00:00.000Z', + 'properties': {}}}, + 'blocks': { 'blk-rb1': { 'id': 'blk-rb1', + 'type': 'text', + 'content': 'Payments service operational ' + 'runbook.', + 'properties': {}, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-05-20T00:00:00.000Z'}}, + 'trash': [], + 'comments': {}, + 'settings': { 'appearance': 'light', + 'startWeekMonday': False, + 'fontSize': 'default'}, + 'notifications': [], + 'pageOrder': ['page-rb'], + 'focusBlockId': None}, + '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': 'checkout is timing out ' + "for customers — who's on " + 'it?', + '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/qa_bug_escalate_004/reward.py b/qa_bug_escalate_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..6710f92208c5cdaa7275f920649320fcbd22df3e --- /dev/null +++ b/qa_bug_escalate_004/reward.py @@ -0,0 +1,116 @@ +""" +Reward Script: se_jira_gitlab_notion_b109 +Task ID: qa_bug_escalate_004 +Domain: mock_websites +Mocks: jira_mock, gitlab_mock, notion_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.25] KAN-9 (payment timeout) moved to In Progress + - [0.2] matching GitLab issue in backend-api + - [0.25] runbook gains a concrete remediation step + - [0.2] runbook pointer pasted back on KAN-9 + - [0.1] Slack names KAN-9 exactly +""" +import re +import sys + +import requests + +MOCK_URLS = { + "jira_mock": "http://28.7.184.198:8153", + "gitlab_mock": "http://28.7.184.198:8137", + "notion_mock": "http://28.7.184.198:8166", + "slack_mock": "http://28.7.184.198:8178" +} +SEED = { + "slack_mock:general": [], + "slack_mock:engineering": [ + "e1" + ], + "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: jira issue i9 status == 'In Progress' +c0_iss = next((i for i in (cur('jira_mock').get('issues') or []) if i.get('id') == 'i9'), None) +if c0_iss and c0_iss.get('status') == 'In Progress': + print('PASS: KAN-9 (payment timeout) moved to In Progress (0.25)') + total += 0.25 +else: + print('FAIL: KAN-9 (payment timeout) moved to In Progress (got ' + str(c0_iss.get('status') if c0_iss else 'missing') + ')') + +# c1: a new gitlab issue about (matching GitLab issue in backend-api) +c1_init = {i.get('id') for i in ((STATES['gitlab_mock'].get('initial_state') or {}).get('issues') or [])} +c1_new = [i for i in (cur('gitlab_mock').get('issues') or []) if i.get('id') not in c1_init and any(t in _lc(i.get('title','')) for t in ['payment checkout timeout', 'payment', 'checkout timeout'])] +if c1_new: + print('PASS: matching GitLab issue in backend-api (0.2)') + total += 0.2 +else: + print('FAIL: matching GitLab issue in backend-api') + +# c2: a new block added to page page-rb mentioning (runbook gains a concrete remediation step) +c2_pg = (cur('notion_mock').get('pages') or {}).get('page-rb') or {} +c2_init_pg = ((STATES['notion_mock'].get('initial_state') or {}).get('pages') or {}).get('page-rb') or {} +c2_init_blk = set(c2_init_pg.get('blockIds') or []) +c2_blocks = cur('notion_mock').get('blocks') or {} +c2_new = [b for b in (c2_pg.get('blockIds') or []) if b not in c2_init_blk] +c2_txt = _lc(' '.join((c2_blocks.get(b, {}).get('content') or '') for b in c2_new)) +if c2_new and any(t in c2_txt for t in ['timeout', 'retry', 'idempotent', 'gateway']): + print('PASS: runbook gains a concrete remediation step (0.25)') + total += 0.25 +else: + print('FAIL: runbook gains a concrete remediation step') + +# c3: a new jira comment on i9 mentioning (runbook pointer pasted back on KAN-9) +c3_init = {cm.get('id') for cm in ((STATES['jira_mock'].get('initial_state') or {}).get('comments') or [])} +c3_new = [cm for cm in (cur('jira_mock').get('comments') or []) if cm.get('id') not in c3_init and cm.get('issueId') == 'i9'] +c3_txt = _lc(' '.join(cm.get('content','') for cm in c3_new)) +if c3_new and any(t in c3_txt for t in ['runbook', 'payments runbook', 'notion']): + print('PASS: runbook pointer pasted back on KAN-9 (0.2)') + total += 0.2 +else: + print('FAIL: runbook pointer pasted back on KAN-9') + +# c4: slack #engineering contains (Slack names KAN-9 exactly) +c4_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c4_seed = set(SEED.get('slack_mock:engineering', [])) +c4_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')) +if all(t in c4_blob for t in ['kan-9']): + print('PASS: Slack names KAN-9 exactly (0.1)') + total += 0.1 +else: + print('FAIL: Slack names KAN-9 exactly') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/qa_bug_escalate_004/reward_label.json b/qa_bug_escalate_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..22c0374f00b4a91b961a55cdaffb7500c3dfdf68 --- /dev/null +++ b/qa_bug_escalate_004/reward_label.json @@ -0,0 +1,67 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/8d571c8b-9ef8-52b9-b0af-7b92ab5ea35d/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:55", + "label": { + "task_id": "se_jira_gitlab_notion_b109", + "domain": "mock_websites", + "summary": "验证用户是否将 Jira 工单 KAN-9 移至 In Progress、在 GitLab backend-api 创建关联 issue、在 Notion runbook 添加具体修复步骤、将 runbook 指针回贴到 KAN-9,并在 Slack #engineering 频道准确提及 KAN-9。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "jira_mock", + "gitlab_mock", + "notion_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 0", + "weight": 0.25, + "description": "Jira 工单 KAN-9(id 为 i9)被移动到 In Progress 状态", + "check_logic": "从 jira_mock 的 current_state.issues 中查找 id='i9' 的 issue,检查其 status 字段是否等于 'In Progress'", + "pass_condition": "c0_iss 存在且 c0_iss.status == 'In Progress'" + }, + { + "name": "Component 1", + "weight": 0.2, + "description": "在 GitLab backend-api 中创建了与支付超时相关的新 issue", + "check_logic": "对比 gitlab_mock 的 initial_state.issues 与 current_state.issues,筛选出 id 不在初始集合中的新 issue,将其 title 转小写后检查是否包含 'payment checkout timeout'、'payment' 或 'checkout timeout' 之一", + "pass_condition": "存在至少一个新 issue,且其 title 包含指定关键词之一" + }, + { + "name": "Component 2", + "weight": 0.25, + "description": "在 Notion 的 runbook 页面(page-rb)新增了包含具体修复步骤的块", + "check_logic": "对比 notion_mock 中 page-rb 页面的 initial_state 与 current_state 的 blockIds,找出新增 block;将这些新增 block 的内容拼接并转小写,检查是否包含 'timeout'、'retry'、'idempotent' 或 'gateway' 之一", + "pass_condition": "存在新增 block 且其内容包含指定关键词之一" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "在 Jira 工单 KAN-9(i9)的评论中贴回了 runbook 指针", + "check_logic": "对比 jira_mock 的 initial_state.comments 与 current_state.comments,筛选出 id 不在初始集合中且 issueId='i9' 的新评论;将新评论内容拼接转小写,检查是否包含 'runbook'、'payments runbook' 或 'notion' 之一", + "pass_condition": "存在至少一条符合条件的新评论,且内容包含指定关键词之一" + }, + { + "name": "Component 4", + "weight": 0.1, + "description": "在 Slack #engineering 频道由 user_1 发送的新消息中准确提及 KAN-9", + "check_logic": "获取 slack_mock current_state 中 engineering 频道的消息,排除 SEED 预置消息和 senderId != 'user_1' 的消息;将剩余消息内容拼接转小写,检查是否包含 'kan-9'", + "pass_condition": "处理后的消息内容中包含 'kan-9'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到 1.0 上限,并四舍五入保留 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空,脚本输出 REWARD: 0.0 并退出", + "从任一 mock 服务(jira_mock、gitlab_mock、notion_mock、slack_mock)拉取状态失败或返回非 200,脚本输出 REWARD: 0.0 并退出", + "各评分组件条件不满足时仅该组件不得分,不会导致提前退出" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 jira_mock、gitlab_mock、notion_mock、slack_mock 发送 HTTP GET 请求拉取当前状态。若任何一步失败,立即返回 0.0。随后按顺序执行 5 项评分检查:1) 检查 Jira 中 id 为 i9 的工单状态是否为 'In Progress';2) 检查 GitLab 是否新增了标题含支付/超时关键词的 issue;3) 检查 Notion 页面 page-rb 是否新增了含 timeout/retry/idempotent/gateway 关键词的 block;4) 检查 Jira 工单 i9 是否新增了含 runbook/notion 关键词的评论;5) 检查 Slack #engineering 频道中 user_1 发送的新消息是否包含 'kan-9'。每项通过则累加对应分值,最终总分经 min(total, 1.0) 限制后保留四位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. 文件头 docstring:\n - Reward Script: se_jira_gitlab_notion_b109\n - Task ID: 8d571c8b-9ef8-52b9-b0af-7b92ab5ea35d\n - Domain: mock_websites\n - Mocks: jira_mock, gitlab_mock, notion_mock, slack_mock\n - Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0):\n - [0.25] KAN-9 (payment timeout) moved to In Progress\n - [0.2] matching GitLab issue in backend-api\n - [0.25] runbook gains a concrete remediation step\n - [0.2] runbook pointer pasted back on KAN-9\n - [0.1] Slack names KAN-9 exactly\n\n2. 代码逻辑:\n - 读取 /tmp/task_web_sid 获取 sid,失败则输出 REWARD: 0.0 并退出\n - 从 MOCK_URLS 获取各个 mock 的 current_state,失败则输出 REWARD: 0.0 并退出\n - 定义 cur(mock) 获取 current_state\n - 定义 _lc(s) 转小写\n\n 评分组件:\n - c0 (0.25): jira_mock 中 issues 里 id 为 'i9' 的 issue,status 为 'In Progress'\n - c1 (0.2): gitlab_mock 中,对比 initial_state 和 current_state 的 issues,找出新创建的 issue(id 不在 initial 中),且 title 包含 'payment checkout timeout', 'payment', 或 'checkout timeout'(不区分大小写)\n - c2 (0.25): notion_mock 中,page-rb 页面,对比 initial_state 和 current_state 的 blockIds,找出新增的 block,且这些 block 的内容包含 'timeout', 'retry', 'idempotent', 'gateway' 之一(不区分大小写)\n - c3 (0.2): jira_mock 中,对比 initial_state 和 current_state 的 comments,找出新增的 comment(id 不在 initial 中),且 issueId 为 'i9',内容包含 'runbook', 'payments runbook', 'notion' 之一(不区分大小写)\n - c4 (0.1): slack_mock 中,engineering 频道,排除 SEED 中的消息和 senderId 不是 'user_1' 的消息,将所有消息内容拼接转小写,检查是否包含 'kan-9'(注意:all(t in c4_blob for t in ['kan-9']) 实际上就是检查 'kan-9' 是否在 c4_blob 中)\n\n 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 输出 REWARD: final\n\n3. 判断 is_placeholder:\n - 不是占位脚本,它真正检查了各个 mock 的状态。\n\n4. data_sources:\n - /tmp/task_web_sid\n - jira_mock (http://28.7.186.212:8173)\n - gitlab_mock (http://28.7.186.212:8157)\n - notion_mock (http://28.7.186.212:8186)\n - slack_mock (http://28.7.186.212:8198)\n\n5. failure_modes:\n - 读取 /tmp/task_web_sid 失败或为空\n - 获取任一 mock 状态失败(网络请求失败或返回非 200)\n - 各组件检查失败(不会提前退出,只是不得分)\n\n6. score_aggregation:\n - 各组件分数相加,最后钳制到上限 1.0(min(total, 1.0)),保留 4 位小数\n\n7. confidence:\n - 1.0,因为代码逻辑清晰完整\n\n现在构建 JSON:\n\ntask_id: \"se_jira_gitlab_notion_b109\" (从 docstring 中的 Reward Script 行提取,或者 Task ID 是 uuid。用户说\"从文件 docstring 中提取的任务 ID,如 se_review_006\"。看 docstring 第一行 \"Reward Script: se_jira_gitlab_notion_b109\",这看起来是任务 ID。虽然下面有 \"Task ID: 8d571c8b...\",但通常 se_xxx 这种是任务 ID。让我再看用户示例:\"如 se_review_006\"。docstring 中明确写了 \"Reward Script: se_jira_gitlab_notion_b109\",这应该作为 task_id。)\n\ndomain: \"mock_websites\"\n\nsummary: \"验证用户是否将 Jira 工单 KAN-9 移至进行中、在 GitLab backend-api 创建关联 issue、在 Notion runbook 添加修复步骤、将 runbook 链接回贴到 KAN-9,并在 Slack #engineering 频道提及 KAN-9。\"\n\nis_placeholder: false\n\ndata_sources: [\"/tmp/task_web_sid\", \"jira_mock\", \"gitlab_mock\", \"notion_mock\", \"slack_mock\"]\n\nscoring_components:\n- name: \"Component 0\" 或 \"KAN-9 状态变更\"\n weight: 0.25\n description: \"Jira 工单 KAN-9 (id=i9) 被移动到 In Progress 状态\"\n check_logic: \"从 jira_mock 的 current_state.issues 中查找 id='i9' 的 issue,检查其 status 字段是否等于 'In Progress'\"\n pass_condition: \"c0_iss 存在且 c0_iss.status == 'In Progress'\"\n\n- name: \"Component 1\" 或 \"GitLab 关联 Issue\"\n weight: 0.2\n description: \"在 GitLab backend-api 项目中创建了与支付超时相关的新 issue\"\n check_logic: \"对比 gitlab_mock 的 initial_state.issues 与 current_state.issues,筛选出 id 不在初始集合中的新 issue,检查新 issue 的 title(转小写后)是否包含 'payment checkout timeout'、'payment' 或 'checkout timeout' 之一\"\n pass_condition: \"存在至少一个新 issue,且其 title 包含指定关键词之一\"\n\n- name: \"Component 2\" 或 \"Notion Runbook 修复步骤\"\n weight: 0.25\n description: \"在 Notion 的 runbook 页面 (page-rb) 新增了包含具体修复步骤的块\"\n check_logic: \"对比 notion_mock 中 page-rb 页面的 initial_state 与 current_state 的 blockIds,找出新增 block;将这些新增 block 的内容拼接并转小写,检查是否包含 'timeout'、'retry'、'idempotent' 或 'gateway' 之一\"\n pass_condition: \"存在新增 block 且其内容包含指定关键词之一\"\n\n- name: \"Component 3\" 或 \"Jira Runbook 回贴\"\n weight: 0.2\n description: \"在 Jira 工单 KAN-9 (i9) 的评论中贴回了 runbook 指针/链接\"\n check_logic: \"对比 jira_mock 的 initial_state.comments 与 current_state.comments,筛选出 id 不在初始集合中且 issueId='i9' 的新评论;将新评论内容拼接转小写,检查是否包含 'runbook'、'payments runbook' 或 'notion' 之一\"\n pass_condition: \"存在至少一条符合条件的新评论,且内容包含指定关键词之一\"\n\n- name: \"Component 4\" 或 \"Slack 提及 KAN-9\"\n weight: 0.1\n description: \"在 Slack #engineering 频道由 user_1 发送的消息中准确提及 KAN-9\"\n check_logic: \"获取 slack_mock current_state 中 engineering 频道的消息,排除 SEED 中预置的消息和 senderId != 'user_1' 的消息;将剩余消息内容拼接转小写,检查是否包含 'kan-9'\"\n pass_condition: \"处理后的消息内容中包含 'kan-9'\"\n\ntotal_max_score: 1.0\n\nscore_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到 1.0 上限,并四舍五入保留 4 位小数\"\n\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或内容为空,脚本输出 REWARD: 0.0 并退出\",\n \"从任一 mock 服务(jira_mock、gitlab_mock、notion_mock、slack_mock)拉取状态失败或返回非 200,脚本输出 REWARD: 0.0 并退出\",\n \"各评分组件条件不满足时仅该组件不得分,不会提前退出\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 jira_mock、gitlab_mock、notion_mock、slack_mock 发送 HTTP GET 请求获取当前状态。若任何一步失败,立即返回 0.0。随后按顺序执行 5 项评分检查:1) 检查 Jira 中 id 为 i9 的工单状态是否为 'In Progress';2) 检查 GitLab 是否新增了标题含支付/超时关键词的 issue;3) 检查 Notion 页面 page-rb 是否新增了含 timeout/retry/idempotent/gateway 关键词的 block;4) 检查 Jira 工单 i9 是否新增了含 runbook/notion 关键词的评论;5) 检查 Slack #engineering 频道中 user_1 发送的新消息是否包含 'kan-9'。每项通过则累加对应分值,最终总分经 min(total, 1.0) 限制后保留四位小数输出。\"\n\nconfidence: 1.0\n\n检查 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n让我再确认 task_id。docstring 中有:\n\"Reward Script: se_jira_gitlab_notion_b109\"\n\"Task ID: 8d571c8b-9ef8-52b9-b0af-7b92ab5ea35d\"\n\n用户说:\"task_id\": \"从文件 docstring 中提取的任务 ID,如 se_review_006\"。示例是 se_review_006,这与 \"Reward Script: se_jira_gitlab_notion_b109\" 格式一致。而 \"Task ID:\" 后面跟的是 UUID。通常在这种上下文中,se_xxx 是任务 ID。我会用 \"se_jira_gitlab_notion_b109\"。\n\ndomain: \"mock_websites\"\n\n所有 set 对象在 JSON 中需要转为 list。我在描述中提到了集合,但 JSON 里不需要。\n\n确保没有 trailing comma。\n\n最终检查一遍。 {\"task_id\":\"se_jira_gitlab_notion_b109\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否将 Jira 工单 KAN-9 移至 In Progress、在 GitLab backend-api 创建关联 issue、在 Notion runbook 添加具体修复步骤、将 runbook 指针回贴到 KAN-9,并在 Slack #engineering 频道准确提及 KAN-9。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"jira_mock\",\"gitlab_mock\",\"notion_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 0\",\"weight\":0.25,\"description\":\"Jira 工单 KAN-9(id 为 i9)被移动到 In Progress 状态\",\"check_logic\":\"从 jira_mock 的 current_state.issues 中查找 id='i9' 的 issue,检查其 status 字段是否等于 'In Progress'\",\"pass_condition\":\"c0_iss 存在且 c0_iss.status == 'In Progress'\"},{\"name\":\"Component 1\",\"weight\":0.2,\"description\":\"在 GitLab backend-api 中创建了与支付超时相关的新 issue\",\"check_logic\":\"对比 gitlab_mock 的 initial_state.issues 与 current_state.issues,筛选出 id 不在初始集合中的新 issue,将其 title 转小写后检查是否包含 'payment checkout timeout'、'payment' 或 'checkout timeout' 之一\",\"pass_condition\":\"存在至少一个新 issue,且其 title 包含指定关键词之一\"},{\"name\":\"Component 2\",\"weight\":0.25,\"description\":\"在 Notion 的 runbook 页面(page-rb)新增了包含具体修复步骤的块\",\"check_logic\":\"对比 notion_mock 中 page-rb 页面的 initial_state 与 current_state 的 blockIds,找出新增 block;将这些新增 block 的内容拼接并转小写,检查是否包含 'timeout'、'retry'、'idempotent' 或 'gateway' 之一\",\"pass_condition\":\"存在新增 block 且其内容包含指定关键词之一\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"在 Jira 工单 KAN-9(i9)的评论中贴回了 runbook 指针\",\"check_logic\":\"对比 jira_mock 的 initial_state.comments 与 current_state.comments,筛选出 id 不在初始集合中且 issueId='i9' 的新评论;将新评论内容拼接转小写,检查是否包含 'runbook'、'payments runbook' 或 'notion' 之一\",\"pass_condition\":\"存在至少一条符合条件的新评论,且内容包含指定关键词之一\"},{\"name\":\"Component 4\",\"weight\":0.1,\"description\":\"在 Slack #engineering 频道由 user_1 发送的新消息中准确提及 KAN-9\",\"check_logic\":\"获取 slack_mock current_state 中 engineering 频道的消息,排除 SEED 预置消息和 senderId != 'user_1' 的消息;将剩余消息内容拼接转小写,检查是否包含 'kan-9'\",\"pass_condition\":\"处理后的消息内容中包含 'kan-9'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total, 1.0) 钳制到 1.0 上限,并四舍五入保留 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空,脚本输出 REWARD: 0.0 并退出\",\"从任一 mock 服务(jira_mock、gitlab_mock、notion_mock、slack_mock)拉取状态失败或返回非 200,脚本输出 REWARD: 0.0 并退出\",\"各评分组件条件不满足时仅该组件不得分,不会导致提前退出\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 jira_mock、gitlab_mock、notion_mock、slack_mock 发送 HTTP GET 请求拉取当前状态。若任何一步失败,立即返回 0.0。随后按顺序执行 5 项评分检查:1) 检查 Jira 中 id 为 i9 的工单状态是否为 'In Progress';2) 检查 GitLab 是否新增了标题含支付/超时关键词的 issue;3) 检查 Notion 页面 page-rb 是否新增了含 timeout/retry/idempotent/gateway 关键词的 block;4) 检查 Jira 工单 i9 是否新增了含 runbook/notion 关键词的评论;5) 检查 Slack #engineering 频道中 user_1 发送的新消息是否包含 'kan-9'。每项通过则累加对应分值,最终总分经 min(total, 1.0) 限制后保留四位小数输出。\",\"confidence\":1.0}" +} diff --git a/qa_defect_triage_001__long/_cua_gym_vm_bridge.sh b/qa_defect_triage_001__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/qa_defect_triage_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/qa_defect_triage_001__long/initial_setup.py b/qa_defect_triage_001__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4fca06df3ed121669ddcfd0dae0559c15c75769b --- /dev/null +++ b/qa_defect_triage_001__long/initial_setup.py @@ -0,0 +1,720 @@ +""" +Initial Setup: W02 — QA defect bulk-triage + vulnerability dispatch (v2) +Task ID: qa_defect_triage_001__long +Persona: QA Quinn +Mocks: jira_mock, gitlab_mock, discord_mock, google_sheets_mock + +Ground-truth embedding (read by reward.py from initial_state): + - Jira issues[*]._expected_priority / _expected_assignee on every OPEN defect + bug that must be bulk-triaged (the answer key). Severity is also written + onto the visible `labels` (e.g. 'severity:critical') so the agent can + decide the target values; the rule maps: + Critical severity -> priority 'Highest', assignee Sarah Connor (u4) + Major severity -> priority 'High', assignee John Smith (u3) + - Jira issues[*]._noise_defect == True on already-fixed (Done) defects and + non-defect backlog items; reward checks these were NOT disturbed. + - GitLab vulnerabilities[*]._expected_jira_key on every HIGH-RISK finding: + the Jira defect key that the finding corresponds to (same root cause / + topic). The agent must Create Issue for the finding, drag it to In + Progress, and then write that GitLab issue's number back onto the MATCHING + Jira defect's Description. reward reconciles vuln -> jira defect via this + key and checks the defect description carries the GitLab issue identifier. + NOTE: Jira's client-side normalizeIssue() strips unknown fields from + current_state, but /go returns the RAW posted state as initial_state, so the + hidden _expected_*/_noise_* keys persist exactly where reward reads them. The + agent-editable Description IS a whitelisted field, so the write-back persists. + +v2 changes (per REVIEW.md 5.0): + 1. The 10 OPEN target defects (5 critical + 5 major) are INTERLEAVED with ~10 + Done/non-defect noise rows in a single long, shuffled `issues` array (no + critical-then-major grouping), so targets are dispersed and the agent must + scroll/filter. (Backlog.tsx has no pagination, so a long mixed list is the + equivalent of "spilling onto page 2".) + 2. Three of the target defects are security defects that map 1:1 to the three + GitLab high-risk findings (matched by topic); the agent links them by + recording the GitLab issue number back onto the Jira defect. + 3. The 'Defect Triage' sheet ships ONLY a worked example row (KAN-000, all + four columns filled); every scored row is left fully blank (the agent + fills Bug Key / Severity / New Priority / Assignee itself). + +Observable outputs kept ABSENT at injection (Rule 3): + - every OPEN defect still has priority 'Medium' and assigneeId null + - GitLab has NO 'Investigate vulnerability: ...' issue and every high-risk + finding is still status 'detected' + - no Jira defect description mentions a GitLab issue number + - Google Sheet 'Defect Triage' has only the KAN-000 example filled + - Discord #qa 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}') + + +# --------------------------------------------------------------------------- +# Triage rule (documented in instruction; encoded here ONLY via the embedded +# answer key, NOT re-derived in reward): +# Critical-severity defect -> priority 'Highest', assignee Sarah Connor (u4) +# Major-severity defect -> priority 'High', assignee John Smith (u3) +# Every OPEN defect starts at priority 'Medium' / unassigned so each is a real +# change. +# --------------------------------------------------------------------------- +CRIT_PRIORITY = 'Highest' +MAJOR_PRIORITY = 'High' +CRIT_ASSIGNEE = 'u4' # Sarah Connor +MAJOR_ASSIGNEE = 'u3' # John Smith + + +# --------------------------------------------------------------------------- +# Jira builders +# --------------------------------------------------------------------------- +def jira_user(uid, name, email, rnd): + return {'id': uid, 'name': name, 'email': email, + 'avatar': f'https://picsum.photos/100/100?random={rnd}'} + + +def defect(key_n, summary, description, severity, created_iso): + """An OPEN defect bug awaiting bulk triage. Carries the hidden answer key + (_expected_priority / _expected_assignee) + a visible severity label. + Starts Medium / unassigned so the bulk change is a real edit.""" + if severity == 'critical': + exp_pri, exp_asg = CRIT_PRIORITY, CRIT_ASSIGNEE + else: + exp_pri, exp_asg = MAJOR_PRIORITY, MAJOR_ASSIGNEE + return { + 'id': f'i{key_n}', 'key': f'KAN-{key_n}', 'projectId': 'p1', + 'summary': summary, 'description': description, + 'type': 'Bug', 'status': 'To Do', 'priority': 'Medium', + 'storyPoints': 0, 'reporterId': 'u1', 'assigneeId': None, + 'sprintId': None, 'epicId': None, + 'createdAt': created_iso, 'updatedAt': created_iso, + 'labels': ['defect', f'severity:{severity}'], + 'subtasks': [], 'linkedIssueIds': [], + '_expected_priority': exp_pri, # hidden answer key + '_expected_assignee': exp_asg, # hidden answer key (user id) + '_defect_target': True, + } + + +def noise_issue(key_n, summary, description, type_, status, priority, + assignee_id, labels, created_iso): + """A backlog item the agent must NOT touch: already-fixed (Done) defects + or non-defect work. Carries _noise_defect so reward checks it stayed put.""" + return { + 'id': f'i{key_n}', 'key': f'KAN-{key_n}', 'projectId': 'p1', + 'summary': summary, 'description': description, + 'type': type_, 'status': status, 'priority': priority, + 'storyPoints': 0, 'reporterId': 'u1', 'assigneeId': assignee_id, + 'sprintId': None, 'epicId': None, + 'createdAt': created_iso, 'updatedAt': created_iso, + 'labels': labels, 'subtasks': [], 'linkedIssueIds': [], + '_noise_defect': True, + } + + +QUINN = jira_user('u1', 'Quinn Rivera', 'quinn.rivera@company.com', 'u1') +JIRA_USERS = [ + QUINN, + jira_user('u2', 'Jane Doe', 'jane.doe@company.com', 'u2'), + jira_user('u3', 'John Smith', 'john.smith@company.com', 'u3'), + jira_user('u4', 'Sarah Connor', 'sarah.connor@company.com', 'u4'), +] + +# --------------------------------------------------------------------------- +# 10 OPEN defects keyed by KAN number. 5 critical (-> Highest/Sarah), 5 major +# (-> High/John). Three of them are SECURITY defects whose topic matches a +# GitLab high-risk finding (see GL_VULN_MAP below) — the agent links those by +# writing the GitLab issue number into the defect description. Descriptions of +# the three mapped defects are deliberately digit-free so the only standalone +# number that can land in them is the GitLab issue id the agent writes back. +# --------------------------------------------------------------------------- +D = { + 101: defect(101, 'SQL injection in order-search endpoint', + "The order-search query concatenates raw user input, letting an attacker read other customers' orders. Confirmed on staging.", + 'critical', '2026-06-22T09:10:00.000Z'), # <-> GitLab vuln 1 + 102: defect(102, 'Hardcoded payment API key in mobile build', + 'The production payment-gateway API key is baked into the mobile build and can be pulled straight out of the shipped bundle.', + 'critical', '2026-06-22T10:30:00.000Z'), # <-> GitLab vuln 2 + 103: defect(103, 'Checkout crashes on payment confirmation (NullPointer)', + 'Tapping "Confirm payment" throws an NPE and the checkout screen white-screens. Repro every time.', + 'critical', '2026-06-23T08:05:00.000Z'), + 104: defect(104, 'Duplicate charges when retrying a failed payment', + 'Retrying a declined payment occasionally double-charges the card. Customer-facing money bug.', + 'critical', '2026-06-23T14:20:00.000Z'), + 105: defect(105, 'Orders silently dropped during cart sync', + 'Under concurrent edits the cart sync loses line items; orders submit with missing products. Data-loss.', + 'critical', '2026-06-24T11:00:00.000Z'), + 106: defect(106, 'Stored XSS in product review form', + 'User-submitted product reviews are rendered without sanitisation, so a crafted review runs script for every other shopper who views the page.', + 'major', '2026-06-24T13:40:00.000Z'), # <-> GitLab vuln 3 + 107: defect(107, 'Search returns stale results after changing filters', + 'Changing a facet filter shows the previous query results until a second refresh.', + 'major', '2026-06-25T09:25:00.000Z'), + 108: defect(108, 'Incorrect tax shown in cart summary', + 'Cart summary rounds tax down by one cent for multi-item orders in some regions.', + 'major', '2026-06-25T15:10:00.000Z'), + 109: defect(109, 'Avatar upload fails for large PNG files', + 'Profile avatar upload silently fails (no error shown) for PNGs above the size limit.', + 'major', '2026-06-26T10:00:00.000Z'), + 110: defect(110, 'Off-by-one timezone error in delivery estimate', + 'Delivery ETA is one day off for users far east of UTC due to a date-truncation bug.', + 'major', '2026-06-26T16:45:00.000Z'), +} + +# ~10 noise rows: already-fixed/wontfix Done defects (some carry tempting +# severity labels) + non-defect work. None is an OPEN defect, so none is a +# triage target; reward checks they stayed put. +N = { + 111: noise_issue(111, 'Login button misaligned on mobile', + 'Cosmetic alignment fixed and shipped in 4.2.1.', 'Bug', 'Done', + 'Low', 'u2', ['defect', 'severity:minor', 'fixed'], + '2026-06-08T09:00:00.000Z'), + 112: noise_issue(112, 'Typo in footer copyright year', + 'Footer year corrected; released.', 'Bug', 'Done', + 'Lowest', 'u2', ['defect', 'severity:trivial', 'fixed'], + '2026-06-09T09:00:00.000Z'), + 113: noise_issue(113, 'Crash on legacy iOS 12 (won\'t fix)', + 'Closed as won\'t-fix; iOS 12 is out of support.', 'Bug', 'Done', + 'Medium', 'u3', ['defect', 'severity:major', 'wontfix'], + '2026-06-10T09:00:00.000Z'), + 114: noise_issue(114, 'Add a dark-mode toggle to settings', + 'Feature request, not a defect.', 'Story', 'To Do', + 'Medium', None, ['enhancement'], + '2026-06-11T09:00:00.000Z'), + 115: noise_issue(115, 'Upgrade the CI build pipeline to Node 20', + 'Infra task, not a defect.', 'Task', 'To Do', + 'Low', 'u3', ['chore'], + '2026-06-12T09:00:00.000Z'), + 116: noise_issue(116, 'Cart total flickers on quantity change', + 'Already fixed and verified in the last release.', 'Bug', 'Done', + 'High', 'u2', ['defect', 'severity:critical', 'fixed'], + '2026-06-13T09:00:00.000Z'), + 117: noise_issue(117, 'Duplicate of the double-charge report', + 'Closed as duplicate; tracked elsewhere.', 'Bug', 'Done', + 'Medium', 'u3', ['defect', 'duplicate'], + '2026-06-14T09:00:00.000Z'), + 118: noise_issue(118, 'Checkout experience revamp', + 'Umbrella epic for the redesign.', 'Epic', 'To Do', + 'Medium', None, ['epic'], + '2026-06-15T09:00:00.000Z'), + 119: noise_issue(119, 'Broken coupon code at checkout', + 'Fixed; coupon validation corrected and shipped.', 'Bug', 'Done', + 'Medium', 'u2', ['defect', 'severity:major', 'fixed'], + '2026-06-16T09:00:00.000Z'), + 120: noise_issue(120, 'Add gift-wrap option to checkout', + 'Feature request from marketing, not a defect.', 'Story', 'To Do', + 'Low', None, ['enhancement'], + '2026-06-17T09:00:00.000Z'), +} + +# Interleaved / shuffled order: targets dispersed, critical & major alternate, +# Done/non-defect noise woven throughout so the list is long and the targets +# are not grouped. +_ORDER = [116, 101, 114, 106, 111, 103, 107, 118, 102, 112, + 108, 113, 104, 109, 115, 105, 119, 110, 117, 120] +ISSUES = [(D[k] if k in D else N[k]) for k in _ORDER] + +JIRA_STATE = { + 'currentUser': QUINN, + 'users': JIRA_USERS, + 'projects': [ + {'id': 'p1', 'key': 'KAN', 'name': 'Checkout & Payments', + 'leadId': 'u1', 'category': 'Software', + 'icon': 'https://picsum.photos/64/64?random=p1'}, + ], + 'sprints': [ + {'id': 's1', 'projectId': 'p1', 'name': 'Sprint 14', + 'goal': 'Stabilize checkout', 'startDate': '2026-06-22T12:00:00.000Z', + 'endDate': '2026-07-06T12:00:00.000Z', 'state': 'active'}, + ], + 'issues': 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': [], +} + +# --------------------------------------------------------------------------- +# GitLab — 'web-checkout' project. Security dashboard has high-risk findings +# (status 'detected', so the per-row "Create Issue" button is available). NO +# 'Investigate vulnerability: ...' issue is pre-seeded. Reducer has no +# DELETE_ISSUE, so reward never penalises extra issues (pure recall). +# +# Each HIGH-RISK finding carries _expected_jira_key: the Jira defect (by topic) +# that it corresponds to. The agent Creates the issue, drags it to In Progress, +# then writes that issue's number onto the matching Jira defect's description. +# --------------------------------------------------------------------------- +def gl_vuln(vid, name, severity, status, jira_key=None): + v = {'id': vid, 'projectId': 1, 'severity': severity, + 'name': name, 'status': status} + if jira_key is not None: + v['_expected_jira_key'] = jira_key # hidden answer key (vuln <-> defect) + return v + + +GITLAB_STATE = { + 'currentUser': {'id': 1, 'name': 'Quinn Rivera', 'username': 'quinn.rivera', 'avatarUrl': ''}, + 'projects': [ + {'id': 1, 'name': 'web-checkout', 'description': 'Customer checkout & payments web app', + 'visibility': 'private', 'stars': 9, 'forks': 3, 'updatedAt': '2026-06-26T00:00:00.000Z', + 'branches': ['main', 'release', 'hotfix'], 'files': []}, + ], + 'pipelines': [], + 'issues': [ + # unrelated decoy issues only — NO security investigation issues + {'id': 1, 'projectId': 1, 'title': 'Refresh QA test plan for 4.3', + 'description': 'Doc chore.', 'status': 'open', 'labels': ['docs'], 'assignee': 'Quinn Rivera'}, + {'id': 2, 'projectId': 1, 'title': 'Flaky checkout e2e on CI', + 'description': 'Known flaky test.', 'status': 'in_progress', 'labels': ['ci'], 'assignee': 'Quinn Rivera'}, + ], + 'mergeRequests': [], + 'registry': [], + 'snippets': [], + 'wiki': [], + 'vulnerabilities': [ + gl_vuln(1, 'SQL Injection in order-search endpoint', 'critical', 'detected', 'KAN-101'), # high-risk -> KAN-101 + gl_vuln(2, 'Hardcoded payment API key in mobile build', 'critical', 'detected', 'KAN-102'), # high-risk -> KAN-102 + gl_vuln(3, 'Stored XSS in product review form', 'high', 'detected', 'KAN-106'), # high-risk -> KAN-106 + gl_vuln(4, 'Verbose error stack traces leak file paths', 'medium', 'detected'), # noise (not high-risk) + gl_vuln(5, 'Missing security headers on static assets', 'low', 'resolved'), # noise (resolved) + ], + 'milestones': [], + 'releases': [], +} + +# --------------------------------------------------------------------------- +# Discord — QA server with an empty #qa channel (decoy chatter elsewhere). +# --------------------------------------------------------------------------- +def d_user(uid, username, disc, rnd, bot=False): + return {'id': uid, 'username': username, 'discriminator': disc, + 'avatar': f'https://picsum.photos/seed/{rnd}/128/128', + 'status': 'online', 'customStatus': None, + 'aboutMe': '', 'roles': ['role-qa'], 'badges': [], + 'bannerColor': '#5865F2', 'joinedAt': '2026-01-10T10:00:00Z', 'isBot': bot} + + +def d_channel(cid, name, topic, pos): + return {'id': cid, 'serverId': 'server-1', 'name': name, 'type': 'text', + 'category': 'QA', 'topic': topic, 'position': pos, 'isNsfw': False, + 'slowMode': 0, 'pinnedMessageIds': [], 'lastMessageId': None, + 'unreadCount': 0} + + +def d_msg(mid, cid, uid, content, ts): + return {'id': mid, 'channelId': cid, 'userId': uid, 'content': content, + 'timestamp': ts, 'editedTimestamp': None, 'reactions': {}, + 'attachments': [], 'embeds': [], 'mentions': [], 'pinned': False, + 'type': 'default', 'referencedMessageId': None, 'threadId': None, + 'isEdited': False} + + +DISCORD_USERS = { + 'user-current': d_user('user-current', 'Quinn', '0001', 'quinn'), + 'user-2': d_user('user-2', 'Jane', '0002', 'jane'), + 'user-3': d_user('user-3', 'John', '0003', 'john'), + 'user-4': d_user('user-4', 'Sarah', '0004', 'sarah'), +} +DISCORD_USERS['user-current']['id'] = 'user-current' + +DISCORD_STATE = { + 'currentUser': {'id': 'user-current', 'username': 'Quinn', 'discriminator': '0001', + 'avatar': 'https://picsum.photos/seed/quinn/128/128', 'status': 'online', + 'customStatus': None, 'aboutMe': 'QA engineer', 'roles': ['role-qa'], + 'badges': [], 'bannerColor': '#5865F2', 'joinedAt': '2026-01-10T10:00:00Z', + 'isBot': False}, + 'servers': { + 'server-1': { + 'id': 'server-1', 'name': 'Engineering', 'icon': 'https://picsum.photos/seed/eng/64/64', + 'ownerId': 'user-current', 'channels': ['ch-general', 'ch-qa', 'ch-releases'], + 'roles': ['role-qa'], 'members': ['user-current', 'user-2', 'user-3', 'user-4'], + 'categories': [{'id': 'cat-1', 'name': 'QA', 'channelIds': ['ch-general', 'ch-qa', 'ch-releases']}], + 'description': 'Engineering workspace', 'boostCount': 0, 'boostTier': 0, + }, + }, + 'channels': { + 'ch-general': d_channel('ch-general', 'general', 'Team chatter', 0), + 'ch-qa': d_channel('ch-qa', 'qa', 'Defect triage updates & QA summaries', 1), + 'ch-releases': d_channel('ch-releases', 'releases', 'Release coordination', 2), + }, + 'messages': { + 'm-g-1': d_msg('m-g-1', 'ch-general', 'user-2', + 'Morning! Bug bash queue is open — defects are piling up in the backlog.', + '2026-06-29T13:02:00Z'), + 'm-g-2': d_msg('m-g-2', 'ch-general', 'user-3', + 'Thanks Jane, I will pick up whatever gets assigned to me.', + '2026-06-29T13:05:00Z'), + 'm-r-1': d_msg('m-r-1', 'ch-releases', 'user-4', + 'Targeting 4.3 once the critical checkout bugs are triaged.', + '2026-06-29T13:10:00Z'), + }, + 'threads': {}, + 'users': DISCORD_USERS, + 'roles': { + 'role-qa': {'id': 'role-qa', 'serverId': 'server-1', 'name': 'QA', 'color': '#1abc9c', + '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 — 'Defect Triage' ledger. +# Row 1: header (Bug Key | Severity | New Priority | Assignee) +# Row 2: a single worked EXAMPLE row, KAN-000, with ALL FOUR columns filled +# to demonstrate the format — reward IGNORES it. +# Rows 3+: left ENTIRELY BLANK (Rule 3). The agent fills Bug Key / Severity / +# New Priority / Assignee for each defect it triages. reward keys off +# the Bug Key the agent writes, never off a fixed row number. +# --------------------------------------------------------------------------- +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'}} + + +_sheet_data = { + 'A1': hcell('Bug Key'), + 'B1': hcell('Severity'), + 'C1': hcell('New Priority'), + 'D1': hcell('Assignee'), + # worked example only — reward ignores KAN-000 + 'A2': cell('KAN-000'), + 'B2': cell('Critical'), + 'C2': cell('Highest'), + 'D2': cell('Sarah Connor'), +} + +SHEETS_STATE = { + 'id': 'workbook_defect_triage', 'title': 'Defect Triage', + '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': 'Defect Triage', '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:8137', GITLAB_STATE), # gitlab_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/qa_defect_triage_001__long/reward.py b/qa_defect_triage_001__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..696e9b8517358e2e1f5bea768eac80a260adba9c --- /dev/null +++ b/qa_defect_triage_001__long/reward.py @@ -0,0 +1,429 @@ +""" +Reward Script: W02 — QA defect bulk-triage + vulnerability dispatch (v2) +Task ID: qa_defect_triage_001__long +Persona: QA Quinn +Mocks: jira_mock, gitlab_mock, discord_mock, google_sheets_mock + +Answer key (embedded in initial_state, read here — never re-derived): + - jira issues[*]._expected_priority / _expected_assignee on every OPEN defect + that must be bulk-triaged (the L2 anchor target set). + - jira issues[*]._noise_defect == True on already-fixed/non-defect items the + agent must NOT touch. + - gitlab vulnerabilities[*]._expected_jira_key on every HIGH-RISK finding: + the Jira defect key the finding maps to (vuln <-> defect correspondence). + +Scoring (sub-weights sum to 1.0): + 0.40 Jira bulk triage (L2 anchor): per target defect, current priority == + _expected_priority AND current assigneeId == _expected_assignee. + Reachable only via the gated Bulk Change button (rendered only when + >=1 issue is checkbox-selected on the Backlog). A disturbed NOISE item + deducts a small penalty inside this component. + 0.15 GitLab vulnerability issues (recall, no penalty for extras): for each + high-risk finding, an issue titled 'Investigate vulnerability: ' + exists AND is in the 'In Progress' column (status == 'in_progress'). + 0.15 Cross-app reconciliation: the GitLab issue number raised for each + high-risk finding is written back onto the MATCHING Jira defect's + Description (looked up via _expected_jira_key). Loose: the GitLab + issue's id appears as a number in that defect's current description. + 0.15 Google Sheet 'Defect Triage' ledger: validated BY ROW CONTENT — for + each data row (KAN-000 example skipped) the agent's Bug Key is looked + up in the answer key and the row's New Priority + Assignee are checked. + Never relies on a fixed row number. + 0.15 Discord #qa summary: a message reporting the defect count (loose + keyword + count match, with a partial-credit 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', + 'gitlab': 'http://28.7.184.198:8137', + '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 _collapse_ws(s): + return re.sub(r'\s+', ' ', norm(s)) + + +def _ints_in(text): + return set(int(x) for x in re.findall(r'\d+', str(text or ''))) + + +def _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +def _by_id(records, key='id'): + 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 row recovery (cell-grid -> rows keyed by header) --- +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, dict): + sheet = sheets.get(sheet_name, {}) + data_rows = _parse_rows_from_sheet_data(sheet.get('data', {})) + if data_rows: + return data_rows + 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 channel message recovery (messages map keyed by id) --- +def _discord_channel_messages(state, channel_name): + channels = state.get('channels', {}) or {} + target_id = None + if isinstance(channels, dict): + for cid, ch in channels.items(): + if norm((ch or {}).get('name')) == norm(channel_name): + target_id = (ch or {}).get('id') or cid + break + elif isinstance(channels, list): + for ch in channels: + if norm((ch or {}).get('name')) == norm(channel_name): + target_id = (ch or {}).get('id') + break + if target_id is None: + return [] + out = [] + messages = state.get('messages', {}) or {} + msg_iter = messages.values() if isinstance(messages, dict) else messages + for m in msg_iter: + if isinstance(m, dict) and norm(m.get('channelId')) == norm(target_id): + out.append(m) + return out + + +# ============================================================================= +# Task-specific reward +# ============================================================================= +def reward(go): + jira_i = go('jira').get('initial_state', {}) or {} + jira_c = go('jira').get('current_state', {}) or {} + gl_i = go('gitlab').get('initial_state', {}) or {} + gl_c = go('gitlab').get('current_state', {}) or {} + disc_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') + issues_c_by_key = {norm(i.get('key')): i for i in (jira_c.get('issues', []) or []) + if isinstance(i, dict)} + + # ---- Answer key: OPEN defects carrying the embedded triage target ---- + targets = [c for c in issues_i + if c.get('_expected_priority') and c.get('_expected_assignee')] + n = len(targets) + if n == 0: + print('DEBUG_W02 no target defects with embedded key; nothing to score') + return 0.0 + + n_crit = sum(1 for t in targets if norm(t['_expected_priority']) == 'highest') + n_major = sum(1 for t in targets if norm(t['_expected_priority']) == 'high') + + # ---- 1) Jira bulk triage (L2 anchor) — 0.40 ---- + triage_match = 0 + try: + for t in targets: + cur = issues_c_by_id.get(t['id'], {}) + if (norm(cur.get('priority')) == norm(t['_expected_priority']) + and norm(cur.get('assigneeId')) == norm(t['_expected_assignee'])): + triage_match += 1 + except Exception as e: + print(f'DEBUG_W02 triage component error: {e!r}') + triage_score = frac(triage_match, n) + + # Noise integrity: penalise (within this component) any noise item whose + # priority OR assignee changed from its injected value. + noise_disturbed = 0 + noise_total = 0 + try: + for ni in issues_i: + if not ni.get('_noise_defect'): + continue + noise_total += 1 + cur = issues_c_by_id.get(ni['id'], {}) + if (norm(cur.get('priority')) != norm(ni.get('priority')) + or norm(cur.get('assigneeId')) != norm(ni.get('assigneeId'))): + noise_disturbed += 1 + except Exception as e: + print(f'DEBUG_W02 noise component error: {e!r}') + noise_penalty = frac(noise_disturbed, noise_total) if noise_total else 0.0 + triage_score = max(0.0, triage_score - noise_penalty) + + # ---- High-risk vuln answer key (shared by components 2 & 3) ---- + high_risk = [] + try: + for v in gl_i.get('vulnerabilities', []) or []: + if norm(v.get('severity')) in ('critical', 'high'): + high_risk.append(v) + except Exception as e: + print(f'DEBUG_W02 vuln-key error: {e!r}') + n_vuln = len(high_risk) + issues_glc = gl_c.get('issues', []) or [] + + # ---- 2) GitLab vulnerability issues (recall + in_progress) — 0.15 ---- + gl_match = 0 + try: + for v in high_risk: + vname = norm(v.get('name')) + for iss in issues_glc: + title = _collapse_ws(iss.get('title')) + if ('investigate vulnerability' in title and vname and vname in title + and norm(iss.get('status')) == 'in_progress'): + gl_match += 1 + break + except Exception as e: + print(f'DEBUG_W02 gitlab component error: {e!r}') + gl_score = frac(gl_match, n_vuln) if n_vuln else 1.0 + + # ---- 3) Cross-app: GitLab issue number written back to matching Jira + # defect description — 0.15 ---- + # For each high-risk finding: locate the GitLab issue raised for it + # (title 'Investigate vulnerability: '), take its id, and require + # that id to appear (as a number) in the description of the Jira defect + # named by _expected_jira_key. Mapped defect descriptions are digit-free at + # injection, so any matching number is the agent's write-back. + writeback_match = 0 + try: + for v in high_risk: + vname = norm(v.get('name')) + jira_key = norm(v.get('_expected_jira_key')) + if not jira_key: + continue + # find the GitLab issue raised for this vuln -> its id (iid) + gl_iid = None + for iss in issues_glc: + title = _collapse_ws(iss.get('title')) + if 'investigate vulnerability' in title and vname and vname in title: + gl_iid = iss.get('id') + break + if gl_iid is None: + continue + defect_cur = issues_c_by_key.get(jira_key, {}) + desc_ints = _ints_in(defect_cur.get('description')) + try: + if int(gl_iid) in desc_ints: + writeback_match += 1 + except (TypeError, ValueError): + if str(gl_iid) and str(gl_iid) in (defect_cur.get('description') or ''): + writeback_match += 1 + except Exception as e: + print(f'DEBUG_W02 writeback component error: {e!r}') + writeback_score = frac(writeback_match, n_vuln) if n_vuln else 1.0 + + # ---- 4) Google Sheet 'Defect Triage' ledger — by-row content — 0.15 ---- + # Build expected map keyed by Bug Key; iterate the agent's rows (skip the + # KAN-000 example), match by the Bug Key the agent typed. Never row-indexed. + name_by_uid = {} + try: + for u in jira_i.get('users', []) or []: + name_by_uid[u.get('id')] = u.get('name') + except Exception: + pass + key_to_expected = {} + for t in targets: + uid = t['_expected_assignee'] + key_to_expected[norm(t.get('key'))] = { + 'priority': norm(t['_expected_priority']), + 'assignee_names': {norm(uid), norm(name_by_uid.get(uid))}, + } + matched_keys = set() + try: + rows_c = _sheet_rows(go('google_sheets'), 'current_state', 'Defect Triage') + + def _rf(row, *aliases): + for a in aliases: + if a in row: + return row[a] + return '' + + for row in rows_c: + key = norm(_rf(row, 'bug key', 'key', 'bug')) + if not key or key == 'kan-000': # skip blanks + worked example + continue + exp = key_to_expected.get(key) + if not exp or key in matched_keys: + continue + pri_ok = norm(_rf(row, 'new priority', 'priority')) == exp['priority'] + asg_ok = norm(_rf(row, 'assignee', 'owner')) in exp['assignee_names'] + if pri_ok and asg_ok: + matched_keys.add(key) + except Exception as e: + print(f'DEBUG_W02 sheet component error: {e!r}') + sheet_match = len(matched_keys) + sheet_score = frac(sheet_match, n) + + # ---- 5) Discord #qa summary — 0.15 ---- + disc_ok = 0.0 + try: + chan = _discord_channel_messages(disc_c, 'qa') + for msg in chan: + txt = (_msg_text(msg) or '').lower() + if not txt.strip(): + continue + nums = [int(x) for x in re.findall(r'\d+', txt)] + if n in nums and ('defect' in txt or 'bug' in txt or 'triag' in txt): + disc_ok = 1.0 + break + if disc_ok == 0.0: # partial credit: any triage-flavored summary message + for msg in chan: + txt = (_msg_text(msg) or '').lower() + if txt.strip() and ('triag' in txt or 'defect' in txt or 'critical' in txt): + disc_ok = 0.5 + break + except Exception as e: + print(f'DEBUG_W02 discord component error: {e!r}') + + # ---- Combine ---- + s_triage = 0.40 * triage_score + s_gl = 0.15 * gl_score + s_wb = 0.15 * writeback_score + s_sheet = 0.15 * sheet_score + s_disc = 0.15 * disc_ok + score = s_triage + s_gl + s_wb + s_sheet + s_disc + + print( + 'DEBUG_W02 ' + f'n_defects={n} n_crit={n_crit} n_major={n_major} n_vuln={n_vuln} ' + f'triage_match={triage_match}/{n} noise_disturbed={noise_disturbed}/{noise_total} ' + f'triage_score={round(triage_score, 4)} ' + f'gl_match={gl_match}/{n_vuln} gl_score={round(gl_score, 4)} ' + f'writeback_match={writeback_match}/{n_vuln} writeback_score={round(writeback_score, 4)} ' + f'sheet_match={sheet_match}/{n} sheet_score={round(sheet_score, 4)} ' + f'disc_ok={disc_ok} ' + f'w_triage={round(s_triage, 4)} w_gl={round(s_gl, 4)} w_wb={round(s_wb, 4)} ' + f'w_sheet={round(s_sheet, 4)} w_disc={round(s_disc, 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_followup_001/_cua_gym_vm_bridge.sh b/recruit_followup_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_followup_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/recruit_followup_001/initial_setup.py b/recruit_followup_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc7c00d40f51fd7ad754b10d3fb1120d992e204 --- /dev/null +++ b/recruit_followup_001/initial_setup.py @@ -0,0 +1,212 @@ +""" +Initial Setup: Recruiting follow-up — thank-you email to candidate + Slack scorecard reminder +Task ID: recruit_followup_001 +Domain: mock_websites (multi-mock: gmail_mock + slack_mock) +""" +import hashlib +import os +import shlex +import subprocess +import time + +import requests + +TASK_ID = 'recruit_followup_001' + +GMAIL_URL = 'http://28.7.184.198:8138' +SLACK_URL = 'http://28.7.184.198:8178' + +# Isolation note: initial_env and golden_env are SEPARATE containers that share +# the xlang.ai HTTP server, whose state is keyed SOLELY by sid. To keep the two +# server states independent, each env uses its OWN deterministic sid derived +# from TASK_ID. initial_setup uses '-init'; golden_patch uses '-gold' +# and independently rebuilds this same baseline before applying its changes. +_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}') + + +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) + + +# --------------------------------------------------------------------------- +# Gmail initial state — recruiter inbox, NO sent thank-you to Diego yet +# --------------------------------------------------------------------------- +gmail_state = { + "user": { + "userId": "u1", + "username": "Taylor Reed", + "email": "recruiter@company.com", + }, + "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": "Interview scheduled: Diego Ramos — Backend Engineer (Technical Interview)", + "body": "

    The Technical Interview for Diego Ramos (Backend Engineer) is scheduled for today at 2:00 PM. Interviewers: Sara Mitchell and Ben Carter.

    ", + "timestamp": "2026-06-30T08:15:00Z", + "read": True, + "starred": False, + "important": True, + "labels": ["l1"], + "category": "primary", + "folder": "inbox", + "attachments": [], + }, + { + "id": "email_2", + "threadId": "thread_2", + "from": {"name": "Diego Ramos", "email": "diego.ramos@gmail.com"}, + "to": [{"name": "Taylor Reed", "email": "recruiter@company.com"}], + "subject": "Re: Backend Engineer interview logistics", + "body": "

    Hi Taylor, thanks for setting this up. I'm looking forward to the technical interview today. Best, Diego

    ", + "timestamp": "2026-06-29T16:40:00Z", + "read": True, + "starred": False, + "important": False, + "labels": [], + "category": "primary", + "folder": "inbox", + "attachments": [], + }, + { + "id": "email_3", + "threadId": "thread_3", + "from": {"name": "Sara Mitchell", "email": "sara.mitchell@company.com"}, + "to": [{"name": "Taylor Reed", "email": "recruiter@company.com"}], + "subject": "Confirming I can cover the Diego Ramos panel", + "body": "

    Hi Taylor, Ben and I are both set for Diego's technical interview this afternoon. We'll get the scorecards in afterward.

    ", + "timestamp": "2026-06-29T11:05:00Z", + "read": True, + "starred": False, + "important": False, + "labels": ["l1"], + "category": "primary", + "folder": "inbox", + "attachments": [], + }, + { + "id": "email_4", + "threadId": "thread_4", + "from": {"name": "HR Operations", "email": "hr-ops@company.com"}, + "to": [{"name": "Taylor Reed", "email": "recruiter@company.com"}], + "subject": "Weekly hiring pipeline summary", + "body": "

    Attached is this week's pipeline summary across all open requisitions. 14 candidates active, 3 offers pending.

    ", + "timestamp": "2026-06-28T09:30:00Z", + "read": True, + "starred": False, + "important": False, + "labels": [], + "category": "primary", + "folder": "inbox", + "attachments": [], + }, + { + "id": "email_5", + "threadId": "thread_5", + "from": {"name": "Taylor Reed", "email": "recruiter@company.com"}, + "to": [{"name": "Marcus Webb", "email": "marcus.webb@gmail.com"}], + "subject": "Thank you for interviewing for the Frontend Engineer role", + "body": "

    Hi Marcus, thank you for taking the time to interview with us yesterday. We'll be in touch with next steps soon. Best, Taylor

    ", + "timestamp": "2026-06-29T17:20:00Z", + "read": True, + "starred": False, + "important": False, + "labels": [], + "category": "primary", + "folder": "sent", + "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": [], +} + +# --------------------------------------------------------------------------- +# Slack initial state — #hiring exists, sara & ben present, NO scorecard reminder yet +# --------------------------------------------------------------------------- +slack_state = { + "currentUser": { + "userId": "user_1", + "fullName": "Taylor Reed", + "displayName": "taylor", + "email": "recruiter@company.com", + "avatar": "https://picsum.photos/200/200?random=1", + "title": "Technical Recruiter", + "status": "online", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York", + }, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", "icon": ""}, + "users": [ + {"userId": "user_1", "fullName": "Taylor Reed", "displayName": "taylor", "email": "recruiter@company.com", "avatar": "https://picsum.photos/200/200?random=1", "title": "Technical Recruiter", "status": "online"}, + {"userId": "user_2", "fullName": "Sara Mitchell", "displayName": "sara", "email": "sara.mitchell@company.com", "avatar": "https://picsum.photos/200/200?random=2", "title": "Senior Backend Engineer", "status": "online"}, + {"userId": "user_3", "fullName": "Ben Carter", "displayName": "ben", "email": "ben.carter@company.com", "avatar": "https://picsum.photos/200/200?random=3", "title": "Staff Engineer", "status": "online"}, + {"userId": "user_4", "fullName": "Priya Nair", "displayName": "priya", "email": "priya.nair@company.com", "avatar": "https://picsum.photos/200/200?random=4", "title": "Engineering Manager", "status": "away"}, + {"userId": "user_5", "fullName": "Jordan Lee", "displayName": "jordan", "email": "jordan.lee@company.com", "avatar": "https://picsum.photos/200/200?random=5", "title": "Recruiting Coordinator", "status": "online"}, + ], + "channels": [ + {"channelId": "hiring", "name": "hiring", "description": "Coordination for open roles and interviews", "topic": "Hiring pipeline updates", "isPrivate": False, "isStarred": True, "members": ["user_1", "user_2", "user_3", "user_4", "user_5"], "createdBy": "user_1", "createdAt": "2026-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "general", "name": "general", "description": "Company-wide announcements", "topic": "", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3", "user_4", "user_5"], "createdBy": "user_1", "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "engineering", "name": "engineering", "description": "Engineering team chat", "topic": "", "isPrivate": False, "isStarred": False, "members": ["user_2", "user_3", "user_4"], "createdBy": "user_4", "createdAt": "2026-01-02T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "hiring": [ + {"messageId": "msg_1", "senderId": "user_5", "content": "Morning all — Diego Ramos (Backend Engineer) is in for his technical interview at 2pm today.", "timestamp": "2026-06-30T08:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_2", "senderId": "user_2", "content": "Got it, Ben and I are running the panel.", "timestamp": "2026-06-30T08:42:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_3", "senderId": "user_4", "content": "Great, looking forward to the debrief.", "timestamp": "2026-06-30T09:01:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "general": [ + {"messageId": "msg_g1", "senderId": "user_4", "content": "Reminder: all-hands moved to Thursday 11am.", "timestamp": "2026-06-29T15:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "engineering": [ + {"messageId": "msg_e1", "senderId": "user_3", "content": "Deploy window tonight 8pm, heads up.", "timestamp": "2026-06-30T07:50: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 state into both mocks with the same sid +# --------------------------------------------------------------------------- +for name, url, state in [ + ("gmail", GMAIL_URL, gmail_state), + ("slack", SLACK_URL, slack_state), +]: + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + 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'{name}: state injected and verified') + +# --------------------------------------------------------------------------- +# Launch browser — primary mock is gmail (workflow starts there) +# --------------------------------------------------------------------------- +launch_gui(f'google-chrome "{GMAIL_URL}/?sid={sid}"', delay_sec=2.0) +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched Gmail and Slack with sid={sid}') diff --git a/recruit_followup_001/reward.py b/recruit_followup_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..8583ab98bde0c9cfd061030fe7f0482a0e1618c6 --- /dev/null +++ b/recruit_followup_001/reward.py @@ -0,0 +1,143 @@ +""" +Reward Script: Same-day follow-up to candidate Diego Ramos (Gmail) + Slack #hiring + reminder asking the two interviewers (@sara, @ben) to submit their + Greenhouse scorecards by end of day. +Task ID: recruit_followup_001 +Domain: mock_websites (gmail + slack) +Scoring (only task-introduced changes; every component fails on a clean initial_env): + C1 (0.30) NEW sent Gmail email to diego.ramos@gmail.com (absent from initial_state) + C2 (0.20) that email thanks Diego AND references today's technical interview + C3 (0.30) NEW #hiring Slack message (absent from initial_state) mentioning @sara AND @ben + C4 (0.20) that message asks to submit scorecards (Greenhouse / end-of-day) + Total: 1.0 +Fully deterministic / structural — no LLM judge needed. +""" +import json +import re +import sys + +import requests + +GMAIL_URL = 'http://28.7.184.198:8138' +SLACK_URL = 'http://28.7.184.198:8178' + +# --- Read sid (per-env, 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) + +print(f'SID: {sid}') + +# --- Fetch state from both mocks --- +try: + gmail = requests.get(f'{GMAIL_URL}/go?sid={sid}', timeout=15).json() + slack = requests.get(f'{SLACK_URL}/go?sid={sid}', timeout=15).json() +except Exception as e: + print(f'CRITICAL: Cannot fetch mock state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def _norm(s): + return (s or '').lower() + + +def verify_task(): + total_score = 0.0 + + # ---- Identify NEW items (present in current_state, absent from initial_state) ---- + # Gmail: new emails by id + g_init = gmail.get('initial_state', {}).get('emails', []) or [] + g_cur = gmail.get('current_state', {}).get('emails', []) or [] + init_email_ids = {e.get('id') for e in g_init} + new_emails = [e for e in g_cur if e.get('id') not in init_email_ids] + + # Slack: new #hiring messages by messageId + s_init = slack.get('initial_state', {}).get('messages', {}).get('hiring', []) or [] + s_cur = slack.get('current_state', {}).get('messages', {}).get('hiring', []) or [] + init_msg_ids = {m.get('messageId') for m in s_init} + new_hiring_msgs = [m for m in s_cur if m.get('messageId') not in init_msg_ids] + + # ---- Component 1: NEW sent email to diego.ramos@gmail.com (0.30) ---- + # Anchored to the task change: a freshly sent email must not exist in initial_state. + diego_email = None + try: + for e in new_emails: + tos = [_norm(t.get('email')) for t in (e.get('to') or [])] + if e.get('folder') == 'sent' and 'diego.ramos@gmail.com' in tos: + diego_email = e + break + if diego_email is not None: + print(f"PASS: C1 — new SENT email to diego.ramos@gmail.com (id={diego_email.get('id')}) (0.30 pts)") + total_score += 0.30 + else: + print('FAIL: C1 — no NEW sent email to diego.ramos@gmail.com') + except Exception as e: + print(f'ERROR: C1 — {e}') + + # ---- Component 2: that email thanks Diego AND references the technical interview (0.20) ---- + try: + if diego_email is not None: + text = _norm(diego_email.get('subject')) + ' ' + _norm(diego_email.get('body')) + has_thanks = 'thank' in text + has_interview = 'interview' in text + # 'today' / 'technical' strengthen the same-day technical-interview reference, + # but are not strictly required beyond the interview reference itself. + if has_thanks and has_interview: + print(f'PASS: C2 — email thanks Diego and references the interview (0.20 pts)') + total_score += 0.20 + else: + print(f'FAIL: C2 — thanks={has_thanks} interview_ref={has_interview}') + else: + print('FAIL: C2 — no candidate email to evaluate') + except Exception as e: + print(f'ERROR: C2 — {e}') + + # ---- Component 3: NEW #hiring message mentioning @sara AND @ben (0.30) ---- + reminder_msg = None + try: + for m in new_hiring_msgs: + c = _norm(m.get('content')) + has_sara = bool(re.search(r'@?\bsara\b', c)) + has_ben = bool(re.search(r'@?\bben\b', c)) + if has_sara and has_ben: + reminder_msg = m + break + if reminder_msg is not None: + print(f"PASS: C3 — new #hiring msg mentions sara AND ben (id={reminder_msg.get('messageId')}) (0.30 pts)") + total_score += 0.30 + else: + print('FAIL: C3 — no NEW #hiring message mentioning both sara and ben') + except Exception as e: + print(f'ERROR: C3 — {e}') + + # ---- Component 4: that message asks to submit scorecards (Greenhouse / EOD) (0.20) ---- + try: + if reminder_msg is not None: + c = _norm(reminder_msg.get('content')) + has_scorecard = 'scorecard' in c + # supporting context: submitting in Greenhouse and/or by end of day + has_context = ('greenhouse' in c) or ('end of day') in c or ('eod' in c) or ('submit' in c) + if has_scorecard and has_context: + print(f'PASS: C4 — message asks to submit scorecards (Greenhouse/EOD) (0.20 pts)') + total_score += 0.20 + else: + print(f'FAIL: C4 — scorecard={has_scorecard} context(submit/greenhouse/eod)={has_context}') + else: + print('FAIL: C4 — no reminder message to evaluate') + except Exception as e: + print(f'ERROR: C4 — {e}') + + final_score = min(total_score, 1.0) + print(f'\nScore: {total_score}/1.0') + print(f'REWARD: {final_score}') + return final_score + + +verify_task() diff --git a/recruit_followup_001/reward_label.json b/recruit_followup_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..9b295c5488bc57ab59c61d253b4ba203bb07a00c --- /dev/null +++ b/recruit_followup_001/reward_label.json @@ -0,0 +1,60 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/recruit_followup_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:32:09", + "label": { + "task_id": "recruit_followup_001", + "domain": "mock_websites (gmail + slack)", + "summary": "验证是否向候选人 Diego Ramos 发送了感谢并提及技术面试的新邮件,并在 Slack #hiring 频道发送了提醒 Sara 和 Ben 提交 Greenhouse 评分卡的新消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "Gmail mock 服务 (GMAIL_URL)", + "Slack mock 服务 (SLACK_URL)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.3, + "description": "检查是否存在新增的已发送邮件给 diego.ramos@gmail.com", + "check_logic": "对比 gmail['initial_state']['emails'] 与 gmail['current_state']['emails'],筛选出 id 不在 initial_state 中的 new_emails;遍历 new_emails,检查 e['folder'] == 'sent' 且 e['to'] 列表中包含 'diego.ramos@gmail.com'", + "pass_condition": "存在一封新的 sent 邮件,其收件人包含 diego.ramos@gmail.com" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "检查该邮件是否感谢 Diego 并提及技术面试", + "check_logic": "将 diego_email 的 subject 与 body 拼接并转为小写;检查文本中是否同时包含 'thank' 和 'interview'", + "pass_condition": "邮件主题或正文中同时出现 'thank' 和 'interview'" + }, + { + "name": "Component 3", + "weight": 0.3, + "description": "检查 Slack #hiring 频道是否存在新增消息同时提及 @sara 和 @ben", + "check_logic": "对比 slack['initial_state']['messages']['hiring'] 与 slack['current_state']['messages']['hiring'],筛选出 messageId 不在 initial_state 中的 new_hiring_msgs;遍历消息内容,使用正则 @?\\bsara\\b 和 @?\\bben\\b 检查是否同时匹配 sara 和 ben", + "pass_condition": "存在一条新的 #hiring 消息,其内容同时提到 sara 和 ben" + }, + { + "name": "Component 4", + "weight": 0.2, + "description": "检查该 Slack 消息是否要求提交 scorecards 并包含相关上下文", + "check_logic": "将 reminder_msg 的 content 转为小写;检查是否包含 'scorecard',且同时包含 'greenhouse'、'end of day'、'eod' 或 'submit' 中的至少一个", + "pass_condition": "消息内容包含 'scorecard',并且包含 'greenhouse'、'end of day'、'eod' 或 'submit' 之一" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加求和,最终通过 min(total_score, 1.0) 钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接退出,REWARD 为 0.0", + "请求 Gmail 或 Slack mock 状态失败:打印 CRITICAL 并直接退出,REWARD 为 0.0", + "未找到新的 sent 邮件给 Diego:C1 失败,且导致 C2 因无候选邮件而失败", + "未找到新的 #hiring 消息同时提及 sara 和 ben:C3 失败,且导致 C4 因无提醒消息而失败", + "各组件检查中若发生异常,被捕获后打印 ERROR,该组件不得分但不中断后续检查" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 Gmail 和 Slack 的 mock 服务拉取包含 initial_state 与 current_state 的完整状态。通过对比 initial_state 与 current_state 的邮件/消息 ID,识别出本次任务新增的 Gmail 邮件(new_emails)和 Slack #hiring 消息(new_hiring_msgs)。接着按顺序执行四项检查:C1 确认新增邮件是 sent 且收件人为 diego.ramos@gmail.com;C2 在该邮件的 subject 与 body 中查找是否同时包含 'thank' 和 'interview';C3 在新增 #hiring 消息中通过正则查找是否同时提到 sara 和 ben;C4 在该消息内容中查找是否包含 'scorecard' 以及 'greenhouse'/'end of day'/'eod'/'submit' 等上下文。每通过一项即累加对应分值,最终用 min(total_score, 1.0) 将总分限制在 1.0 以内并输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. **Task ID**: recruit_followup_001 (从 docstring 中明确提取)\n2. **Domain**: mock_websites (gmail + slack) (从 docstring 中明确提取)\n3. **Summary**: 一句话概括:验证是否给候选人 Diego Ramos 发送了感谢邮件并提及技术面试,同时在 Slack #hiring 频道发送消息提醒 Sara 和 Ben 提交 Greenhouse 评分卡。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `http://28.7.186.212:8158` (Gmail mock)\n - `http://28.7.186.212:8198` (Slack mock)\n - 也可以写成 gmail_mock, slack_mock\n\n6. **scoring_components**:\n - C1 (0.30): 检查是否有 NEW sent email 给 diego.ramos@gmail.com。通过比较 current_state 和 initial_state 的 emails,找出 new_emails,然后检查 folder 是否为 'sent',to 是否包含 diego.ramos@gmail.com。\n - C2 (0.20): 检查该邮件是否感谢 Diego 并提及技术面试。检查 subject + body 中是否包含 'thank' 和 'interview'。\n - C3 (0.30): 检查是否有 NEW #hiring Slack 消息提及 @sara 和 @ben。通过比较 current_state 和 initial_state 的 messages.hiring,找出 new_hiring_msgs,检查 content 是否包含 sara 和 ben(正则匹配 @?\\bsara\\b 和 @?\\bben\\b)。\n - C4 (0.20): 检查该 Slack 消息是否要求提交 scorecards。检查 content 是否包含 'scorecard',以及是否包含 'greenhouse'、'end of day'、'eod' 或 'submit'。\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,REWARD: 0.0,sys.exit(0)\n - 获取 mock state 失败(Gmail 或 Slack):打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 没有新的发送给 Diego 的邮件:C1 失败,不得分\n - 没有新的 #hiring 消息:C3 失败,不得分\n - 如果 C1 失败,C2 自动失败(因为依赖 diego_email)\n - 如果 C3 失败,C4 自动失败(因为依赖 reminder_msg)\n - 各组件异常被捕获,打印 ERROR,但不退出,只是不得分\n\n10. **scoring_logic_explanation**: 详细中文解释执行顺序:\n - 从 /tmp/task_web_sid 读取环境会话 ID。\n - 分别向 Gmail 和 Slack 的 mock 服务发送请求,拉取 initial_state 和 current_state。\n - 对比 initial_state 和 current_state,识别出 Gmail 中新增的邮件(new_emails)和 Slack #hiring 频道中新增的消息(new_hiring_msgs)。\n - 逐项检查四个组件:C1 确认有发给 diego.ramos@gmail.com 的新 sent 邮件;C2 在该邮件主题和正文中查找 \"thank\" 和 \"interview\";C3 确认有新的 #hiring 消息同时提到 sara 和 ben;C4 在该消息中查找 \"scorecard\" 以及 \"greenhouse\"/\"end of day\"/\"eod\"/\"submit\" 等上下文。\n - 各组件通过则累加对应分数,最终用 min 钳制到 1.0 并输出。\n\n11. **confidence**: 1.0,因为代码逻辑非常清晰。\n\n现在构建 JSON。注意:\n- 不要输出 Markdown 代码块\n- 第一个字符必须是 {,最后一个必须是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- weight 填写显式分值:0.30, 0.20, 0.30, 0.20\n\n让我再仔细检查一下 C4 的代码:\n```python\nhas_context = ('greenhouse' in c) or ('end of day') in c or ('eod' in c) or ('submit' in c)\n```\n这里有一个小 bug:`('end of day') in c` 其实等价于 `'end of day' in c`,括号没问题,但逻辑是对的。不过 `('greenhouse' in c)` 和 `('submit' in c)` 的括号使用不一致,但功能上没问题。我只需要如实描述。\n\n检查 C3 的正则:`r'@?\\bsara\\b'` 和 `r'@?\\bben\\b'`,这是检查是否提到 sara 和 ben,前面可选 @ 符号。\n\n检查 C2:`has_thanks = 'thank' in text`,`has_interview = 'interview' in text`。\n\n数据源:Gmail mock 服务 (GMAIL_URL)、Slack mock 服务 (SLACK_URL)、/tmp/task_web_sid。\n\nJSON 结构确认无误。 {\"task_id\":\"recruit_followup_001\",\"domain\":\"mock_websites (gmail + slack)\",\"summary\":\"验证是否向候选人 Diego Ramos 发送了感谢并提及技术面试的新邮件,并在 Slack #hiring 频道发送了提醒 Sara 和 Ben 提交 Greenhouse 评分卡的新消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"Gmail mock 服务 (GMAIL_URL)\",\"Slack mock 服务 (SLACK_URL)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.3,\"description\":\"检查是否存在新增的已发送邮件给 diego.ramos@gmail.com\",\"check_logic\":\"对比 gmail['initial_state']['emails'] 与 gmail['current_state']['emails'],筛选出 id 不在 initial_state 中的 new_emails;遍历 new_emails,检查 e['folder'] == 'sent' 且 e['to'] 列表中包含 'diego.ramos@gmail.com'\",\"pass_condition\":\"存在一封新的 sent 邮件,其收件人包含 diego.ramos@gmail.com\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"检查该邮件是否感谢 Diego 并提及技术面试\",\"check_logic\":\"将 diego_email 的 subject 与 body 拼接并转为小写;检查文本中是否同时包含 'thank' 和 'interview'\",\"pass_condition\":\"邮件主题或正文中同时出现 'thank' 和 'interview'\"},{\"name\":\"Component 3\",\"weight\":0.3,\"description\":\"检查 Slack #hiring 频道是否存在新增消息同时提及 @sara 和 @ben\",\"check_logic\":\"对比 slack['initial_state']['messages']['hiring'] 与 slack['current_state']['messages']['hiring'],筛选出 messageId 不在 initial_state 中的 new_hiring_msgs;遍历消息内容,使用正则 @?\\\\bsara\\\\b 和 @?\\\\bben\\\\b 检查是否同时匹配 sara 和 ben\",\"pass_condition\":\"存在一条新的 #hiring 消息,其内容同时提到 sara 和 ben\"},{\"name\":\"Component 4\",\"weight\":0.2,\"description\":\"检查该 Slack 消息是否要求提交 scorecards 并包含相关上下文\",\"check_logic\":\"将 reminder_msg 的 content 转为小写;检查是否包含 'scorecard',且同时包含 'greenhouse'、'end of day'、'eod' 或 'submit' 中的至少一个\",\"pass_condition\":\"消息内容包含 'scorecard',并且包含 'greenhouse'、'end of day'、'eod' 或 'submit' 之一\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终通过 min(total_score, 1.0) 钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接退出,REWARD 为 0.0\",\"请求 Gmail 或 Slack mock 状态失败:打印 CRITICAL 并直接退出,REWARD 为 0.0\",\"未找到新的 sent 邮件给 Diego:C1 失败,且导致 C2 因无候选邮件而失败\",\"未找到新的 #hiring 消息同时提及 sara 和 ben:C3 失败,且导致 C4 因无提醒消息而失败\",\"各组件检查中若发生异常,被捕获后打印 ERROR,该组件不得分但不中断后续检查\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 Gmail 和 Slack 的 mock 服务拉取包含 initial_state 与 current_state 的完整状态。通过对比 initial_state 与 current_state 的邮件/消息 ID,识别出本次任务新增的 Gmail 邮件(new_emails)和 Slack #hiring 消息(new_hiring_msgs)。接着按顺序执行四项检查:C1 确认新增邮件是 sent 且收件人为 diego.ramos@gmail.com;C2 在该邮件的 subject 与 body 中查找是否同时包含 'thank' 和 'interview';C3 在新增 #hiring 消息中通过正则查找是否同时提到 sara 和 ben;C4 在该消息内容中查找是否包含 'scorecard' 以及 'greenhouse'/'end of day'/'eod'/'submit' 等上下文。每通过一项即累加对应分值,最终用 min(total_score, 1.0) 将总分限制在 1.0 以内并输出。\",\"confidence\":1.0}" +} diff --git a/recruit_resume_screen_004__long/_cua_gym_vm_bridge.sh b/recruit_resume_screen_004__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_resume_screen_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/recruit_resume_screen_004__long/initial_setup.py b/recruit_resume_screen_004__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d7126c1e897824669e74d4e1a70f2e4717297ca3 --- /dev/null +++ b/recruit_resume_screen_004__long/initial_setup.py @@ -0,0 +1,915 @@ +""" +Initial Setup: T08 — Greenhouse scorecard-driven onsite decisions +Task ID: recruit_resume_screen_004__long +Mocks: greenhouse_mock,gmail_mock,google_calendar_mock,slack_mock + +The agent screens candidates for the 'Senior Frontend Engineer' job (job-1). +For every ACTIVE application in the 'Onsite' stage it must read the SUBMITTED +scorecards (overallRecommendation != null) and decide: + - ADVANCE -> move application to the 'Offer' stage (no no/strong_no AND >=2 strong_yes/yes) + - REJECT -> status 'rejected', reason 'Not enough support' (any strong_no OR >=2 'no') + - LEAVE -> unchanged (otherwise: mixed/insufficient) +After ADVANCE: email Subject 'Next steps - ' AND schedule a Google + Calendar event 'Offer discussion - ' (today+3) with the + candidate's email typed in as a GUEST. +After REJECT: email Subject 'Update on your application - '. +For BOTH advance and reject: add a decision NOTE on the candidate ('Advanced to + Offer ...' / 'Rejected - Not enough support') AND pin that note. +After processing all decisions: post a one-line summary to the Slack #recruiting + channel ('Processed N onsite decisions ...') AND pin that message. +LEAVE candidates are neither moved nor emailed nor scheduled nor noted. + +HIDDEN ACCESS POINTS the agent must DISCOVER (the point of this task): + - Greenhouse stage-move and reject controls live only on the candidate's own + detail page (Move Stage / Reject buttons appear after opening the candidate). + - Calendar guests are typed into the buried "Add guests" field (the candidate + is not in the autocomplete, so the email is carried from Greenhouse/Gmail). + - Greenhouse note PINNING is a hover Pin toggle on the candidate Notes side-tab + (no visible "pin" button until you reach the Notes tab; persists as + note.isPinned). NEW hidden control. + - Slack message PINNING is behind the per-message hover "..." (More actions) + menu in #recruiting. NEW hidden control. + +Ground truth (answer key) is embedded as a hidden `_decision` dict on each +onsite application of job-1, PRECOMPUTED in Python from the visible scorecard +recommendations so the visible data and the key can never disagree. + +Observable result kept ABSENT at injection (Rule 3): + - every onsite application starts active in the Onsite stage (no advance/reject) + - gmail has NO emails whose subject starts with 'Next steps -' or + 'Update on your application -' (sent folder empty of decision mail). + - calendar has NO 'Offer discussion -' events at injection (only decoys). + - greenhouse has NO notes on the 6 onsite candidates EXCEPT the two non-decision + watermark notes already present on cand-1/cand-3 (NOT pinned; reward only + credits NEWLY-ADDED pinned notes, so the watermark can't earn the note point). + - the Slack #recruiting channel starts EMPTY (no messages, no pinned messages). +""" +import os +import shlex +import subprocess +import time +import uuid +from datetime import datetime, timedelta, timezone + +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}') + + +# ------------------------------------------------------------------ +# Time anchors (real datetime so derived fields stay self-consistent) +# ------------------------------------------------------------------ +NOW = datetime(2026, 6, 23, 16, 0, 0, tzinfo=timezone.utc) + +# The instruction PINS "today" so the agent can compute the deterministic +# offer-discussion date. These must stay in lock-step with the instruction +# text ("Today's date is Tuesday, June 23, 2026" / offer event on +# "Friday, June 26, 2026"); the reward compares the calendar event against the +# baked _decision.event_date (NOW+3), not the wall clock, so this guard is what +# keeps the stated date and the answer key from silently diverging. +assert NOW.date().isoformat() == '2026-06-23', NOW +assert (NOW + timedelta(days=3)).date().isoformat() == '2026-06-26' + + +def iso(dt): + return dt.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + + +APPLIED_AT = iso(NOW - timedelta(days=24)) +ONSITE_SINCE = NOW - timedelta(days=5) # entered onsite 5 days ago +SCORECARD_SUBMIT = iso(NOW - timedelta(days=2)) # scorecards submitted 2 days ago +SCORECARD_CREATE = iso(NOW - timedelta(days=4)) +LAST_ACTIVITY = iso(NOW - timedelta(days=2)) +DAYS_IN_ONSITE = (NOW - ONSITE_SINCE).days + + +# ================================================================== +# GREENHOUSE +# ================================================================== +GH_USERS = [ + {'id': 'user-1', 'firstName': 'Jules', 'lastName': 'Park', 'name': 'Jules Park', + 'email': 'jules.park@company.com', 'role': 'recruiter', 'avatarUrl': None, + 'department': 'People Operations', 'title': 'Senior Recruiter'}, + {'id': 'user-2', 'firstName': 'Sarah', 'lastName': 'Chen', 'name': 'Sarah Chen', + 'email': 'sarah.chen@company.com', 'role': 'recruiter', 'avatarUrl': None, + 'department': 'People Operations', 'title': 'Recruiter'}, + {'id': 'user-3', 'firstName': 'David', 'lastName': 'Kim', 'name': 'David Kim', + 'email': 'david.kim@company.com', 'role': 'hiring_manager', 'avatarUrl': None, + 'department': 'Engineering', 'title': 'VP of Engineering'}, + {'id': 'user-4', 'firstName': 'Emily', 'lastName': 'Rodriguez', 'name': 'Emily Rodriguez', + 'email': 'emily.rodriguez@company.com', 'role': 'hiring_manager', 'avatarUrl': None, + 'department': 'Design', 'title': 'Head of Design'}, + {'id': 'user-5', 'firstName': 'Marcus', 'lastName': 'Johnson', 'name': 'Marcus Johnson', + 'email': 'marcus.johnson@company.com', 'role': 'interviewer', 'avatarUrl': None, + 'department': 'Engineering', 'title': 'Staff Engineer'}, + {'id': 'user-6', 'firstName': 'Priya', 'lastName': 'Patel', 'name': 'Priya Patel', + 'email': 'priya.patel@company.com', 'role': 'interviewer', 'avatarUrl': None, + 'department': 'Engineering', 'title': 'Senior Engineer'}, + {'id': 'user-7', 'firstName': 'James', 'lastName': 'Wright', 'name': 'James Wright', + 'email': 'james.wright@company.com', 'role': 'coordinator', 'avatarUrl': None, + 'department': 'People Operations', 'title': 'Recruiting Coordinator'}, +] +GH_CURRENT_USER = GH_USERS[0] + + +def job_stages(job_id): + """Standard 8-stage frontend/eng pipeline. Index 6 = Onsite, 7 = Offer.""" + spec = [ + ('Application Review', 'application_review'), + ('Recruiter Phone Screen', 'phone_screen'), + ('Hiring Manager Screen', 'phone_screen'), + ('Technical Interview', 'interview'), + ('Take Home', 'take_home'), + ('Onsite', 'onsite'), + ('Offer', 'offer'), + ('Hired', 'hired'), + ] + return [ + {'id': f'stage-{job_id}-{i}', 'jobId': job_id, 'name': name, + 'orderIndex': i - 1, 'stageType': stype} + for i, (name, stype) in enumerate(spec, start=1) + ] + + +JOB1_STAGES = job_stages('job-1') +JOB2_STAGES = job_stages('job-2') +GH_JOB_STAGES = JOB1_STAGES + JOB2_STAGES + +# Resolve key stage ids for the target job from the data itself. +ONSITE_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'onsite') # stage-job-1-6 +OFFER_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'offer') # stage-job-1-7 + +GH_JOBS = [ + {'id': 'job-1', 'title': 'Senior Frontend Engineer', 'status': 'open', + 'departmentId': 'dept-1', 'officeId': 'office-1', + 'hiringManagerId': 'user-3', 'recruiterId': 'user-1', 'coordinatorId': 'user-7', + 'openings': 2, 'openDate': '2026-04-01', 'closeDate': None, + 'description': 'Build and own core frontend experiences in React/TypeScript.', + 'requirements': ['5+ years frontend', 'React/TypeScript', 'Strong UX sense'], + 'stages': [s['id'] for s in JOB1_STAGES], 'candidateCount': 10, + 'createdAt': '2026-04-01T09:00:00Z', 'updatedAt': iso(NOW - timedelta(days=2))}, + {'id': 'job-2', 'title': 'Product Designer', 'status': 'open', + 'departmentId': 'dept-2', 'officeId': 'office-2', + 'hiringManagerId': 'user-4', 'recruiterId': 'user-2', 'coordinatorId': 'user-7', + 'openings': 1, 'openDate': '2026-05-01', 'closeDate': None, + 'description': 'Own product design end to end for our growth surfaces.', + 'requirements': ['4+ years product design', 'Figma', 'Portfolio'], + 'stages': [s['id'] for s in JOB2_STAGES], 'candidateCount': 2, + 'createdAt': '2026-05-01T09:00:00Z', 'updatedAt': iso(NOW - timedelta(days=3))}, +] + + +# ---- Candidates --------------------------------------------------- +# Target onsite candidates (job-1): (cand_id, first, last) +ONSITE_CANDS = [ + ('cand-1', 'Alex', 'Chen'), # advance + ('cand-2', 'Bianca', 'Romero'), # advance + ('cand-3', 'Caleb', 'Idris'), # reject (strong_no) + ('cand-4', 'Dahlia', 'Novak'), # reject (>=2 'no') + ('cand-5', 'Ezra', 'Mbeki'), # leave (mixed: one 'no') + ('cand-6', 'Farida', 'Haddad'), # leave (insufficient: one submitted) +] +# Distractor candidates (NOT onsite / wrong job) +DISTRACTOR_CANDS = [ + ('cand-7', 'Greg', 'Olsen'), # job-1 Application Review + ('cand-8', 'Hana', 'Suzuki'), # job-1 Technical Interview + ('cand-9', 'Ivan', 'Petrov'), # job-1 already in Offer + ('cand-10', 'Julia', 'Mwangi'), # job-1 rejected (Technical Interview) + ('cand-11', 'Kofi', 'Mensah'), # job-2 Onsite (WRONG JOB) + ('cand-12', 'Lena', 'Brandt'), # job-2 Recruiter Phone Screen +] + +ALL_CANDS = ONSITE_CANDS + DISTRACTOR_CANDS +GH_CANDIDATES = [ + {'id': cid, 'firstName': fn, 'lastName': ln, 'name': f'{fn} {ln}', + 'email': f'{fn.lower()}.{ln.lower()}@example.com', 'phone': '+1-555-0{:03d}'.format(i), + 'location': 'Remote', 'currentCompany': 'Acme', 'currentTitle': 'Engineer', + 'resumeUrl': None, 'linkedinUrl': None, 'source': 'applied', + 'referrerId': None, 'tags': [], + 'createdAt': APPLIED_AT, 'updatedAt': LAST_ACTIVITY} + for i, (cid, fn, ln) in enumerate(ALL_CANDS, start=1) +] +NAME_BY_CAND = {cid: f'{fn} {ln}' for (cid, fn, ln) in ALL_CANDS} + + +# ---- Decision rule (mirrors the task instruction) ----------------- +def decide(submitted_recs): + """submitted_recs: list of overallRecommendation strings (submitted only).""" + has_strong_no = any(r == 'strong_no' for r in submitted_recs) + num_no = sum(1 for r in submitted_recs if r == 'no') + num_yes = sum(1 for r in submitted_recs if r in ('strong_yes', 'yes')) + if has_strong_no or num_no >= 2: + return 'reject' + if num_no == 0 and num_yes >= 2: + return 'advance' + return 'leave' + + +REJECT_REASON = 'Not enough support' + +# Onsite scorecard plans: cand_id -> list of (interviewerId, overallRecommendation) +# overallRecommendation None == pending (unsubmitted) -> MUST be ignored by reward. +ONSITE_SCORECARD_PLAN = { + 'cand-1': [('user-5', 'strong_yes'), ('user-6', 'yes'), ('user-3', 'yes')], + 'cand-2': [('user-5', 'strong_yes'), ('user-6', 'strong_yes'), ('user-3', None)], + 'cand-3': [('user-5', 'yes'), ('user-6', 'strong_no'), ('user-3', 'yes')], + 'cand-4': [('user-5', 'no'), ('user-6', 'no'), ('user-3', 'yes')], + 'cand-5': [('user-5', 'yes'), ('user-6', 'no')], + 'cand-6': [('user-5', 'strong_yes'), ('user-6', None)], +} +# Sanity: the 6 plans must yield exactly advance,advance,reject,reject,leave,leave +EXPECTED_ACTIONS = { + 'cand-1': 'advance', 'cand-2': 'advance', + 'cand-3': 'reject', 'cand-4': 'reject', + 'cand-5': 'leave', 'cand-6': 'leave', +} + + +def attr(name, rating, note): + return {'name': name, 'rating': rating, 'note': note} + + +REC_ATTRS = { + 'strong_yes': [attr('Technical', 4, 'Excellent depth and code quality.'), + attr('Communication', 4, 'Crisp, structured answers.')], + 'yes': [attr('Technical', 3, 'Solid, would hire.'), + attr('Communication', 3, 'Clear and collaborative.')], + 'no_opinion': [attr('Technical', 2, 'Hard to read from this session.')], + 'no': [attr('Technical', 1, 'Notable gaps on the system-design round.'), + attr('Communication', 2, 'Some hand-waving under pressure.')], + 'strong_no': [attr('Technical', 0, 'Failed core fundamentals; serious concerns.'), + attr('Communication', 1, 'Defensive when challenged.')], +} + +# Build applications + scorecards for the 6 target onsite candidates. +GH_APPLICATIONS = [] +GH_SCORECARDS = [] +GH_INTERVIEWS = [] +_sc_counter = 0 +_int_counter = 0 + +for idx, (cid, fn, ln) in enumerate(ONSITE_CANDS, start=1): + app_id = f'app-{idx}' + plan = ONSITE_SCORECARD_PLAN[cid] + submitted = [rec for (_iv, rec) in plan if rec is not None] + action = decide(submitted) + assert action == EXPECTED_ACTIONS[cid], ( + f'{cid}: computed {action} but expected {EXPECTED_ACTIONS[cid]} (plan {plan})' + ) + + # Hidden answer-key field (per EMBEDDING CONTRACT). target_stage_id/email_subject + # are null for 'leave'. reject_reason added for the reject reason sub-rubric. + # ADVANCE decisions also carry a Google Calendar answer key: an offer-discussion + # event whose guest is the candidate's email (typed into the buried guest field). + cand_name = NAME_BY_CAND[cid] + cand_email = f'{fn.lower()}.{ln.lower()}@example.com' + if action == 'advance': + decision = {'action': 'advance', 'candidate_name': cand_name, + 'candidate_email': cand_email, + 'target_stage_id': OFFER_STAGE_ID, 'target_status': 'active', + 'email_subject': f'Next steps - {cand_name}', + 'reject_reason': None, + 'event_title': f'Offer discussion - {cand_name}', + 'event_date': iso(NOW + timedelta(days=3))[:10], + 'guest_email': cand_email, + # Decision NOTE answer key (pinned via the hidden Notes-tab toggle). + 'note_required': True, + 'note_keywords': ['advanc', 'offer']} + elif action == 'reject': + decision = {'action': 'reject', 'candidate_name': cand_name, + 'candidate_email': cand_email, + 'target_stage_id': None, 'target_status': 'rejected', + 'email_subject': f'Update on your application - {cand_name}', + 'reject_reason': REJECT_REASON, + 'event_title': None, 'event_date': None, 'guest_email': None, + 'note_required': True, + 'note_keywords': ['reject', 'not enough support']} + else: # leave + decision = {'action': 'leave', 'candidate_name': cand_name, + 'candidate_email': cand_email, + 'target_stage_id': None, 'target_status': 'active', + 'email_subject': None, 'reject_reason': None, + 'event_title': None, 'event_date': None, 'guest_email': None, + 'note_required': False, 'note_keywords': []} + + GH_APPLICATIONS.append({ + 'id': app_id, 'candidateId': cid, 'jobId': 'job-1', + 'currentStageId': ONSITE_STAGE_ID, 'status': 'active', + 'appliedAt': APPLIED_AT, 'rejectedAt': None, 'rejectionReason': None, + 'hiredAt': None, 'lastActivityAt': LAST_ACTIVITY, 'source': 'applied', + 'creditedTo': None, 'recruiterId': 'user-1', 'coordinatorId': 'user-7', + 'actionRequired': 'needs_decision', 'daysInCurrentStage': DAYS_IN_ONSITE, + '_decision': decision, + }) + + # One completed onsite interview per candidate (realism). + _int_counter += 1 + GH_INTERVIEWS.append({ + 'id': f'int-{_int_counter}', 'applicationId': app_id, 'stageId': ONSITE_STAGE_ID, + 'interviewerIds': [iv for (iv, _rec) in plan], 'scheduledAt': SCORECARD_CREATE, + 'duration': 240, 'location': 'Onsite — SF HQ', 'status': 'completed', + 'meetingUrl': '', 'notes': 'Full onsite loop.'}) + + # Scorecards (submitted + pending) for this application. + for (interviewer, rec) in plan: + _sc_counter += 1 + GH_SCORECARDS.append({ + 'id': f'sc-{_sc_counter}', 'applicationId': app_id, + 'interviewerId': interviewer, 'stageId': ONSITE_STAGE_ID, + 'overallRecommendation': rec, + 'attributes': REC_ATTRS.get(rec, []) if rec is not None else [], + 'submittedAt': SCORECARD_SUBMIT if rec is not None else None, + 'createdAt': SCORECARD_CREATE, + 'notes': '' if rec is not None else 'Pending — not yet submitted.'}) + +# ---- Distractor applications (NO _decision; must remain unchanged) ---- +DISTRACTOR_APPS = [ + # id, cand, job, stageId, status, rejectedAt, rejectionReason, actionRequired + ('app-7', 'cand-7', 'job-1', 'stage-job-1-1', 'active', None, None, 'needs_decision'), + ('app-8', 'cand-8', 'job-1', 'stage-job-1-4', 'active', None, None, 'needs_scorecard'), + ('app-9', 'cand-9', 'job-1', 'stage-job-1-7', 'active', None, None, None), + ('app-10', 'cand-10', 'job-1', 'stage-job-1-4', 'rejected', + iso(NOW - timedelta(days=9)), 'Lacking technical skills', None), + # WRONG JOB: onsite for Product Designer (job-2). Agent must NOT touch it. + ('app-11', 'cand-11', 'job-2', 'stage-job-2-6', 'active', None, None, 'needs_decision'), + ('app-12', 'cand-12', 'job-2', 'stage-job-2-2', 'active', None, None, 'needs_scheduling'), +] +for (aid, cid, jid, stage, status, rej_at, rej_reason, action_req) in DISTRACTOR_APPS: + GH_APPLICATIONS.append({ + 'id': aid, 'candidateId': cid, 'jobId': jid, + 'currentStageId': stage, 'status': status, + 'appliedAt': APPLIED_AT, 'rejectedAt': rej_at, 'rejectionReason': rej_reason, + 'hiredAt': None, 'lastActivityAt': LAST_ACTIVITY, 'source': 'applied', + 'creditedTo': None, + 'recruiterId': 'user-1' if jid == 'job-1' else 'user-2', + 'coordinatorId': 'user-7', + 'actionRequired': action_req, 'daysInCurrentStage': 3}) + +# A few scorecards on the wrong-job onsite distractor (app-11) so it looks like a +# real "ready" candidate and tempts a careless agent. No _decision -> not graded. +for j, (interviewer, rec) in enumerate([('user-4', 'strong_yes'), ('user-6', 'yes')], start=1): + _sc_counter += 1 + GH_SCORECARDS.append({ + 'id': f'sc-{_sc_counter}', 'applicationId': 'app-11', + 'interviewerId': interviewer, 'stageId': 'stage-job-2-6', + 'overallRecommendation': rec, 'attributes': REC_ATTRS[rec], + 'submittedAt': SCORECARD_SUBMIT, 'createdAt': SCORECARD_CREATE, 'notes': ''}) + +# One offer record for the candidate already in the Offer stage (app-9). +GH_OFFERS = [ + {'id': 'offer-1', 'applicationId': 'app-9', 'jobId': 'job-1', + 'status': 'pending_approval', 'salary': 185000, 'currency': 'USD', + 'startDate': '2026-08-01', 'expiresAt': iso(NOW + timedelta(days=14)), + 'createdBy': 'user-1', + 'approvers': [{'userId': 'user-3', 'status': 'pending', 'respondedAt': None}], + 'createdAt': LAST_ACTIVITY, 'updatedAt': LAST_ACTIVITY}, +] + +GREENHOUSE_STATE = { + 'currentUser': GH_CURRENT_USER, + 'users': GH_USERS, + 'departments': [ + {'id': 'dept-1', 'name': 'Engineering', 'parentId': None}, + {'id': 'dept-2', 'name': 'Design', 'parentId': None}, + {'id': 'dept-6', 'name': 'People Operations', 'parentId': None}, + ], + 'offices': [ + {'id': 'office-1', 'name': 'San Francisco HQ', 'location': 'San Francisco, CA'}, + {'id': 'office-2', 'name': 'New York', 'location': 'New York, NY'}, + {'id': 'office-3', 'name': 'Remote', 'location': 'Remote'}, + ], + 'sources': [{'id': 'src-1', 'name': 'Applied'}, + {'id': 'src-2', 'name': 'Referral'}], + 'rejectionReasons': [ + {'id': 'rr-1', 'name': 'Lacking technical skills'}, + {'id': 'rr-2', 'name': 'Not enough support'}, + {'id': 'rr-3', 'name': 'Culture/values misalignment'}, + ], + 'jobs': GH_JOBS, + 'jobStages': GH_JOB_STAGES, + 'candidates': GH_CANDIDATES, + 'applications': GH_APPLICATIONS, + 'scorecards': GH_SCORECARDS, + 'interviews': GH_INTERVIEWS, + 'offers': GH_OFFERS, + 'notes': [ + {'id': 'note-1', 'candidateId': 'cand-1', 'authorId': 'user-1', + 'body': 'Strong onsite loop, panel was enthusiastic.', 'visibility': 'public', + 'isPinned': False, 'createdAt': LAST_ACTIVITY, 'updatedAt': LAST_ACTIVITY}, + {'id': 'note-2', 'candidateId': 'cand-3', 'authorId': 'user-6', + 'body': 'One interviewer had serious reservations.', 'visibility': 'public', + 'isPinned': False, 'createdAt': LAST_ACTIVITY, 'updatedAt': LAST_ACTIVITY}, + ], + 'activityFeed': [], + 'notifications': [ + {'id': 'notif-1', 'type': 'scorecard_due', 'title': 'Scorecards in', + 'message': 'Onsite scorecards submitted for Senior Frontend Engineer.', + 'isRead': False, 'link': '/jobs/job-1', 'createdAt': SCORECARD_SUBMIT}, + ], + 'ui': {'searchQuery': '', 'activeJobId': 'job-1', 'activeCandidateId': None, + 'modals': {'addCandidate': False, 'createJob': False, + 'scheduleInterview': False, 'rejectCandidate': False, + 'moveStage': False, 'search': False, 'notifications': False}}, +} + + +# ================================================================== +# GMAIL — recruiter inbox. NO decision emails present (Rule 3). +# ================================================================== +def gmail_email(i, sender_name, sender_email, subject, body, folder='inbox', + read=False, days_ago=1): + ts = iso(NOW - timedelta(days=days_ago)) + return { + 'id': f'email_{i}', 'threadId': f'thread_{i}', + 'from': {'name': sender_name, 'email': sender_email, 'avatar': ''}, + 'to': [{'name': 'Jules Park', 'email': 'jules.park@company.com'}], + 'cc': [], 'bcc': [], 'subject': subject, 'body': body, 'snippet': body[:80], + 'timestamp': ts, 'read': read, 'starred': False, 'important': False, + 'labels': [], 'category': 'primary', 'folder': folder, 'attachments': [], + } + + +GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Jules Park', + 'email': 'jules.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1'}, + 'emails': [ + # Decoys only — none start with 'Next steps -' / 'Update on your application -'. + gmail_email(1, 'James Wright', 'james.wright@company.com', + 'Onsite logistics for Senior Frontend Engineer', + 'All onsite loops wrapped this week. Scorecards are in Greenhouse ' + 'for your review whenever you are ready. Let me know on next steps.', + days_ago=2), + gmail_email(2, 'Alex Chen', 'alex.chen@example.com', + 'Thank you for the onsite', + 'Thanks for hosting me onsite — I really enjoyed meeting the team ' + 'and am excited about the role. Happy to answer anything else.', + days_ago=1), + gmail_email(3, 'David Kim', 'david.kim@company.com', + 'Debrief notes', + 'Posted my thoughts on the candidates in the scorecards. Defer to ' + 'the written recommendations for the final call.', days_ago=1), + gmail_email(4, 'Workday Notifications', 'no-reply@workday.com', + 'Weekly hiring summary', + 'Your pipelines have new activity. Log in to review.', + folder='inbox', read=True, days_ago=3), + ], + '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': [], + 'settings': { + 'density': 'default', 'undoSend': 10, + 'signature': '--\nJules Park\nSenior Recruiter, Acme Corp', + 'replyBehavior': 'Reply', 'language': 'English (US)', + }, +} + + +# ================================================================== +# GOOGLE CALENDAR — recruiter calendar. NO 'Offer discussion -' events +# at injection (Rule 3); two decoys for realism. Advance candidates need a +# follow-up event with the candidate email typed into the guest field. +# ================================================================== +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': 'Jules Park', + 'email': 'jules.park@company.com', + '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': 'Recruiting', 'color': 'bg-green-500', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}, + ], + 'events': [ + cal_event('evt_sync', 'c2', 'Hiring Sync', + '2026-06-24T15:00:00.000Z', '2026-06-24T15:30:00.000Z', + 'Zoom', 'Weekly hiring sync', ['david.kim@company.com']), + cal_event('evt_panel', 'c2', 'Panel Debrief', + '2026-06-25T17:00:00.000Z', '2026-06-25T18:00:00.000Z', + 'SF HQ', 'Onsite panel debrief', []), + ], + 'view': 'week', + 'currentDate': '2026-06-23T00:00:00.000Z', + 'sidebarOpen': True, + 'settings': {'weekStart': 0, 'defaultDuration': 60}, + 'today': '2026-06-23', +} + + +# ================================================================== +# SLACK — recruiting workspace. The agent posts a one-line summary of the +# onsite decisions to #recruiting and PINS it (pin is behind the per-message +# hover "..." menu). #recruiting starts EMPTY (Rule 3); other channels carry +# watermark chatter so the agent must find the right channel. Shape copied +# from the canonical greenhouse+calendar+gmail+slack reference (ccf892d6). +# ================================================================== +def slack_user(uid, full, disp, email, rnd, title='', status='online'): + return {'userId': uid, 'fullName': full, 'displayName': disp, 'email': email, + 'avatar': f'https://picsum.photos/200/200?random={rnd}', 'title': title, + 'status': status, 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'} + + +def slack_channel(cid, name, desc, topic, members, created_by, starred=False, unread=0): + return {'channelId': cid, 'name': name, 'description': desc, 'topic': topic, + 'isPrivate': False, 'isStarred': starred, 'members': members, + 'createdBy': created_by, 'createdAt': '2026-04-01T08:00:00Z', + 'pinnedMessages': [], 'unreadCount': unread} + + +def slack_msg(mid, sender, content, ts, reactions=None): + return {'messageId': mid, 'senderId': sender, 'content': content, + 'timestamp': ts, 'reactions': reactions or [], 'isEdited': False, + 'threadId': None, 'attachments': []} + + +SLACK_USERS = [ + slack_user('user_1', 'Jules Park', 'Jules', 'jules.park@company.com', 1, + 'Senior Recruiter'), + slack_user('user_2', 'Sarah Chen', 'Sarah', 'sarah.chen@company.com', 2, + 'Recruiter', status='away'), + slack_user('user_3', 'David Kim', 'David', 'david.kim@company.com', 3, + 'VP of Engineering'), + slack_user('user_4', 'James Wright', 'James', 'james.wright@company.com', 4, + 'Recruiting Coordinator'), +] + +SLACK_STATE = { + 'currentUser': SLACK_USERS[0], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'users': SLACK_USERS, + 'channels': [ + slack_channel('general', 'general', 'Company-wide announcements', + 'Welcome to Acme Corp!', ['user_1', 'user_2', 'user_3', 'user_4'], + 'user_3', starred=True), + slack_channel('random', 'random', 'Non-work banter', 'Coffee and memes', + ['user_1', 'user_2', 'user_3', 'user_4'], 'user_2'), + slack_channel('eng-hiring', 'eng-hiring', 'Engineering hiring coordination', + 'Pipeline syncs, debriefs', ['user_1', 'user_3', 'user_4'], 'user_3'), + # TARGET channel — starts empty (Rule 3). + slack_channel('recruiting', 'recruiting', + 'Recruiting team channel — onsite decisions, candidate updates', + 'Post one line per onsite decision batch', + ['user_1', 'user_2', 'user_4'], 'user_1', starred=True), + ], + 'messages': { + 'general': [ + slack_msg('m_g_1', 'user_3', + 'Senior Frontend onsite loops wrapped — scorecards are in.', + '2026-06-22T15:30:00Z'), + slack_msg('m_g_2', 'user_4', + 'Reminder: debrief notes due before any offer goes out.', + '2026-06-22T17:02:00Z', + reactions=[{'emoji': '✅', 'users': ['user_1', 'user_2']}]), + ], + 'random': [ + slack_msg('m_r_1', 'user_2', 'Espresso machine is making sad noises again.', + '2026-06-22T13:45:00Z'), + slack_msg('m_r_2', 'user_4', 'Filed a ticket. ETA: eventually.', + '2026-06-22T13:48:00Z'), + ], + 'eng-hiring': [ + slack_msg('m_e_1', 'user_3', + 'Frontend panel finished all six onsites. Over to you for decisions.', + '2026-06-22T13:00:00Z', + reactions=[{'emoji': '\U0001f44d', 'users': ['user_1']}]), + slack_msg('m_e_2', 'user_1', 'On it — will process decisions today.', + '2026-06-22T13:04:00Z'), + ], + 'recruiting': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', + 'displayDensity': 'comfortable', 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': [], +} + + +# ================================================================== +# Inject + verify + launch +# ================================================================== +APP_STATES = [ + ('http://28.7.184.198:8146', GREENHOUSE_STATE), # greenhouse_mock + ('http://28.7.184.198:8138', GMAIL_STATE), # gmail_mock + ('http://28.7.184.198:8141', GOOGLE_CALENDAR_STATE), # google_calendar_mock + ('http://28.7.184.198:8178', SLACK_STATE), # slack_mock +] + +# --- internal consistency assertions (fail fast at build time) --- +_onsite_decisions = [a['_decision']['action'] for a in GH_APPLICATIONS + if a.get('jobId') == 'job-1' and a['currentStageId'] == ONSITE_STAGE_ID + and '_decision' in a] +assert _onsite_decisions.count('advance') == 2, _onsite_decisions +assert _onsite_decisions.count('reject') == 2, _onsite_decisions +assert _onsite_decisions.count('leave') == 2, _onsite_decisions +_dec_subjects = {a['_decision']['email_subject'] for a in GH_APPLICATIONS if '_decision' in a} +assert not any( + (e['subject'].startswith('Next steps -') or + e['subject'].startswith('Update on your application -')) + for e in GMAIL_STATE['emails']), 'decision email leaked into initial gmail' +# advance/reject decisions require a pinned note; leave does not. +assert all(a['_decision']['note_required'] for a in GH_APPLICATIONS + if '_decision' in a and a['_decision']['action'] in ('advance', 'reject')) +assert all(not a['_decision']['note_required'] for a in GH_APPLICATIONS + if '_decision' in a and a['_decision']['action'] == 'leave') +# Rule 3: no PINNED note exists on any onsite candidate at injection, and the +# #recruiting channel starts empty (so both new components are absent -> 0). +_onsite_cands = {a['candidateId'] for a in GH_APPLICATIONS + if '_decision' in a} +assert not any(n.get('isPinned') and n.get('candidateId') in _onsite_cands + for n in GREENHOUSE_STATE['notes']), 'pinned note leaked at injection' +assert SLACK_STATE['messages']['recruiting'] == [], '#recruiting must start empty' +assert all(ch['pinnedMessages'] == [] for ch in SLACK_STATE['channels']), \ + 'no pinned slack message at injection' +print('Self-check OK:', _onsite_decisions) + + +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/recruit_resume_screen_004__long/reward.py b/recruit_resume_screen_004__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..784ee0404848196d500d23b5d86e31033048da07 --- /dev/null +++ b/recruit_resume_screen_004__long/reward.py @@ -0,0 +1,746 @@ +""" +Reward Script: T08 — Greenhouse scorecard-driven onsite decisions +Task ID: recruit_resume_screen_004__long +Mocks: greenhouse_mock,gmail_mock,google_calendar_mock,slack_mock + +The agent screens the ACTIVE 'Onsite' applications of job-1 ('Senior Frontend +Engineer') and decides advance / reject / leave from the SUBMITTED scorecards, +then sends a per-decision email, (for advances) schedules an offer-discussion +calendar event, adds + PINS a decision note on the candidate, and posts + +PINS a one-line summary to Slack #recruiting. Ground truth is a hidden +`_decision` field on each onsite job-1 application in initial_state (the reward +reads it there — it is the contract). + +Positive components are scored ONLY over the actions the agent must actively take +(advance/reject), so a do-nothing agent scores exactly 0. 'leave' candidates and +distractor applications appear ONLY as penalties. + 0.24 advance/reject moved correctly (advance->Offer stage; reject->status rejected) + 0.20 advance/reject decision email present (exact subject) + 0.08 reject reason == _decision.reject_reason on rejected targets + 0.16 advance -> 'Offer discussion - ' calendar event on the target date + 0.12 that event lists the candidate's email as a GUEST (hidden, buried field) + 0.10 per advance/reject: a NEWLY-ADDED note on the candidate that is PINNED and + mentions the decision (hidden: Notes-tab hover Pin toggle) + 0.05 Slack #recruiting summary message posted (must contain 'onsite' or 'decision' AND a digit; channel empty at injection) + 0.05 that #recruiting message is PINNED (hidden: message hover "..." menu) — the pinned message itself must satisfy the summary keyword check + -0.15 PENALTY: 'leave' candidate moved/rejected/emailed + -0.10 PENALTY: non-target distractor application changed from injection +""" +import copy +from datetime import datetime +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 = {'greenhouse': 'http://28.7.184.198:8146', '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 _email_text(email): + if not isinstance(email, dict): + return str(email) + + to = email.get('to', '') + if isinstance(to, list): + to = ' '.join( + (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x) + for x in to + ) + elif isinstance(to, dict): + to = to.get('name') or to.get('email') or str(to) + + to_recips = email.get('toRecipients', []) + if isinstance(to_recips, list): + to_recips = ' '.join( + (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x) + for x in to_recips + ) + else: + to_recips = '' + + return f"{to} {to_recips} {email.get('subject', '')} {email.get('body', '')}" + + +def _slack_channel_messages(slack_state, channel_name): + out = [] + if not isinstance(slack_state, dict): + return out + + channels = slack_state.get('channels', []) + msg_map = slack_state.get('messages', {}) + for ch in channels: + if not isinstance(ch, dict) or norm(ch.get('name')) != norm(channel_name): + continue + + if isinstance(ch.get('messages'), list): + out.extend(ch.get('messages')) + + if isinstance(msg_map, dict): + cid = ch.get('channelId') or ch.get('id') + if isinstance(msg_map.get(cid), list): + out.extend(msg_map.get(cid)) + name_key = ch.get('name') + if isinstance(msg_map.get(name_key), list): + out.extend(msg_map.get(name_key)) + + return out + + +def _slack_msg_text(msg): + if not isinstance(msg, dict): + return str(msg) + + parts = [msg.get('text'), msg.get('content'), msg.get('message')] + nested_message = msg.get('message') + if isinstance(nested_message, dict): + parts.append(nested_message.get('text')) + parts.append(nested_message.get('content')) + + nested_content = msg.get('content') + if isinstance(nested_content, dict): + parts.append(nested_content.get('text')) + parts.append(nested_content.get('content')) + + return ' '.join(str(x) for x in parts if x is not None) + + +def _gmail_sent_emails(gmail_state): + out = [] + if not isinstance(gmail_state, dict): + return out + + for e in gmail_state.get('emails', []): + if not isinstance(e, dict): + continue + folder = norm(e.get('folder')) + if folder in ('sent', 'sentitems', 'sent items'): + out.append(e) + continue + if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'): + out.append(e) + + if out: + return out + + for key in ('sent', 'sentEmails', 'outbox'): + items = gmail_state.get(key, []) + if isinstance(items, list): + out.extend(x for x in items if isinstance(x, dict)) + return out + + +def _parse(t): + if not t: + return None + s = str(t).strip() + # datetime.fromisoformat does not accept trailing 'Z' directly. + if s.endswith('Z'): + s = s[:-1] + '+00:00' + try: + return datetime.fromisoformat(s) + except Exception: + return None + + +def _overlaps(events): + spans = [] + for e in events or []: + if not isinstance(e, dict): + continue + st = _parse(e.get('start')) + en = _parse(e.get('end')) + if st and en: + # Convert to naive datetime for safe comparison + if st.tzinfo is not None: + st_naive = st.replace(tzinfo=None) + else: + st_naive = st + if en.tzinfo is not None: + en_naive = en.replace(tzinfo=None) + else: + en_naive = en + + if en_naive > st_naive: + spans.append((st_naive, en_naive)) + spans.sort(key=lambda x: x[0]) + bad = 0 + for i in range(1, len(spans)): + if spans[i][0] < spans[i - 1][1]: + bad += 1 + return bad + + +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 === +TARGET_JOB = 'job-1' + + +def _job_stage_id_by_type(state, job_id, stage_type): + """Resolve a stage id from jobStages by (jobId, stageType) — do not hardcode.""" + for s in (state or {}).get('jobStages', []) or []: + if (isinstance(s, dict) and s.get('jobId') == job_id + and norm(s.get('stageType')) == norm(stage_type)): + return s.get('id') + return None + + +def _current_emails(gmail_payload): + state = gmail_payload.get('current_state') or {} + return [e for e in (state.get('emails') or []) if isinstance(e, dict)] + + +def _subject_present(emails, subject): + """True iff some current email has an (exact, normalized) matching subject.""" + target = norm(subject) + if not target: + return False + return any(norm(e.get('subject')) == target for e in emails) + + +def _cal_date_key(s): + """Local (UTC+8) calendar date 'YYYY-MM-DD' for an event start, robust to the + datetime-local -> toISOString() tz shift the calendar mock performs.""" + if not s: + return None + t = str(s).strip() + raw_date = t.split('T', 1)[0] if 'T' in t else t[:10] + dt = _parse(t) + if dt is None: + return raw_date + from datetime import timezone, timedelta + tzp8 = timezone(timedelta(hours=8)) + if dt.tzinfo is None: + return raw_date + return dt.astimezone(tzp8).date().isoformat() + + +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 + + +def reward(go): + gh = go('greenhouse') + gh_initial = gh.get('initial_state') or {} + gh_current = gh.get('current_state') or {} + gmail = go('gmail') + + # Resolve the onsite stage of the target job from the data (not hardcoded). + onsite_stage_id = _job_stage_id_by_type(gh_initial, TARGET_JOB, 'onsite') + + apps_i = [a for a in (gh_initial.get('applications') or []) if isinstance(a, dict)] + apps_c = {a.get('id'): a for a in (gh_current.get('applications') or []) + if isinstance(a, dict)} + + emails = _current_emails(gmail) + cur_events = go('google_calendar').get('current_state', {}).get('events', []) or [] + + # Target set: onsite job-1 applications carrying the hidden answer key. + targets = [ + a for a in apps_i + if a.get('jobId') == TARGET_JOB + and a.get('currentStageId') == onsite_stage_id + and isinstance(a.get('_decision'), dict) + ] + # Partition by the action each REQUIRES. Positive credit is given only for + # actions the agent must actively take (advance/reject); 'leave' candidates + # and distractors are scored as PENALTIES so do-nothing == 0. + act_rows = [a for a in targets if norm(a['_decision'].get('action')) in ('advance', 'reject')] + advance_rows = [a for a in targets if norm(a['_decision'].get('action')) == 'advance'] + reject_rows = [a for a in targets if norm(a['_decision'].get('action')) == 'reject'] + leave_rows = [a for a in targets if norm(a['_decision'].get('action')) == 'leave'] + + # --- Component 1 (0.30): advance/reject applications moved correctly --- + move_ok = 0 + for a in act_rows: + dec = a['_decision'] + action = norm(dec.get('action')) + cur = apps_c.get(a.get('id')) if isinstance(apps_c.get(a.get('id')), dict) else {} + if action == 'advance': + ok = norm(cur.get('currentStageId')) == norm(dec.get('target_stage_id')) + else: # reject + ok = norm(cur.get('status')) == norm(dec.get('target_status') or 'rejected') + move_ok += int(bool(ok)) + move_frac = frac(move_ok, len(act_rows)) if act_rows else 1.0 + + # --- Component 2 (0.25): decision emails for advance/reject --- + email_ok = 0 + for a in act_rows: + email_ok += int(_subject_present(emails, a['_decision'].get('email_subject'))) + email_frac = frac(email_ok, len(act_rows)) if act_rows else 1.0 + + # --- Component 3 (0.10): reject reason on rejected targets --- + reason_ok = 0 + for a in reject_rows: + want = norm(a['_decision'].get('reject_reason') or '') + cur = apps_c.get(a.get('id')) if isinstance(apps_c.get(a.get('id')), dict) else {} + if want and norm(cur.get('rejectionReason')) == want: + reason_ok += 1 + reason_frac = frac(reason_ok, len(reject_rows)) if reject_rows else 1.0 + + # --- Component 4 (0.20): advance -> 'Offer discussion' calendar event on the date --- + event_ok = 0 + for a in advance_rows: + dec = a['_decision'] + want_title = norm(dec.get('event_title')) + want_date = dec.get('event_date') + if want_title and any( + norm(ev.get('title')) == want_title and _cal_date_key(ev.get('start')) == want_date + for ev in cur_events if isinstance(ev, dict) + ): + event_ok += 1 + event_frac = frac(event_ok, len(advance_rows)) if advance_rows else 1.0 + + # --- Component 5 (0.12): that event lists the candidate email as a guest --- + guest_ok = 0 + for a in advance_rows: + dec = a['_decision'] + want_title = norm(dec.get('event_title')) + want_guest = norm(dec.get('guest_email')) + if want_title and want_guest and any( + norm(ev.get('title')) == want_title and want_guest in _event_guests(ev) + for ev in cur_events if isinstance(ev, dict) + ): + guest_ok += 1 + guest_frac = frac(guest_ok, len(advance_rows)) if advance_rows else 1.0 + + # --- Component 6 (0.10): NEWLY-ADDED pinned decision note per advance/reject --- + # Hidden control: the per-note Pin toggle lives on the candidate Notes side-tab. + # Credit only notes that (a) are absent at injection (diff by id), (b) are + # pinned now, and (c) mention the decision (keyword). Watermark notes present + # at injection (note-1/note-2, unpinned) therefore cannot earn this point. + notes_i = [n for n in (gh_initial.get('notes') or []) if isinstance(n, dict)] + notes_c = [n for n in (gh_current.get('notes') or []) if isinstance(n, dict)] + initial_note_ids = {n.get('id') for n in notes_i} + note_ok = 0 + for a in act_rows: + dec = a['_decision'] + if not dec.get('note_required'): + continue + cand_id = a.get('candidateId') + kws = [norm(k) for k in (dec.get('note_keywords') or []) if k] + hit = False + for n in notes_c: + if n.get('candidateId') != cand_id: + continue + if n.get('id') in initial_note_ids: # not newly added + continue + if not n.get('isPinned'): # must be pinned (hidden toggle) + continue + body = norm(n.get('body')) + if kws and any(k in body for k in kws): + hit = True + break + note_ok += int(hit) + note_frac = frac(note_ok, len(act_rows)) if act_rows else 1.0 + + # --- Component 7 (0.05 post + 0.05 pin): Slack #recruiting summary, pinned --- + # Tightened to prevent free credit for arbitrary chatter: the message must + # look like an actual onsite-decisions summary (contains 'onsite' or 'decision' + # AND at least one digit, i.e. the count). And `pin_ok` requires that the + # pinned message ITSELF satisfies the same keyword check, not just any + # non-empty pinned message in the channel. + slack = go('slack') + scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + rec_msgs = _slack_channel_messages(scur, 'recruiting') + rec_ch = None + for ch in (scur.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == 'recruiting': + rec_ch = ch + break + pinned_ids = (rec_ch.get('pinnedMessages') or []) if isinstance(rec_ch, dict) else [] + + def _is_summary(msg): + text = (_slack_msg_text(msg) or '').strip() + if not text: + return False + return has_text(text, 'onsite', 'decision') and bool(re.search(r'\d', text)) + + post_ok = any(_is_summary(m) for m in rec_msgs if isinstance(m, dict)) + # The pinned message must itself look like the summary (not just any pinned + # non-empty message in the channel). + pinned_msgs = [m for m in rec_msgs + if isinstance(m, dict) + and (m.get('messageId') or m.get('id')) in set(pinned_ids)] + pin_ok = post_ok and any(_is_summary(m) for m in pinned_msgs) + post_frac = 1.0 if post_ok else 0.0 + pin_frac = 1.0 if pin_ok else 0.0 + + # --- Penalty: 'leave' candidates that were moved/rejected/emailed/scheduled --- + leave_leak = 0 + for a in leave_rows: + dec = a['_decision'] + cur = apps_c.get(a.get('id')) if isinstance(apps_c.get(a.get('id')), dict) else {} + moved = (norm(cur.get('currentStageId')) != norm(a.get('currentStageId')) + or norm(cur.get('status')) != 'active') + name = dec.get('candidate_name') or '' + emailed = (_subject_present(emails, f'Next steps - {name}') + or _subject_present(emails, f'Update on your application - {name}')) + if moved or emailed: + leave_leak += 1 + leave_leak_frac = frac(leave_leak, len(leave_rows)) if leave_rows else 0.0 + + # --- Penalty: non-target distractor applications changed from injection --- + distractors = [a for a in apps_i if not isinstance(a.get('_decision'), dict)] + distract_leak = 0 + for a in distractors: + cur = apps_c.get(a.get('id')) + if not isinstance(cur, dict): + continue + if (norm(cur.get('currentStageId')) != norm(a.get('currentStageId')) + or norm(cur.get('status')) != norm(a.get('status')) + or norm(cur.get('rejectionReason')) != norm(a.get('rejectionReason'))): + distract_leak += 1 + distract_leak_frac = frac(distract_leak, len(distractors)) if distractors else 0.0 + + s_move = 0.24 * move_frac + s_email = 0.20 * email_frac + s_reason = 0.08 * reason_frac + s_event = 0.16 * event_frac + s_guest = 0.12 * guest_frac + s_note = 0.10 * note_frac + s_post = 0.05 * post_frac + s_pin = 0.05 * pin_frac + positive = s_move + s_email + s_reason + s_event + s_guest + s_note + s_post + s_pin + penalty = 0.15 * leave_leak_frac + 0.10 * distract_leak_frac + score = clamp01(positive - penalty) + + print( + 'DEBUG_b69c97fd ' + f'targets={len(targets)} act={len(act_rows)} adv={len(advance_rows)} ' + f'rej={len(reject_rows)} leave={len(leave_rows)} onsite_stage={onsite_stage_id} ' + f'move={move_ok}/{len(act_rows)} email={email_ok}/{len(act_rows)} ' + f'reason={reason_ok}/{len(reject_rows)} event={event_ok}/{len(advance_rows)} ' + f'guest={guest_ok}/{len(advance_rows)} note={note_ok}/{len(act_rows)} ' + f'slack_post={post_ok} slack_pin={pin_ok} ' + f'leave_leak={leave_leak}/{len(leave_rows)} distract_leak={distract_leak}/{len(distractors)} ' + f's_move={round(s_move, 4)} s_email={round(s_email, 4)} s_reason={round(s_reason, 4)} ' + f's_event={round(s_event, 4)} s_guest={round(s_guest, 4)} s_note={round(s_note, 4)} ' + f's_post={round(s_post, 4)} s_pin={round(s_pin, 4)} ' + f'penalty={round(penalty, 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)}') diff --git a/sdr_cold_outreach_001/_cua_gym_vm_bridge.sh b/sdr_cold_outreach_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/sdr_cold_outreach_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/sdr_cold_outreach_001/initial_setup.py b/sdr_cold_outreach_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b4c9aff5911776ca5b967e6babddc367a6410c --- /dev/null +++ b/sdr_cold_outreach_001/initial_setup.py @@ -0,0 +1,574 @@ +# --- 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: SDR cold outreach to a brand-new lead (Marcus Bell @ Cedar Grove Health). +Task ID: sdr_cold_outreach_001 +Domain: mock_websites +Mocks: gmail_mock, hubspot_mock + +PRE-TASK STATE (negative constraints enforced): + - HubSpot Marcus Bell exists, lifecycleStage 'lead', leadStatus 'new' (NOT 'attempted'). + - A near-duplicate distractor 'Marcus Bellamy' (leadStatus 'connected') at a different company. + - NO notes and NO tasks associated with Marcus Bell. + - Gmail mailbox is the SDR's (Alex Morgan). Inbox has unrelated mail; drafts empty; + NO sent/draft email addressed to marcus.bell@cedargrovehealth.com. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +GMAIL_URL = 'http://28.7.184.198:8138' +HUBSPOT_URL = 'http://28.7.184.198:8150' + +sid = str(uuid.uuid4()) + +# --- §1.5 Egress proxy helper --- +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 + raise RuntimeError('No working route to mock servers; direct and proxy attempts failed') + + +PROXY = resolve_proxy(f'{HUBSPOT_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + +# --- Persist sid for golden_patch.py and reward.py --- +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +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 +def build_gmail_state(): + return { + "user": { + "userId": "u1", + "username": "Alex Morgan", + "email": "alex.morgan@northwindcloud.com", + "avatar": "https://i.pravatar.cc/150?u=alex-morgan", + }, + "emails": [ + { + "id": "email_pipeline", + "threadId": "thread_pipeline", + "from": {"name": "Priya Raman", "email": "priya.raman@northwindcloud.com"}, + "to": [{"name": "Alex Morgan", "email": "alex.morgan@northwindcloud.com"}], + "cc": [], + "bcc": [], + "subject": "Q3 outbound targets for the healthcare vertical", + "body": ( + "

    Hi Alex,

    " + "

    Sharing the refreshed list of healthcare accounts we want to prioritize " + "for outbound this quarter. A few brand-new leads landed in the CRM overnight, " + "so please start working them today. Let me know if you need help with " + "messaging.

    " + "

    Thanks,
    Priya

    " + ), + "timestamp": "2026-06-24T08:10:00Z", + "read": False, + "starred": False, + "important": True, + "labels": ["l1"], + "category": "primary", + "folder": "inbox", + "attachments": [], + }, + { + "id": "email_webinar", + "threadId": "thread_webinar", + "from": {"name": "SaaS Growth Weekly", "email": "hello@saasgrowthweekly.com"}, + "to": [{"name": "Alex Morgan", "email": "alex.morgan@northwindcloud.com"}], + "cc": [], + "bcc": [], + "subject": "[Webinar] 7 cold email frameworks that actually book meetings", + "body": ( + "

    Struggling to get replies? Join our free webinar Thursday where we break " + "down seven proven cold email frameworks for SDRs. Save your seat below.

    " + ), + "timestamp": "2026-06-24T06:45:00Z", + "read": False, + "starred": False, + "important": False, + "labels": [], + "category": "promotions", + "folder": "inbox", + "attachments": [], + }, + { + "id": "email_standup", + "threadId": "thread_standup", + "from": {"name": "Northwind Sales Ops", "email": "salesops@northwindcloud.com"}, + "to": [{"name": "Alex Morgan", "email": "alex.morgan@northwindcloud.com"}], + "cc": [], + "bcc": [], + "subject": "Reminder: SDR pipeline standup moved to 9:30am", + "body": ( + "

    Hi team,

    " + "

    A quick note that today's SDR pipeline standup has been moved to 9:30am " + "in the Aspen room. Come ready to share your top three accounts and any " + "blockers.

    " + ), + "timestamp": "2026-06-23T17:20:00Z", + "read": True, + "starred": False, + "important": False, + "labels": [], + "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": [], + } + + +# ====================================================================== +# HUBSPOT INITIAL STATE — Marcus Bell (new lead) + Marcus Bellamy distractor +# ====================================================================== +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}, +} + + +def build_hubspot_state(): + companies = [ + { + "id": "comp_cedar", "name": "Cedar Grove Health", "domain": "cedargrovehealth.com", + "industry": "Healthcare", "phone": "+1 (555) 247-8810", "city": "Portland", + "state": "OR", "country": "United States", "numberOfEmployees": 480, + "annualRevenue": 62000000, "lifecycleStage": "lead", "owner": "Alex Morgan", + "description": "Regional network of outpatient clinics and urgent-care centers.", + "createDate": "2026-06-23T17:42:00Z", + }, + { + "id": "comp_summit", "name": "Summit Wellness Group", "domain": "summitwellness.com", + "industry": "Healthcare", "phone": "+1 (555) 661-2204", "city": "Denver", + "state": "CO", "country": "United States", "numberOfEmployees": 210, + "annualRevenue": 28000000, "lifecycleStage": "opportunity", "owner": "Alex Morgan", + "description": "Chain of preventive-care and physical therapy clinics.", + "createDate": "2026-04-11T10:15:00Z", + }, + { + "id": "comp_brightpath", "name": "BrightPath Diagnostics", "domain": "brightpathdx.com", + "industry": "Healthcare", "phone": "+1 (555) 902-3380", "city": "Austin", + "state": "TX", "country": "United States", "numberOfEmployees": 95, + "annualRevenue": 14500000, "lifecycleStage": "mql", "owner": "Alex Morgan", + "description": "Lab diagnostics startup expanding into the Southwest.", + "createDate": "2026-05-02T09:30:00Z", + }, + { + "id": "comp_acme", "name": "Acme Retail Co", "domain": "acmeretail.com", + "industry": "Other", "phone": "+1 (555) 118-7700", "city": "Chicago", + "state": "IL", "country": "United States", "numberOfEmployees": 1200, + "annualRevenue": 210000000, "lifecycleStage": "customer", "owner": "Jordan Lee", + "description": "National specialty retail chain.", + "createDate": "2025-11-20T13:00:00Z", + }, + ] + + contacts = [ + # --- TARGET: brand-new lead, leadStatus 'new', no notes/tasks --- + { + "id": "c_marcus_bell", "firstName": "Marcus", "lastName": "Bell", + "email": "marcus.bell@cedargrovehealth.com", "phone": "+1 (555) 247-8842", + "jobTitle": "Director of Operations", "companyId": "comp_cedar", + "lifecycleStage": "lead", "leadStatus": "new", "owner": "Alex Morgan", + "city": "Portland", "state": "OR", "country": "United States", + "createDate": "2026-06-23T17:42:00Z", "lastActivityDate": "2026-06-23T17:42:00Z", + "timeline": [], + }, + # --- DISTRACTOR: near-duplicate name, different company, leadStatus 'connected' --- + { + "id": "c_marcus_bellamy", "firstName": "Marcus", "lastName": "Bellamy", + "email": "m.bellamy@summitwellness.com", "phone": "+1 (555) 661-2299", + "jobTitle": "VP of Operations", "companyId": "comp_summit", + "lifecycleStage": "opportunity", "leadStatus": "connected", "owner": "Alex Morgan", + "city": "Denver", "state": "CO", "country": "United States", + "createDate": "2026-04-12T11:05:00Z", "lastActivityDate": "2026-06-18T15:30:00Z", + "timeline": [], + }, + # --- realistic filler contacts --- + { + "id": "c_nadia", "firstName": "Nadia", "lastName": "Okonkwo", + "email": "nadia.okonkwo@brightpathdx.com", "phone": "+1 (555) 902-3391", + "jobTitle": "Chief Operating Officer", "companyId": "comp_brightpath", + "lifecycleStage": "mql", "leadStatus": "open", "owner": "Alex Morgan", + "city": "Austin", "state": "TX", "country": "United States", + "createDate": "2026-05-02T09:31:00Z", "lastActivityDate": "2026-06-15T12:00:00Z", + "timeline": [], + }, + { + "id": "c_dwyer", "firstName": "Tom", "lastName": "Dwyer", + "email": "tom.dwyer@summitwellness.com", "phone": "+1 (555) 661-2210", + "jobTitle": "Facilities Manager", "companyId": "comp_summit", + "lifecycleStage": "lead", "leadStatus": "in_progress", "owner": "Alex Morgan", + "city": "Denver", "state": "CO", "country": "United States", + "createDate": "2026-05-20T14:20:00Z", "lastActivityDate": "2026-06-12T09:45:00Z", + "timeline": [], + }, + { + "id": "c_garcia", "firstName": "Elena", "lastName": "Garcia", + "email": "elena.garcia@acmeretail.com", "phone": "+1 (555) 118-7712", + "jobTitle": "Director of Procurement", "companyId": "comp_acme", + "lifecycleStage": "customer", "leadStatus": "open_deal", "owner": "Jordan Lee", + "city": "Chicago", "state": "IL", "country": "United States", + "createDate": "2025-12-01T10:00:00Z", "lastActivityDate": "2026-06-10T16:10:00Z", + "timeline": [], + }, + ] + + # Notes exist for OTHER contacts only — NONE for Marcus Bell. + notes = [ + { + "id": "note_summit_1", + "body": "Connected with Marcus Bellamy on a discovery call; they're evaluating " + "scheduling tools for Q3. Send the ROI one-pager.", + "associatedType": "contact", "associatedId": "c_marcus_bellamy", + "createdBy": "Alex Morgan", "createDate": "2026-06-18T15:35:00Z", + }, + { + "id": "note_brightpath_1", + "body": "Nadia mentioned procurement freeze lifts in July. Re-engage early next month.", + "associatedType": "contact", "associatedId": "c_nadia", + "createdBy": "Alex Morgan", "createDate": "2026-06-15T12:05:00Z", + }, + ] + + # Tasks exist for OTHER contacts only — NONE for Marcus Bell. + tasks = [ + { + "id": "task_bellamy_followup", "title": "Send ROI one-pager to Marcus Bellamy", + "type": "email", "status": "not_started", "priority": "medium", + "dueDate": "2026-06-25T09:00:00Z", + "notes": "Follow up after discovery call with Summit Wellness.", + "owner": "Alex Morgan", "contactId": "c_marcus_bellamy", + "companyId": "comp_summit", "dealId": None, + "createDate": "2026-06-18T15:36:00Z", "completedDate": None, + }, + { + "id": "task_nadia_call", "title": "Call Nadia Okonkwo about July re-engagement", + "type": "call", "status": "not_started", "priority": "low", + "dueDate": "2026-07-02T16:00:00Z", + "notes": "Procurement freeze lifts in July.", + "owner": "Alex Morgan", "contactId": "c_nadia", + "companyId": "comp_brightpath", "dealId": None, + "createDate": "2026-06-15T12:06:00Z", "completedDate": None, + }, + ] + + return { + "contacts": contacts, + "companies": companies, + "deals": [], + "tickets": [], + "tasks": tasks, + "notes": notes, + "templates": [ + { + "id": "tmp1", "name": "Cold Outreach — Operations Leaders", + "subject": "Quick idea for {{company_name}}", + "body": "Hi {{first_name}},\n\nI work with operations teams in healthcare to " + "cut manual scheduling overhead.\n\nWorth a quick chat?\n\nAlex", + "folder": "Sales", "createdBy": "Alex Morgan", + "createDate": "2026-03-01T10:00:00Z", "timesUsed": 23, + }, + ], + "meetings": [], + "forms": [], + "dealStages": DEAL_STAGES, + "ticketStatuses": TICKET_STATUSES, + "appState": { + "sidebarOpen": True, + "currentUser": {"name": "Alex Morgan", "email": "alex.morgan@northwindcloud.com", "avatar": None}, + }, + } + + +# ====================================================================== +# Inject state into both mocks (same sid) +# ====================================================================== +mocks = { + GMAIL_URL: build_gmail_state(), + HUBSPOT_URL: build_hubspot_state(), +} + +for url, state in mocks.items(): + resp = requests.post( + f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + proxies=PROXIES, + ) + assert resp.status_code == 200, f'State injection failed for {url}: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10, proxies=PROXIES).json() + assert go['initial_state'] is not None, f'initial_state is None after injection for {url}' + print(f'State injected & verified: {url} sid={sid}') + +# ====================================================================== +# Launch browsers (HubSpot + Gmail), Gmail focused last +# ====================================================================== +chrome_proxy = f'--proxy-server={PROXY}' if PROXY else '' +launch_gui(f'google-chrome "{HUBSPOT_URL}/?sid={sid}"', delay_sec=2.0) +launch_gui(f'google-chrome "{GMAIL_URL}/?sid={sid}"', delay_sec=2.0) +wait_mocks_loaded() +print(f'GUI_READY: launched HubSpot and Gmail with sid={sid}') diff --git a/sdr_cold_outreach_001/reward.py b/sdr_cold_outreach_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4670df9539d6cbd6432d06eec6c1dd1520694b --- /dev/null +++ b/sdr_cold_outreach_001/reward.py @@ -0,0 +1,417 @@ +# --- 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: SDR cold outreach to Marcus Bell (Lead-To-Meeting pipeline) +Task ID: sdr_cold_outreach_001 +Domain: mock_websites (multi-mock: gmail_mock + hubspot_mock) + +Scoring rubric (total 1.0): + C1 (0.25) GMAIL — new SENT email addressed to marcus.bell@cedargrovehealth.com + with a non-empty subject and a non-empty body. [programmatic] + C2 (0.20) GMAIL — the outreach body speaks to his operations role and is concise + (mentions operations + Marcus/Cedar Grove, ~2-6 sentences). [programmatic] + C3 (0.20) HUBSPOT— Marcus Bell's contact leadStatus is 'attempted' (changed from 'new'), + and the near-duplicate 'Marcus Bellamy' distractor is untouched + (still 'connected'). [programmatic] + C4 (0.15) HUBSPOT— a note associated to Marcus Bell's contact recording the outreach. [programmatic] + C5 (0.20) HUBSPOT— a follow-up task (type 'email', status 'not_started', + dueDate the upcoming Friday in local time, or today if + the runtime local date is Friday) + associated to Marcus Bell. [programmatic] + +All 5 components are programmatic (100%). The email-content requirement is verified with +concrete contains/count checks (the preferred approach over LLM for checkable criteria), +which also makes the reward deterministic and independent of LLM-judge availability. + +Each component is anchored to a task-introduced CHANGE, so it FAILS on initial_env and +PASSES on golden_env. No pre-existing property is scored. +""" + +import json +import sys + +from datetime import date, datetime, timedelta +import os +import re +import requests + +# --------------------------------------------------------------------------- +# 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) + +GMAIL_URL = 'http://28.7.184.198:8138' +HUBSPOT_URL = 'http://28.7.184.198:8150' + +TARGET_EMAIL = 'marcus.bell@cedargrovehealth.com' +DISTRACTOR_EMAIL = 'm.bellamy@summitwellness.com' + + +def upcoming_friday(anchor=None): + """Return the upcoming Friday in local time, or today if today is Friday.""" + today = anchor or date.today() + return today + timedelta(days=(4 - today.weekday()) % 7) + + +TARGET_FRIDAY = upcoming_friday() + + +def parse_calendar_date(value): + """Extract a calendar date from common date/datetime formats.""" + if value is None: + return None + if isinstance(value, datetime): + return value.date() + if isinstance(value, date): + return value + if isinstance(value, (int, float)): + try: + timestamp = value / 1000 if abs(value) > 10_000_000_000 else value + return datetime.fromtimestamp(timestamp).date() + except (OverflowError, OSError, ValueError): + return None + + raw = str(value).strip() + if not raw: + return None + + iso_candidate = raw.replace('Z', '+00:00') + try: + return datetime.fromisoformat(iso_candidate).date() + except ValueError: + pass + + for fmt in ( + '%Y-%m-%d', '%Y/%m/%d', + '%m/%d/%Y', '%m-%d-%Y', + '%A, %B %d, %Y', '%a, %b %d, %Y', + '%B %d, %Y', '%b %d, %Y', + ): + try: + return datetime.strptime(raw, fmt).date() + except ValueError: + continue + + match = re.search(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})', raw) + if match: + year, month, day = map(int, match.groups()) + try: + return date(year, month, day) + except ValueError: + return None + + match = re.search(r'\b(\d{1,2})[-/](\d{1,2})[-/](\d{4})\b', raw) + if match: + month, day, year = map(int, match.groups()) + try: + return date(year, month, day) + except ValueError: + return None + + return None + + +def same_calendar_date(value, expected): + actual = parse_calendar_date(value) + return actual is not None and ( + actual.year == expected.year + and actual.month == expected.month + and actual.day == expected.day + ) + + +def normalized_text(value): + text = re.sub(r'<[^>]+>', ' ', str(value or '')) + text = re.sub(r'[^a-z0-9]+', ' ', text.lower()) + return re.sub(r'\s+', ' ', text).strip() + + +def enum_key(value): + return re.sub(r'[^a-z0-9]+', '', str(value or '').lower()) + + +def contains_phrase(text, phrases): + norm = normalized_text(text) + return any(normalized_text(phrase) in norm for phrase in phrases) + +# --------------------------------------------------------------------------- +# Egress proxy helper — direct access is expected for current mock hosts. +# --------------------------------------------------------------------------- +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'{HUBSPOT_URL}/go?sid=conn-probe') +PROXIES = 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: + gmail = fetch_state(GMAIL_URL) + hubspot = fetch_state(HUBSPOT_URL) +except Exception as e: + print(f'CRITICAL: Cannot fetch mock state: {e}') + print('REWARD: 0.0') + sys.exit(0) + +gmail_init = gmail.get('initial_state') or {} +gmail_cur = gmail.get('current_state') or {} +hub_init = hubspot.get('initial_state') or {} +hub_cur = hubspot.get('current_state') or {} + + +def find_contact_by_email(state, email): + for c in state.get('contacts', []) or []: + if (c.get('email') or '').strip().lower() == email.lower(): + return c + return None + + +def verify_task(): + total = 0.0 + + # ---- Resolve Marcus Bell's contact id from the CURRENT hubspot state ---- + marcus = find_contact_by_email(hub_cur, TARGET_EMAIL) + marcus_id = marcus.get('id') if marcus else None + + sent_to_marcus = None + sent_body_text = '' # plain-text version of the outreach body (set in C1) + + # ===================================================================== + # Component 1 (0.25) — GMAIL: a new SENT email to Marcus Bell + # ===================================================================== + sent_to_marcus = None + try: + def sent_emails_to(state): + out = [] + for e in state.get('emails', []) or []: + if (e.get('folder') or '').lower() != 'sent': + continue + recips = [(r.get('email') or '').strip().lower() + for r in (e.get('to') or [])] + if TARGET_EMAIL.lower() in recips: + out.append(e) + return out + + init_sent = sent_emails_to(gmail_init) + cur_sent = sent_emails_to(gmail_cur) + # task-introduced: there must be MORE sent emails to Marcus than before + if len(cur_sent) > len(init_sent): + cand = cur_sent[-1] + subj = (cand.get('subject') or '').strip() + # body may be HTML; strip tags for emptiness/length checks + import re as _re + body_text = _re.sub(r'<[^>]+>', ' ', cand.get('body') or '') + body_text = _re.sub(r'\s+', ' ', body_text).strip() + if subj and body_text: + sent_to_marcus = cand + sent_body_text = body_text + print(f'PASS: C1 — new sent email to {TARGET_EMAIL} with subject ' + f'{subj!r} and non-empty body (0.25 pts)') + total += 0.25 + else: + print(f'FAIL: C1 — sent email found but subject/body empty ' + f'(subj={subj!r}, body_len={len(body_text)})') + else: + print(f'FAIL: C1 — no new sent email addressed to {TARGET_EMAIL} ' + f'(init={len(init_sent)}, cur={len(cur_sent)})') + except Exception as e: + print(f'ERROR: C1 — {e}') + + # ===================================================================== + # Component 2 (0.20) — GMAIL: the outreach body speaks to his operations + # role and is concise. Verified programmatically: + # (a) mentions operations / his role (keyword), AND + # (b) references Marcus and/or Cedar Grove Health, AND + # (c) is concise — between 1 and 6 sentences in the body. + # This is a checkable criterion, so a programmatic check is preferred + # over an LLM judge. + # ===================================================================== + try: + if sent_to_marcus is not None and sent_body_text: + mentions_ops = contains_phrase( + sent_body_text, + ( + 'operation', 'operational', 'ops', 'logistics', + 'coordination', 'workflow', 'scheduling', 'patient flow', + 'care delivery', 'clinic operations', + ), + ) + mentions_target = contains_phrase( + sent_body_text, + ('marcus', 'cedar grove', 'cedargrove', 'cedar grove health'), + ) + # count sentences using terminal punctuation + import re as _re2 + sentences = [s for s in _re2.split(r'[.!?]+', sent_body_text) if s.strip()] + n_sent = len(sentences) + concise = 1 <= n_sent <= 6 + if mentions_ops and mentions_target and concise: + print(f'PASS: C2 — outreach speaks to operations role and is concise ' + f'({n_sent} sentences) (0.20 pts)') + total += 0.20 + else: + print(f'FAIL: C2 — ops_keyword={mentions_ops}, target_ref={mentions_target}, ' + f'sentences={n_sent} (need ops keyword + Marcus/Cedar Grove ref + 1-6 sentences)') + else: + print('FAIL: C2 — no qualifying outreach email body to evaluate') + except Exception as e: + print(f'ERROR: C2 — {e}') + + # ===================================================================== + # Component 3 (0.20) — HUBSPOT: Marcus Bell leadStatus 'new' -> 'attempted' + # and distractor Marcus Bellamy unchanged. + # ===================================================================== + try: + if marcus is None: + print(f'FAIL: C3 — no contact with email {TARGET_EMAIL} in current state') + else: + status = enum_key(marcus.get('leadStatus')) + # distractor must remain 'connected' + distractor = find_contact_by_email(hub_cur, DISTRACTOR_EMAIL) + distractor_ok = distractor is not None and \ + enum_key(distractor.get('leadStatus')) == 'connected' + if status == 'attempted' and distractor_ok: + print('PASS: C3 — Marcus Bell leadStatus=attempted; ' + 'Marcus Bellamy still connected (0.20 pts)') + total += 0.20 + elif status == 'attempted' and not distractor_ok: + print('FAIL: C3 — Marcus Bell is attempted but distractor Marcus Bellamy ' + f'was altered (distractor leadStatus=' + f'{(distractor or {}).get("leadStatus")!r})') + else: + print(f'FAIL: C3 — Marcus Bell leadStatus=' + f'{marcus.get("leadStatus")!r} (expected "attempted")') + except Exception as e: + print(f'ERROR: C3 — {e}') + + # ===================================================================== + # Component 4 (0.15) — HUBSPOT: note recording the outreach, associated + # to Marcus Bell's contact. + # ===================================================================== + try: + if marcus_id is None: + print('FAIL: C4 — cannot resolve Marcus Bell contact id for note check') + else: + init_note_ids = {n.get('id') for n in (hub_init.get('notes') or [])} + matched = False + for n in hub_cur.get('notes', []) or []: + if (n.get('associatedType') or '').lower() != 'contact': + continue + if n.get('associatedId') != marcus_id: + continue + # must be a note that did not already exist for him + if n.get('id') in init_note_ids: + continue + body = n.get('body') or '' + # body should record that an outreach/email was sent + if contains_phrase( + body, + ( + 'outreach', 'reach out', 'reached out', 'cold email', + 'email', 'emailed', 'first touch', 'sent', 'contacted', + 'attempted contact', 'attempted to reach', 'initial note', + ), + ): + matched = True + print(f'PASS: C4 — outreach note associated to Marcus Bell ' + f'(note id={n.get("id")}) (0.15 pts)') + total += 0.15 + break + if not matched: + print('FAIL: C4 — no new note associated to Marcus Bell recording the outreach') + except Exception as e: + print(f'ERROR: C4 — {e}') + + # ===================================================================== + # Component 5 (0.20) — HUBSPOT: follow-up task for Marcus Bell + # type='email', status='not_started', dueDate the upcoming Friday in + # local time, or today if today is Friday, associated to Marcus Bell's + # contact. + # ===================================================================== + try: + if marcus_id is None: + print('FAIL: C5 — cannot resolve Marcus Bell contact id for task check') + else: + init_task_ids = {t.get('id') for t in (hub_init.get('tasks') or [])} + matched = False + for t in hub_cur.get('tasks', []) or []: + if t.get('contactId') != marcus_id: + continue + if t.get('id') in init_task_ids: + continue + ttype = enum_key(t.get('type')) + tstatus = enum_key(t.get('status')) + due = (t.get('dueDate') or '') + due_ok = same_calendar_date(due, TARGET_FRIDAY) + if ttype == 'email' and tstatus == 'notstarted' and due_ok: + matched = True + print(f'PASS: C5 — follow-up email task for Marcus Bell, ' + f'not_started, due {due} (expected ' + f'{TARGET_FRIDAY.isoformat()}) (0.20 pts)') + total += 0.20 + break + if not matched: + # provide diagnostic on closest candidate + cands = [t for t in (hub_cur.get('tasks') or []) + if t.get('contactId') == marcus_id + and t.get('id') not in init_task_ids] + print(f'FAIL: C5 — no new email/not_started task due ' + f'{TARGET_FRIDAY.isoformat()} for Marcus Bell. ' + f'New tasks for him: ' + f'{[(t.get("type"), t.get("status"), t.get("dueDate")) for t in cands]}') + except Exception as e: + print(f'ERROR: C5 — {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/sdr_cold_outreach_001/reward_label.json b/sdr_cold_outreach_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..ccd2b0b435ffc6ef9917f65f287ccd44f6f4ac82 --- /dev/null +++ b/sdr_cold_outreach_001/reward_label.json @@ -0,0 +1,69 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/sdr_cold_outreach_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-03 21:50:26", + "label": { + "task_id": "sdr_cold_outreach_001", + "domain": "mock_websites", + "summary": "验证 SDR 向 Marcus Bell 发送冷外联邮件,并在 HubSpot 中更新其线索状态为 attempted、添加外联备注及创建周五截止的 email 跟进任务。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "gmail_mock (http://28.7.186.212:8158)", + "hubspot_mock (http://28.7.186.212:8170)" + ], + "scoring_components": [ + { + "name": "C1", + "weight": 0.25, + "description": "检查 Gmail 的 Sent 文件夹中是否出现了新发送给 Marcus Bell 的邮件,且主题和正文均非空。", + "check_logic": "分别统计初始状态 gmail_init 与当前状态 gmail_cur 中 folder 为 'sent' 且收件人包含 TARGET_EMAIL 的邮件数量;若 cur_sent 数量大于 init_sent,则取最新邮件 cand,去除 HTML 标签并归一化空白后检查 subject 和 body_text 是否均非空。", + "pass_condition": "当前 sent 邮件数严格大于初始 sent 邮件数,且最新邮件的 subject 与 body_text(去标签后)均非空。" + }, + { + "name": "C2", + "weight": 0.2, + "description": "检查邮件正文是否针对 Marcus Bell 的运营角色展开,并提及 Marcus 或 Cedar Grove Health,且篇幅简洁。", + "check_logic": "基于 C1 获取的 sent_body_text,使用 contains_phrase 检查是否包含运营关键词(operation, operational, ops, logistics 等);是否提及目标对象关键词(marcus, cedar grove 等);使用正则 [.!?]+ 分割正文统计句子数,检查句子数是否在 1 到 6 之间(含)。", + "pass_condition": "同时满足:包含至少一个运营相关关键词、提及 Marcus 或 Cedar Grove Health、句子数在 1-6 句之间。" + }, + { + "name": "C3", + "weight": 0.2, + "description": "检查 HubSpot 中 Marcus Bell 的 leadStatus 是否由 new 变为 attempted,且干扰联系人 Marcus Bellamy 未被改动。", + "check_logic": "在当前 hubspot 状态中通过 TARGET_EMAIL 查找 Marcus Bell,使用 enum_key 规范化后检查 leadStatus 是否等于 'attempted';同时通过 DISTRACTOR_EMAIL 查找 Marcus Bellamy,检查其 leadStatus 是否仍为 'connected'。", + "pass_condition": "Marcus Bell 的 leadStatus 为 'attempted',且 Marcus Bellamy 的 leadStatus 保持为 'connected'。" + }, + { + "name": "C4", + "weight": 0.15, + "description": "检查是否为 Marcus Bell 新增了一条记录此次外联活动的备注(note)。", + "check_logic": "遍历 hub_cur 中的 notes,筛选 associatedType 为 'contact'、associatedId 等于 marcus_id 且 id 不在 hub_init 初始备注集合中的新备注;使用 contains_phrase 检查备注 body 是否包含 outreach/email 相关关键词(如 outreach, email, contacted, sent 等)。", + "pass_condition": "存在一条新的、关联到 Marcus Bell 的备注,且其正文包含外联或邮件相关关键词。" + }, + { + "name": "C5", + "weight": 0.2, + "description": "检查是否为 Marcus Bell 创建了一个新的 email 跟进任务,状态为未开始,且截止日期为即将到来的周五(若当天为周五则为今天)。", + "check_logic": "遍历 hub_cur 中的 tasks,筛选 contactId 等于 marcus_id 且 id 不在 hub_init 初始任务集合中的新任务;检查 enum_key(type) 为 'email',enum_key(status) 为 'notstarted',并使用 same_calendar_date 比较 dueDate 与 TARGET_FRIDAY(upcoming_friday() 返回的日期)。", + "pass_condition": "存在新的任务,其类型为 'email'、状态为 'not_started'、截止日期等于即将到来的周五(或今天若今天是周五),且关联到 Marcus Bell。" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数直接累加,最终通过 round(min(total, 1.0), 4) 计算总分,即相加后钳制到 1.0 上限并四舍五入保留四位小数。", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并直接退出,REWARD 为 0.0。", + "请求 gmail_mock 或 hubspot_mock 状态失败:打印 CRITICAL 并直接退出,REWARD 为 0.0。", + "C1 失败:当前 sent 邮件数未增加,或最新邮件主题/正文为空。", + "C2 失败:邮件正文缺少运营关键词、未提及 Marcus/Cedar Grove,或句子数不在 1-6 范围内。", + "C3 失败:Marcus Bell 的 leadStatus 不是 attempted,或干扰项 Marcus Bellamy 的 leadStatus 被改动。", + "C4 失败:未找到关联到 Marcus Bell 的新备注,或备注正文不包含外联相关关键词。", + "C5 失败:未找到关联到 Marcus Bell 的新任务,或任务类型/状态/截止日期不匹配。" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识;若失败则直接返回 0.0。随后通过 HTTP 请求分别拉取 gmail_mock 和 hubspot_mock 的初始状态与当前状态;若拉取失败也直接返回 0.0。接着在当前 hubspot 状态中解析 Marcus Bell 的联系人及其 id,供后续组件使用。评分按顺序执行五个组件:C1 验证 Gmail Sent 中新增了一封发给 marcus.bell@cedargrovehealth.com 且主题和正文均非空的邮件;C2 在 C1 通过的基础上,进一步检查邮件正文是否包含运营角色关键词、是否提及 Marcus 或 Cedar Grove Health,且句子数在 1-6 之间;C3 检查 HubSpot 中 Marcus Bell 的 leadStatus 变为 'attempted',同时确保干扰联系人 Marcus Bellamy 的状态未被修改;C4 检查是否为 Marcus Bell 新增了一条记录外联的备注;C5 检查是否为 Marcus Bell 新增了一个类型为 email、状态为 not_started、截止日期为即将到来的周五的跟进任务。每个组件独立判断,通过则累加对应分值,失败或异常则该组件得 0 分但不中断后续检查。最终汇总各组件得分,钳制在 1.0 以内并四舍五入后输出 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。我需要仔细阅读源码,提取所有必要信息。\n\n首先,让我分析文件内容:\n\n1. **Task ID**: 从 docstring 中可以看到 \"Task ID: sdr_cold_outreach_002\"\n2. **Domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock: gmail_mock + hubspot_mock)\"\n3. **Summary**: 这是一个 SDR 冷外联任务,给 Marcus Bell 发送邮件并在 HubSpot 中更新状态、添加备注和跟进任务。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `gmail_mock` (通过 http://28.7.186.212:8158)\n - `hubspot_mock` (通过 http://28.7.186.212:8170)\n\n6. **Scoring components**:\n - C1 (0.25): GMAIL - 新发送的邮件给 marcus.bell@cedargrovehealth.com,非空主题和正文\n - C2 (0.20): GMAIL - 邮件正文提到运营角色,提到 Marcus/Cedar Grove,1-6句话\n - C3 (0.20): HUBSPOT - Marcus Bell 的 leadStatus 从 'new' 变为 'attempted',且干扰项 Marcus Bellamy 保持 'connected'\n - C4 (0.15): HUBSPOT - 给 Marcus Bell 添加了记录外联的备注\n - C5 (0.20): HUBSPOT - 给 Marcus Bell 添加了跟进任务,类型 'email',状态 'not_started',截止日期为即将到来的周五(或今天如果是周五)\n\n7. **Score aggregation**: 各组件分数相加,最后取 min(total, 1.0) 并四舍五入到4位小数。\n\n8. **Failure modes**:\n - 无法读取 /tmp/task_web_sid -> 退出,0.0\n - 无法获取 mock 状态 -> 退出,0.0\n - 各组件检查失败会打印 FAIL 但不退出,只是不得分\n - 没有新邮件、邮件主题/正文为空、leadStatus 不对、备注不存在、任务不存在等\n\n9. **Scoring logic explanation**: 需要详细描述执行顺序:\n - 读取 sid\n - 解析代理\n - 获取 gmail 和 hubspot 的初始和当前状态\n - 查找 Marcus Bell 联系人\n - C1: 检查当前 sent 文件夹中发给目标邮箱的邮件是否比初始状态多,且最新邮件有非空主题和正文\n - C2: 检查邮件正文是否包含运营关键词、是否提到 Marcus/Cedar Grove、句子数是否在1-6之间\n - C3: 检查 Marcus Bell 的 leadStatus 是否为 'attempted',且干扰项 Marcus Bellamy 的 leadStatus 是否仍为 'connected'\n - C4: 检查是否有新的备注关联到 Marcus Bell,且备注内容包含外联相关关键词\n - C5: 检查是否有新的任务关联到 Marcus Bell,类型为 email,状态为 not_started,截止日期为即将到来的周五\n - 汇总分数并输出\n\n10. **Confidence**: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON。注意:\n- 不要输出 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- weight 使用代码中显式给出的分值\n\n让我详细整理每个组件:\n\nComponent 1:\n- name: C1\n- weight: 0.25\n- description: 检查 Gmail 中是否有新发送给 Marcus Bell 的邮件,且主题和正文非空\n- check_logic: 比较当前状态与初始状态中 sent 文件夹发给 TARGET_EMAIL 的邮件数量;若 cur_sent > init_sent,取最新邮件,检查 subject 和 body_text(去除 HTML 标签后)是否非空\n- pass_condition: 当前 sent 邮件数大于初始数,且最新邮件有非空主题和非空正文\n\nComponent 2:\n- name: C2\n- weight: 0.20\n- description: 检查邮件正文是否针对其运营角色且简洁\n- check_logic: 使用 contains_phrase 检查正文是否包含运营关键词(operation, operational, ops 等);是否提到 Marcus 或 Cedar Grove;使用正则 [.!?]+ 分割计算句子数,检查是否在 1 到 6 之间\n- pass_condition: 同时满足:包含运营关键词、提到 Marcus/Cedar Grove、句子数在 1-6 之间\n\nComponent 3:\n- name: C3\n- weight: 0.20\n- description: 检查 HubSpot 中 Marcus Bell 的 leadStatus 是否变为 attempted,且干扰项未被修改\n- check_logic: 在当前 hubspot 状态中查找 TARGET_EMAIL 联系人,检查 enum_key(leadStatus) == 'attempted';查找 DISTRACTOR_EMAIL 联系人,检查其 leadStatus 仍为 'connected'\n- pass_condition: Marcus Bell 的 leadStatus 为 'attempted',且 Marcus Bellamy 的 leadStatus 仍为 'connected'\n\nComponent 4:\n- name: C4\n- weight: 0.15\n- description: 检查是否为 Marcus Bell 添加了记录外联活动的新备注\n- check_logic: 遍历当前 notes,筛选 associatedType 为 'contact' 且 associatedId 为 marcus_id 且 id 不在初始备注集合中的新备注;检查 body 是否包含 outreach/email 相关关键词\n- pass_condition: 存在一条新的、关联到 Marcus Bell 的备注,且正文包含外联相关关键词\n\nComponent 5:\n- name: C5\n- weight: 0.20\n- description: 检查是否为 Marcus Bell 创建了跟进任务\n- check_logic: 遍历当前 tasks,筛选 contactId 为 marcus_id 且 id 不在初始任务集合中的新任务;检查 enum_key(type) == 'email',enum_key(status) == 'notstarted',且 dueDate 的日历日期等于 upcoming_friday()(即将到来的周五,或今天若今天是周五)\n- pass_condition: 存在新的 email 类型任务,状态为 not_started,截止日期为即将到来的周五(或今天若周五),且关联到 Marcus Bell\n\nFailure modes:\n- 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL,输出 REWARD: 0.0,sys.exit(0)\n- 获取 mock 状态失败 -> CRITICAL,输出 REWARD: 0.0,sys.exit(0)\n- C1 失败:无新邮件、主题或正文为空\n- C2 失败:缺少运营关键词、未提及目标、句子数不在 1-6 范围内\n- C3 失败:leadStatus 不是 attempted,或干扰项被修改\n- C4 失败:无新备注或备注内容不匹配\n- C5 失败:无新任务或任务类型/状态/日期不匹配\n\nScore aggregation: 各组件分数累加,最终通过 round(min(total, 1.0), 4) 计算,即相加后钳制到 1.0 上限并四舍五入到4位小数。\n\n现在用中文组织内容,确保所有 value 都是中文(除了保留的标识符)。\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n\n让我构建最终的 JSON。 {\"task_id\":\"sdr_cold_outreach_002\",\"domain\":\"mock_websites\",\"summary\":\"验证 SDR 向 Marcus Bell 发送冷外联邮件,并在 HubSpot 中更新其线索状态为 attempted、添加外联备注及创建周五截止的 email 跟进任务。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"gmail_mock (http://28.7.186.212:8158)\",\"hubspot_mock (http://28.7.186.212:8170)\"],\"scoring_components\":[{\"name\":\"C1\",\"weight\":0.25,\"description\":\"检查 Gmail 的 Sent 文件夹中是否出现了新发送给 Marcus Bell 的邮件,且主题和正文均非空。\",\"check_logic\":\"分别统计初始状态 gmail_init 与当前状态 gmail_cur 中 folder 为 'sent' 且收件人包含 TARGET_EMAIL 的邮件数量;若 cur_sent 数量大于 init_sent,则取最新邮件 cand,去除 HTML 标签并归一化空白后检查 subject 和 body_text 是否均非空。\",\"pass_condition\":\"当前 sent 邮件数严格大于初始 sent 邮件数,且最新邮件的 subject 与 body_text(去标签后)均非空。\"},{\"name\":\"C2\",\"weight\":0.20,\"description\":\"检查邮件正文是否针对 Marcus Bell 的运营角色展开,并提及 Marcus 或 Cedar Grove Health,且篇幅简洁。\",\"check_logic\":\"基于 C1 获取的 sent_body_text,使用 contains_phrase 检查是否包含运营关键词(operation, operational, ops, logistics 等);是否提及目标对象关键词(marcus, cedar grove 等);使用正则 [.!?]+ 分割正文统计句子数,检查句子数是否在 1 到 6 之间(含)。\",\"pass_condition\":\"同时满足:包含至少一个运营相关关键词、提及 Marcus 或 Cedar Grove Health、句子数在 1-6 句之间。\"},{\"name\":\"C3\",\"weight\":0.20,\"description\":\"检查 HubSpot 中 Marcus Bell 的 leadStatus 是否由 new 变为 attempted,且干扰联系人 Marcus Bellamy 未被改动。\",\"check_logic\":\"在当前 hubspot 状态中通过 TARGET_EMAIL 查找 Marcus Bell,使用 enum_key 规范化后检查 leadStatus 是否等于 'attempted';同时通过 DISTRACTOR_EMAIL 查找 Marcus Bellamy,检查其 leadStatus 是否仍为 'connected'。\",\"pass_condition\":\"Marcus Bell 的 leadStatus 为 'attempted',且 Marcus Bellamy 的 leadStatus 保持为 'connected'。\"},{\"name\":\"C4\",\"weight\":0.15,\"description\":\"检查是否为 Marcus Bell 新增了一条记录此次外联活动的备注(note)。\",\"check_logic\":\"遍历 hub_cur 中的 notes,筛选 associatedType 为 'contact'、associatedId 等于 marcus_id 且 id 不在 hub_init 初始备注集合中的新备注;使用 contains_phrase 检查备注 body 是否包含 outreach/email 相关关键词(如 outreach, email, contacted, sent 等)。\",\"pass_condition\":\"存在一条新的、关联到 Marcus Bell 的备注,且其正文包含外联或邮件相关关键词。\"},{\"name\":\"C5\",\"weight\":0.20,\"description\":\"检查是否为 Marcus Bell 创建了一个新的 email 跟进任务,状态为未开始,且截止日期为即将到来的周五(若当天为周五则为今天)。\",\"check_logic\":\"遍历 hub_cur 中的 tasks,筛选 contactId 等于 marcus_id 且 id 不在 hub_init 初始任务集合中的新任务;检查 enum_key(type) 为 'email',enum_key(status) 为 'notstarted',并使用 same_calendar_date 比较 dueDate 与 TARGET_FRIDAY(upcoming_friday() 返回的日期)。\",\"pass_condition\":\"存在新的任务,其类型为 'email'、状态为 'not_started'、截止日期等于即将到来的周五(或今天若今天是周五),且关联到 Marcus Bell。\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数直接累加,最终通过 round(min(total, 1.0), 4) 计算总分,即相加后钳制到 1.0 上限并四舍五入保留四位小数。\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并直接退出,REWARD 为 0.0。\",\"请求 gmail_mock 或 hubspot_mock 状态失败:打印 CRITICAL 并直接退出,REWARD 为 0.0。\",\"C1 失败:当前 sent 邮件数未增加,或最新邮件主题/正文为空。\",\"C2 失败:邮件正文缺少运营关键词、未提及 Marcus/Cedar Grove,或句子数不在 1-6 范围内。\",\"C3 失败:Marcus Bell 的 leadStatus 不是 attempted,或干扰项 Marcus Bellamy 的 leadStatus 被改动。\",\"C4 失败:未找到关联到 Marcus Bell 的新备注,或备注正文不包含外联相关关键词。\",\"C5 失败:未找到关联到 Marcus Bell 的新任务,或任务类型/状态/截止日期不匹配。\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识;若失败则直接返回 0.0。随后通过 HTTP 请求分别拉取 gmail_mock 和 hubspot_mock 的初始状态与当前状态;若拉取失败也直接返回 0.0。接着在当前 hubspot 状态中解析 Marcus Bell 的联系人及其 id,供后续组件使用。评分按顺序执行五个组件:C1 验证 Gmail Sent 中新增了一封发给 marcus.bell@cedargrovehealth.com 且主题和正文均非空的邮件;C2 在 C1 通过的基础上,进一步检查邮件正文是否包含运营角色关键词、是否提及 Marcus 或 Cedar Grove Health,且句子数在 1-6 之间;C3 检查 HubSpot 中 Marcus Bell 的 leadStatus 变为 'attempted',同时确保干扰联系人 Marcus Bellamy 的状态未被修改;C4 检查是否为 Marcus Bell 新增了一条记录外联的备注;C5 检查是否为 Marcus Bell 新增了一个类型为 email、状态为 not_started、截止日期为即将到来的周五的跟进任务。每个组件独立判断,通过则累加对应分值,失败或异常则该组件得 0 分但不中断后续检查。最终汇总各组件得分,钳制在 1.0 以内并四舍五入后输出 REWARD。\",\"confidence\":1.0}" +} diff --git a/sdr_source_lead_003/_cua_gym_vm_bridge.sh b/sdr_source_lead_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/sdr_source_lead_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/sdr_source_lead_003/initial_setup.py b/sdr_source_lead_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d785a599b372c33a89d0d9cb88a5403511f30319 --- /dev/null +++ b/sdr_source_lead_003/initial_setup.py @@ -0,0 +1,787 @@ +# --- 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: SDR sources a LinkedIn prospect (Priya Nair, VP of Engineering at +NorthBeam Logistics), then logs her as a Salesforce lead + follow-up task. +Task ID: sdr_source_lead_003 +Domain: mock_websites +Mocks: linkedin_mock, salesforce_mock + +Pre-task (initial) state: + LinkedIn - logged in as Alex Morgan (user_admin, SDR @ Northwind Cloud). + users map has the target user_5 = Priya Nair (VP of Engineering @ + NorthBeam Logistics, Austin TX) AND the near-duplicate distractor + user_6 = Priya Naidu (Engineering Manager @ BrightForge Systems). + companies map includes NorthBeam Logistics. connectionRequests = []. + Salesforce- logged in as Alex Morgan (user-1, Sales). 7 unrelated default leads, + NONE for Priya Nair / NorthBeam Logistics. activities holds default + tasks/events, none referencing Priya. + +NEGATIVE CONSTRAINTS (verified true here): + - No pending connection request from user_admin to user_5. + - No Priya Nair / NorthBeam Logistics lead. + - No follow-up intro-email activity for Priya. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +LINKEDIN_URL = 'http://28.7.184.198:8157' +SF_URL = 'http://28.7.184.198:8175' + +sid = str(uuid.uuid4()) + +# --- §1.5 Egress proxy helper --- +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 + raise RuntimeError('No working route to mock servers; direct and proxy attempts failed') + + +PROXY = resolve_proxy(f'{SF_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + +# --- Persist sid for golden_patch.py and reward.py --- +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +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 +def build_linkedin_state(): + return { + "currentUser": { + "id": "user_admin", + "name": "Alex Morgan", + "headline": "Sales Development Representative at Northwind Cloud", + "location": "Denver, Colorado, United States", + "about": "SDR at Northwind Cloud helping engineering and ops teams modernize " + "their cloud infrastructure. Always happy to connect with builders.", + "avatar": "https://i.pravatar.cc/200?u=user_admin", + "banner": "https://picsum.photos/1200/400?random=banner_admin", + "connections": ["user_2", "user_3", "user_4"], + "experience": [ + { + "title": "Sales Development Representative", + "company": "Northwind Cloud", + "duration": "2024 - Present", + "location": "Denver, CO", + } + ], + "education": [ + { + "school": "University of Colorado Boulder", + "degree": "B.A. Communications", + "years": "2016 - 2020", + } + ], + "skills": ["Prospecting", "SaaS Sales", "Lead Generation", "CRM"], + }, + "users": { + "user_2": { + "id": "user_2", + "name": "Daniel Brooks", + "headline": "Account Executive at Northwind Cloud", + "location": "Denver, Colorado, United States", + "about": "Closing deals and building relationships.", + "avatar": "https://i.pravatar.cc/200?u=user_2", + "banner": "https://picsum.photos/1200/400?random=banner_2", + "connections": ["user_admin"], + "experience": [], "education": [], "skills": [], + }, + "user_3": { + "id": "user_3", + "name": "Sophia Reyes", + "headline": "Sales Manager at Northwind Cloud", + "location": "Austin, Texas, United States", + "about": "Leading a team of SDRs and AEs.", + "avatar": "https://i.pravatar.cc/200?u=user_3", + "banner": "https://picsum.photos/1200/400?random=banner_3", + "connections": ["user_admin"], + "experience": [], "education": [], "skills": [], + }, + "user_4": { + "id": "user_4", + "name": "Marcus Johnson", + "headline": "Solutions Engineer at CloudScale", + "location": "Seattle, Washington, United States", + "about": "Helping customers architect scalable systems.", + "avatar": "https://i.pravatar.cc/200?u=user_4", + "banner": "https://picsum.photos/1200/400?random=banner_4", + "connections": ["user_admin"], + "experience": [], "education": [], "skills": [], + }, + # --- TARGET PROSPECT --- + "user_5": { + "id": "user_5", + "name": "Priya Nair", + "headline": "VP of Engineering at NorthBeam Logistics", + "location": "Austin, Texas, United States", + "about": "Engineering leader scaling logistics platforms. Passionate about " + "reliability, observability, and growing high-performing teams.", + "avatar": "https://i.pravatar.cc/200?u=user_5", + "banner": "https://picsum.photos/1200/400?random=banner_5", + "connections": ["user_7", "user_8"], + "experience": [ + { + "title": "VP of Engineering", + "company": "NorthBeam Logistics", + "duration": "2022 - Present", + "location": "Austin, TX", + } + ], + "education": [ + { + "school": "Georgia Institute of Technology", + "degree": "M.S. Computer Science", + "years": "2008 - 2010", + } + ], + "skills": ["Engineering Leadership", "Distributed Systems", "Logistics Tech"], + }, + # --- NEAR-DUPLICATE DISTRACTOR (must remain untouched) --- + "user_6": { + "id": "user_6", + "name": "Priya Naidu", + "headline": "Engineering Manager at BrightForge Systems", + "location": "San Jose, California, United States", + "about": "Engineering manager focused on developer productivity tooling.", + "avatar": "https://i.pravatar.cc/200?u=user_6", + "banner": "https://picsum.photos/1200/400?random=banner_6", + "connections": ["user_4"], + "experience": [ + { + "title": "Engineering Manager", + "company": "BrightForge Systems", + "duration": "2021 - Present", + "location": "San Jose, CA", + } + ], + "education": [], "skills": ["Team Management", "Developer Tools"], + }, + "user_7": { + "id": "user_7", + "name": "Olivia Carter", + "headline": "Director of Operations at NorthBeam Logistics", + "location": "Austin, Texas, United States", + "about": "Operations leader in supply chain.", + "avatar": "https://i.pravatar.cc/200?u=user_7", + "banner": "https://picsum.photos/1200/400?random=banner_7", + "connections": ["user_5"], + "experience": [], "education": [], "skills": [], + }, + "user_8": { + "id": "user_8", + "name": "Ethan Wright", + "headline": "Staff Software Engineer at NorthBeam Logistics", + "location": "Remote, United States", + "about": "Backend engineer working on routing optimization.", + "avatar": "https://i.pravatar.cc/200?u=user_8", + "banner": "https://picsum.photos/1200/400?random=banner_8", + "connections": ["user_5"], + "experience": [], "education": [], "skills": [], + }, + }, + "companies": { + "company_1": { + "id": "company_1", + "name": "Northwind Cloud", + "logo": "https://logo.clearbit.com/northwind.example", + "industry": "Software Development", + "size": "201-500 employees", + "headquarters": "Denver, CO", + "description": "Cloud infrastructure platform for modern engineering teams.", + }, + "company_2": { + "id": "company_2", + "name": "NorthBeam Logistics", + "logo": "https://logo.clearbit.com/northbeam.example", + "industry": "Logistics & Supply Chain", + "size": "501-1,000 employees", + "headquarters": "Austin, TX", + "description": "Technology-driven logistics and supply chain company serving " + "mid-market retailers across North America.", + }, + "company_3": { + "id": "company_3", + "name": "BrightForge Systems", + "logo": "https://logo.clearbit.com/brightforge.example", + "industry": "Computer Software", + "size": "51-200 employees", + "headquarters": "San Jose, CA", + "description": "Developer productivity and tooling company.", + }, + "company_4": { + "id": "company_4", + "name": "CloudScale", + "logo": "https://logo.clearbit.com/cloudscale.example", + "industry": "Information Technology", + "size": "1,001-5,000 employees", + "headquarters": "Seattle, WA", + "description": "Enterprise cloud solutions provider.", + }, + }, + "posts": [ + { + "id": "post_1", + "userId": "user_5", + "content": "Proud of the NorthBeam Logistics engineering team for shipping our " + "new real-time tracking platform this quarter. Reliability up, " + "latency down. Hiring backend and SRE talent — reach out!", + "image": "https://picsum.photos/800/450?random=post_1", + "reactions": { + "like": ["user_7", "user_8"], "celebrate": ["user_4"], + "love": [], "insightful": [], "funny": [], "curious": [], + }, + "comments": [ + { + "id": "cmt_1", "userId": "user_8", + "content": "Great milestone — proud to be part of it!", + "created": "2026-06-20T15:10:00Z", "likes": ["user_5"], + } + ], + "created": "2026-06-20T14:00:00Z", + "repostedBy": None, "repostOf": None, + }, + { + "id": "post_2", + "userId": "user_2", + "content": "Northwind Cloud just crossed 300 customers. Grateful to our team " + "and partners. Onward!", + "image": None, + "reactions": { + "like": ["user_admin", "user_3"], "celebrate": ["user_admin"], + "love": [], "insightful": [], "funny": [], "curious": [], + }, + "comments": [], + "created": "2026-06-18T09:30:00Z", + "repostedBy": None, "repostOf": None, + }, + ], + "jobs": [], + "chats": [ + { + "id": "chat_1", + "participants": ["user_admin", "user_2"], + "messages": [ + { + "id": "m1", "senderId": "user_2", + "content": "Hey Alex, did you get a chance to look at the NorthBeam " + "account? Might be a good fit.", + "created": "2026-06-22T17:05:00Z", "read": True, + }, + { + "id": "m2", "senderId": "user_admin", + "content": "On it — about to start prospecting their eng leadership.", + "created": "2026-06-22T17:08:00Z", "read": True, + }, + ], + } + ], + "notifications": [ + { + "id": "notif_1", "type": "profile_view", "actorId": "user_4", + "targetId": "user_admin", "content": "Marcus Johnson viewed your profile", + "read": False, "created": "2026-06-23T11:00:00Z", + }, + { + "id": "notif_2", "type": "like", "actorId": "user_3", + "targetId": "post_2", "content": "Sophia Reyes liked a post you reacted to", + "read": True, "created": "2026-06-18T10:00:00Z", + }, + ], + # NEGATIVE CONSTRAINT: no pending request from user_admin to user_5 + "connectionRequests": [], + } + + +# ====================================================================== +# SALESFORCE INITIAL STATE +# ====================================================================== +def build_salesforce_state(): + users = [ + { + "userId": "user-1", "firstName": "Alex", "lastName": "Morgan", + "email": "alex.morgan@northwindcloud.com", "phone": "(555) 123-4567", + "title": "Sales Development Representative", "department": "Sales", "role": "Sales", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/Denver", "locale": "en-US", "theme": "lightning", + }, + { + "userId": "user-2", "firstName": "Sophia", "lastName": "Reyes", + "email": "sophia.reyes@northwindcloud.com", "phone": "(555) 234-5678", + "title": "Sales Manager", "department": "Sales", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning", + }, + { + "userId": "user-3", "firstName": "Daniel", "lastName": "Brooks", + "email": "daniel.brooks@northwindcloud.com", "phone": "(555) 345-6789", + "title": "Account Executive", "department": "Sales", "role": "Sales", + "avatar": "https://i.pravatar.cc/150?u=user-3", + "timezone": "America/Denver", "locale": "en-US", "theme": "lightning", + }, + { + "userId": "user-4", "firstName": "Emily", "lastName": "Tran", + "email": "emily.tran@northwindcloud.com", "phone": "(555) 456-7890", + "title": "Marketing Specialist", "department": "Marketing", "role": "Marketing", + "avatar": "https://i.pravatar.cc/150?u=user-4", + "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning", + }, + { + "userId": "user-5", "firstName": "James", "lastName": "Patel", + "email": "james.patel@northwindcloud.com", "phone": "(555) 567-8901", + "title": "Account Executive", "department": "Sales", "role": "Sales", + "avatar": "https://i.pravatar.cc/150?u=user-5", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + }, + ] + + leads = [ + { + "leadId": "lead-1", "firstName": "Rachel", "lastName": "Kim", + "company": "Vertex Manufacturing", "title": "Director of IT", + "email": "rachel.kim@vertexmfg.com", "phone": "(555) 201-3001", "mobile": "", + "status": "Working", "source": "Web", "rating": "Warm", + "street": "120 Industrial Pkwy", "city": "Cleveland", "state": "OH", + "zip": "44101", "country": "USA", "industry": "Manufacturing", + "employees": 600, "revenue": 40000000, "website": "https://vertexmfg.com", + "description": "Inbound demo request.", "ownerId": "user-1", + "createdDate": "2026-05-12T00:00:00.000Z", "modifiedDate": "2026-06-10T00:00:00.000Z", + }, + { + "leadId": "lead-2", "firstName": "Tom", "lastName": "Alvarez", + "company": "Skyline Retail Group", "title": "VP of Operations", + "email": "tom.alvarez@skylineretail.com", "phone": "(555) 202-3002", "mobile": "", + "status": "New", "source": "Trade Show", "rating": "Cold", + "street": "88 Market St", "city": "Phoenix", "state": "AZ", + "zip": "85001", "country": "USA", "industry": "Retail", + "employees": 1200, "revenue": 90000000, "website": "https://skylineretail.com", + "description": "Met at SaaSConf booth.", "ownerId": "user-3", + "createdDate": "2026-06-01T00:00:00.000Z", "modifiedDate": "2026-06-01T00:00:00.000Z", + }, + { + "leadId": "lead-3", "firstName": "Nina", "lastName": "Okafor", + "company": "Brightline Health", "title": "CTO", + "email": "nina.okafor@brightlinehealth.com", "phone": "(555) 203-3003", "mobile": "", + "status": "Qualified", "source": "Referral", "rating": "Hot", + "street": "9 Wellness Way", "city": "Boston", "state": "MA", + "zip": "02108", "country": "USA", "industry": "Healthcare", + "employees": 300, "revenue": 25000000, "website": "https://brightlinehealth.com", + "description": "Referred by existing customer.", "ownerId": "user-5", + "createdDate": "2026-04-22T00:00:00.000Z", "modifiedDate": "2026-06-15T00:00:00.000Z", + }, + { + "leadId": "lead-4", "firstName": "Greg", "lastName": "Holloway", + "company": "Apex Financial", "title": "Head of Infrastructure", + "email": "greg.holloway@apexfin.com", "phone": "(555) 204-3004", "mobile": "", + "status": "Working", "source": "Web", "rating": "Warm", + "street": "400 Finance Blvd", "city": "Charlotte", "state": "NC", + "zip": "28202", "country": "USA", "industry": "Finance", + "employees": 2500, "revenue": 180000000, "website": "https://apexfin.com", + "description": "Downloaded whitepaper.", "ownerId": "user-1", + "createdDate": "2026-05-28T00:00:00.000Z", "modifiedDate": "2026-06-12T00:00:00.000Z", + }, + { + "leadId": "lead-5", "firstName": "Carla", "lastName": "Mendez", + "company": "Greenfield Energy", "title": "Procurement Manager", + "email": "carla.mendez@greenfieldenergy.com", "phone": "(555) 205-3005", "mobile": "", + "status": "New", "source": "Email", "rating": "Cold", + "street": "55 Solar Dr", "city": "Denver", "state": "CO", + "zip": "80202", "country": "USA", "industry": "Energy", + "employees": 450, "revenue": 35000000, "website": "https://greenfieldenergy.com", + "description": "Cold outreach response.", "ownerId": "user-3", + "createdDate": "2026-06-08T00:00:00.000Z", "modifiedDate": "2026-06-08T00:00:00.000Z", + }, + { + "leadId": "lead-6", "firstName": "Victor", "lastName": "Shaw", + "company": "Cobalt Media", "title": "IT Director", + "email": "victor.shaw@cobaltmedia.com", "phone": "(555) 206-3006", "mobile": "", + "status": "Unqualified", "source": "Web", "rating": "Cold", + "street": "17 Broadcast Ln", "city": "Atlanta", "state": "GA", + "zip": "30303", "country": "USA", "industry": "Media", + "employees": 220, "revenue": 18000000, "website": "https://cobaltmedia.com", + "description": "Budget not aligned this cycle.", "ownerId": "user-5", + "createdDate": "2026-03-30T00:00:00.000Z", "modifiedDate": "2026-05-02T00:00:00.000Z", + }, + { + "leadId": "lead-7", "firstName": "Hannah", "lastName": "Lindqvist", + "company": "Meridian Travel", "title": "VP Engineering", + "email": "hannah.l@meridiantravel.com", "phone": "(555) 207-3007", "mobile": "", + "status": "Working", "source": "Referral", "rating": "Warm", + "street": "210 Journey Ave", "city": "Miami", "state": "FL", + "zip": "33101", "country": "USA", "industry": "Travel", + "employees": 800, "revenue": 60000000, "website": "https://meridiantravel.com", + "description": "Intro call completed; evaluating.", "ownerId": "user-1", + "createdDate": "2026-05-19T00:00:00.000Z", "modifiedDate": "2026-06-14T00:00:00.000Z", + }, + ] + + accounts = [ + { + "accountId": "account-1", "name": "Vertex Manufacturing", "phone": "(555) 201-3000", + "website": "https://vertexmfg.com", "type": "Prospect", "industry": "Manufacturing", + "revenue": 40000000, "employees": 600, + "description": "Mid-market manufacturer evaluating cloud migration.", + "ownerId": "user-1", + "billingStreet": "120 Industrial Pkwy", "billingCity": "Cleveland", "billingState": "OH", + "billingZip": "44101", "billingCountry": "United States", + "shippingStreet": "120 Industrial Pkwy", "shippingCity": "Cleveland", "shippingState": "OH", + "shippingZip": "44101", "shippingCountry": "United States", + "createdDate": "2026-05-12T00:00:00.000Z", "modifiedDate": "2026-06-10T00:00:00.000Z", + }, + { + "accountId": "account-2", "name": "Brightline Health", "phone": "(555) 203-3000", + "website": "https://brightlinehealth.com", "type": "Customer", "industry": "Healthcare", + "revenue": 25000000, "employees": 300, + "description": "Healthcare SaaS customer since 2025.", + "ownerId": "user-5", + "billingStreet": "9 Wellness Way", "billingCity": "Boston", "billingState": "MA", + "billingZip": "02108", "billingCountry": "United States", + "shippingStreet": "9 Wellness Way", "shippingCity": "Boston", "shippingState": "MA", + "shippingZip": "02108", "shippingCountry": "United States", + "createdDate": "2025-11-02T00:00:00.000Z", "modifiedDate": "2026-06-15T00:00:00.000Z", + }, + ] + + contacts = [ + { + "contactId": "contact-1", "accountId": "account-2", "firstName": "Nina", + "lastName": "Okafor", "title": "CTO", "department": "Engineering", + "email": "nina.okafor@brightlinehealth.com", "phone": "(555) 203-3003", + "mobile": "(555) 203-3013", "mailingStreet": "9 Wellness Way", + "mailingCity": "Boston", "mailingState": "MA", "mailingZip": "02108", + "mailingCountry": "United States", "ownerId": "user-5", + "createdDate": "2025-11-02T00:00:00.000Z", "modifiedDate": "2026-06-15T00:00:00.000Z", + } + ] + + activities = [ + { + "activityId": "activity-1", "type": "task", + "subject": "Follow up with Apex Financial on whitepaper", + "status": "Open", "priority": "Normal", "dueDate": "2026-06-25", + "relatedToType": "lead", "relatedToId": "lead-4", "assignedToId": "user-1", + }, + { + "activityId": "activity-2", "type": "task", + "subject": "Send pricing to Vertex Manufacturing", + "status": "Open", "priority": "High", "dueDate": "2026-06-27", + "relatedToType": "lead", "relatedToId": "lead-1", "assignedToId": "user-1", + }, + { + "activityId": "activity-3", "type": "event", + "subject": "Discovery call: Meridian Travel", + "status": "Open", "priority": "Normal", + "startDateTime": "2026-06-26T15:00:00.000Z", + "endDateTime": "2026-06-26T15:30:00.000Z", + "relatedToType": "lead", "relatedToId": "lead-7", "assignedToId": "user-1", + }, + { + "activityId": "activity-4", "type": "task", + "subject": "Prep demo deck for Brightline Health QBR", + "status": "Completed", "priority": "Normal", "dueDate": "2026-06-18", + "relatedToType": "account", "relatedToId": "account-2", "assignedToId": "user-5", + }, + { + "activityId": "activity-5", "type": "task", + "subject": "Research NorthBeam Logistics account fit", + "status": "Open", "priority": "Normal", "dueDate": "2026-06-24", + "relatedToType": "account", "relatedToId": "account-1", "assignedToId": "user-1", + }, + { + "activityId": "activity-6", "type": "event", + "subject": "Weekly sales sync", + "status": "Open", "priority": "Low", + "startDateTime": "2026-06-25T16:00:00.000Z", + "endDateTime": "2026-06-25T16:30:00.000Z", + "relatedToType": "", "relatedToId": "", "assignedToId": "user-1", + }, + ] + + return { + "user": users[0], + "users": users, + "leads": leads, + "accounts": accounts, + "contacts": contacts, + "opportunities": [], + "cases": [], + "activities": activities, + "chatterPosts": [], + "files": [], + "following": ["user-2", "user-3"], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# ====================================================================== +# Inject state into both mocks (same sid) +# ====================================================================== +mocks = { + LINKEDIN_URL: build_linkedin_state(), + SF_URL: build_salesforce_state(), +} + +for url, state in mocks.items(): + resp = requests.post( + f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + proxies=PROXIES, + ) + assert resp.status_code == 200, f'State injection failed for {url}: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10, proxies=PROXIES).json() + assert go['initial_state'] is not None, f'initial_state is None after injection for {url}' + print(f'State injected & verified: {url} sid={sid}') + +# ====================================================================== +# Launch browsers (LinkedIn primary/focused last, Salesforce too) +# ====================================================================== +chrome_proxy = f'--proxy-server={PROXY}' if PROXY else '' +launch_gui(f'google-chrome "{SF_URL}/?sid={sid}"', delay_sec=2.0) +launch_gui(f'google-chrome "{LINKEDIN_URL}/?sid={sid}"', delay_sec=2.0) +wait_mocks_loaded() +print(f'GUI_READY: launched Salesforce and LinkedIn with sid={sid}') diff --git a/sdr_source_lead_003/reward.py b/sdr_source_lead_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1245a6c5b15d389677d9432825363d2d2d99cf72 --- /dev/null +++ b/sdr_source_lead_003/reward.py @@ -0,0 +1,339 @@ +# --- 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: Source a LinkedIn lead (Priya Nair) into Salesforce + follow-up task +Task ID: sdr_source_lead_003 +Domain: mock_websites +Mocks: linkedin_mock, salesforce_mock + +Scoring (1.0 total) — all components verify TASK-INTRODUCED changes only +(every sub-check FAILS on initial_env and PASSES on golden_env): + + Component A — LinkedIn connection request to Priya Nair (0.30) + A1 (0.30): a NEW pending request fromUserId=user_admin, toUserId=user_5 + with a non-empty note (len >= 10 after normalize) + + Component B — Salesforce new lead for Priya Nair (0.40) + B1 (0.10): exactly one NEW lead identifiable as Priya Nair @ NorthBeam Logistics + B2 (0.10): source == 'LinkedIn' + B3 (0.10): rating == 'Warm' + B4 (0.10): status == 'New' (fresh/untouched) AND ownerId == 'user-1' + AND title == 'VP of Engineering' + + Component C — Salesforce follow-up task (0.30) + C1 (0.10): a NEW task (type 'task') whose subject names an intro email to Priya/Nair + C2 (0.10): dueDate is the local date two days from reward runtime + AND status is open/pending rather than completed/blank + C3 (0.10): relatedToType 'lead' pointing at the new lead AND assignedToId 'user-1' +""" +from datetime import date, datetime, timedelta +import json +import os +import re +import sys + +import requests + +LINKEDIN_URL = 'http://28.7.184.198:8157' +SALESFORCE_URL = 'http://28.7.184.198:8175' + +# --- Read sid (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) + +# --- Egress proxy helper (cluster VMs may need a proxy to reach mock servers) --- +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'{LINKEDIN_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +def fetch(url): + try: + resp = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES) + resp.raise_for_status() + return resp.json() + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {url}/go?sid={sid}: {e}') + return None + + +li = fetch(LINKEDIN_URL) +sf = fetch(SALESFORCE_URL) +if li is None or sf is None: + print('REWARD: 0.0') + sys.exit(0) + +li_ini = li.get('initial_state') or {} +li_cur = li.get('current_state') or {} +sf_ini = sf.get('initial_state') or {} +sf_cur = sf.get('current_state') or {} + +if not li_cur or not sf_cur: + print('CRITICAL: current_state missing for one of the mocks') + print('REWARD: 0.0') + sys.exit(0) + + +def is_priya_lead(lead): + """A lead that represents Priya Nair at NorthBeam Logistics.""" + fn = str(lead.get('firstName', '')).strip().lower() + ln = str(lead.get('lastName', '')).strip().lower() + co = str(lead.get('company', '')).strip().lower() + name_ok = (fn == 'priya' and ln == 'nair') + company_ok = 'northbeam' in co # tolerant of "NorthBeam Logistics" spacing/suffix + return name_ok and company_ok + + +def is_personalized_note(note): + """Accept any non-trivial note (no keyword requirements).""" + text = ' '.join(str(note or '').strip().lower().split()) + return len(text) >= 10 + + +def is_vp_engineering_title(title): + text = ' '.join(str(title or '').strip().lower().split()) + if not text: + return False + compact = re.sub(r'[^a-z]+', ' ', text).strip() + title_patterns = ( + r'\bvp\s+(?:of\s+)?engineering\b', + r'\bvice\s+president\s+(?:of\s+)?engineering\b', + r'\bengineering\s+vice\s+president\b', + ) + return any(re.search(pattern, compact) for pattern in title_patterns) + + +def is_intro_email_subject(subject): + text = ' '.join(str(subject or '').strip().lower().split()) + if not text: + return False + mentions_person = 'priya' in text or 'nair' in text + mentions_intro = any(term in text for term in ('intro', 'introduction', 'introductory')) + mentions_email = any(term in text for term in ('email', 'e-mail', 'mail', 'message', 'note', 'outreach')) + return mentions_person and (mentions_intro or mentions_email) + + +def is_open_task_status(status): + text = str(status or '').strip().lower() + return text in {'open', 'pending', 'not started', 'new', 'todo', 'to do'} + + +def parse_date_parts(value): + """Return (year, month, day) for ISO-like date strings without relying on prefixes.""" + text = str(value or '').strip() + if not text: + return None + + normalized = text.replace('Z', '+00:00') + for candidate in (normalized, normalized[:10]): + try: + parsed = datetime.fromisoformat(candidate) + return parsed.year, parsed.month, parsed.day + except ValueError: + try: + parsed_date = date.fromisoformat(candidate[:10]) + return parsed_date.year, parsed_date.month, parsed_date.day + except ValueError: + pass + + match = re.search(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})', text) + if match: + return tuple(int(part) for part in match.groups()) + return None + + +def verify_task(): + total_score = 0.0 + + # ============================================================ + # Component A — LinkedIn connection request with personalized note (0.30) + # ============================================================ + # Anchor on NEW connection requests (ids not present in initial_state) + # so a pre-existing request could never earn points. + try: + ini_reqs = li_ini.get('connectionRequests', []) or [] + cur_reqs = li_cur.get('connectionRequests', []) or [] + ini_ids = {r.get('id') for r in ini_reqs} + new_reqs = [r for r in cur_reqs if r.get('id') not in ini_ids] + + # The specific request: from the logged-in SDR to Priya (user_5), pending + target = None + for r in new_reqs: + if (r.get('fromUserId') == 'user_admin' + and r.get('toUserId') == 'user_5' + and str(r.get('status', '')).lower() == 'pending'): + target = r + break + + # A1: new pending request user_admin -> user_5 with non-empty note (0.30) + if target is not None: + note = str(target.get('note', '') or '').strip() + if is_personalized_note(note): + print('PASS: A1 — new pending request user_admin -> user_5 ' + f'with note ("{note[:60]}...") (0.30)') + total_score += 0.30 + else: + print('FAIL: A1 — request exists but note is missing/too short; ' + f'expected non-empty note (len>=10), got {note!r}') + else: + print('FAIL: A1 — no new pending request from user_admin to user_5 ' + f'(new requests: {json.dumps(new_reqs)[:200]})') + except Exception as e: + print(f'ERROR: Component A — {e}') + + # ============================================================ + # Component B — Salesforce new lead for Priya Nair (0.40) + # ============================================================ + new_lead = None + try: + ini_leads = sf_ini.get('leads', []) or [] + cur_leads = sf_cur.get('leads', []) or [] + ini_lead_ids = {l.get('leadId') for l in ini_leads} + new_leads = [l for l in cur_leads if l.get('leadId') not in ini_lead_ids] + + priya_new = [l for l in new_leads if is_priya_lead(l)] + + # B1: exactly one NEW Priya Nair @ NorthBeam lead (0.10) + if len(priya_new) == 1: + new_lead = priya_new[0] + print('PASS: B1 — exactly one new Priya Nair @ NorthBeam Logistics lead (0.10)') + total_score += 0.10 + elif len(priya_new) > 1: + new_lead = priya_new[0] + print(f'FAIL: B1 — expected exactly 1 new Priya lead, found {len(priya_new)} ' + '(not awarding B1, but evaluating B2-B4 on first match)') + else: + print('FAIL: B1 — no new lead matching Priya Nair @ NorthBeam Logistics ' + f'(new leads: {json.dumps([{k: l.get(k) for k in ("firstName","lastName","company")} for l in new_leads])[:200]})') + + if new_lead is not None: + # B2: source == LinkedIn (0.10) + if str(new_lead.get('source', '')).strip().lower() == 'linkedin': + print('PASS: B2 — lead source is LinkedIn (0.10)') + total_score += 0.10 + else: + print(f'FAIL: B2 — source is {new_lead.get("source")!r}, expected LinkedIn') + + # B3: rating == Warm (0.10) + if str(new_lead.get('rating', '')).strip().lower() == 'warm': + print('PASS: B3 — lead rating is Warm (0.10)') + total_score += 0.10 + else: + print(f'FAIL: B3 — rating is {new_lead.get("rating")!r}, expected Warm') + + # B4: status New (fresh) AND owner user-1 AND title VP of Engineering (0.10) + status_ok = str(new_lead.get('status', '')).strip().lower() == 'new' + owner_ok = str(new_lead.get('ownerId', '')).strip() == 'user-1' + title_ok = is_vp_engineering_title(new_lead.get('title', '')) + if status_ok and owner_ok and title_ok: + print('PASS: B4 — status New + ownerId user-1 + title VP of Engineering (0.10)') + total_score += 0.10 + else: + print(f'FAIL: B4 — status={new_lead.get("status")!r} owner={new_lead.get("ownerId")!r} ' + f'title={new_lead.get("title")!r} (need New / user-1 / VP of Engineering)') + except Exception as e: + print(f'ERROR: Component B — {e}') + + # ============================================================ + # Component C — Salesforce follow-up task (0.30) + # ============================================================ + try: + ini_acts = sf_ini.get('activities', []) or [] + cur_acts = sf_cur.get('activities', []) or [] + ini_act_ids = {a.get('activityId') for a in ini_acts} + new_acts = [a for a in cur_acts if a.get('activityId') not in ini_act_ids] + + # Find a NEW task whose subject references an intro email to Priya/Nair. + task = None + for a in new_acts: + is_task = str(a.get('type', '')).strip().lower() == 'task' + if is_task and is_intro_email_subject(a.get('subject', '')): + task = a + break + + # C1: new intro-email task referencing Priya/Nair (0.10) + if task is not None: + print(f'PASS: C1 — new intro-email task for Priya/Nair ("{task.get("subject")}") (0.10)') + total_score += 0.10 + + # C2: dueDate two local days from reward runtime AND task still open (0.10) + due = str(task.get('dueDate', '') or '').strip() + status_open = is_open_task_status(task.get('status', '')) + expected_due = datetime.now().date() + timedelta(days=2) + due_parts = parse_date_parts(due) + expected_parts = (expected_due.year, expected_due.month, expected_due.day) + if due_parts == expected_parts and status_open: + print(f'PASS: C2 — dueDate {due} matches local +2 days ' + f'({expected_due.isoformat()}) and task status is open (0.10)') + total_score += 0.10 + else: + print(f'FAIL: C2 — dueDate={due!r} status={task.get("status")!r} ' + f'(need {expected_due.isoformat()} and open/pending status)') + + # C3: relatedToType lead -> new lead AND assignedToId user-1 (0.10) + rel_type_ok = str(task.get('relatedToType', '')).strip().lower() == 'lead' + assigned_ok = str(task.get('assignedToId', '')).strip() == 'user-1' + rel_id = str(task.get('relatedToId', '')).strip() + rel_points_to_new = bool(new_lead) and rel_id == str(new_lead.get('leadId')) + if rel_type_ok and assigned_ok and rel_points_to_new: + print('PASS: C3 — relatedToType lead -> new lead, assignedToId user-1 (0.10)') + total_score += 0.10 + else: + print(f'FAIL: C3 — relatedToType={task.get("relatedToType")!r} ' + f'relatedToId={rel_id!r} assignedToId={task.get("assignedToId")!r} ' + f'(need lead / {new_lead.get("leadId") if new_lead else ""} / user-1)') + else: + print('FAIL: C1 — no new task referencing an intro email to Priya/Nair ' + f'(new activities: {json.dumps([{ "type": a.get("type"), "subject": a.get("subject")} for a in new_acts])[:200]})') + except Exception as e: + print(f'ERROR: Component C — {e}') + + 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/sdr_source_lead_003/reward_label.json b/sdr_source_lead_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..9c87ab34c801dd2566da72f69dd0340d3600ff8f --- /dev/null +++ b/sdr_source_lead_003/reward_label.json @@ -0,0 +1,92 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/sdr_source_lead_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-03 21:51:40", + "label": { + "task_id": "sdr_source_lead_003", + "domain": "mock_websites", + "summary": "验证将 LinkedIn 潜在客户 Priya Nair 导入 Salesforce 并创建跟进任务的任务行为", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "linkedin_mock", + "salesforce_mock" + ], + "scoring_components": [ + { + "name": "Component A — LinkedIn connection request", + "weight": 0.3, + "description": "验证向 Priya Nair 发送了新的 LinkedIn 连接请求并附带个性化备注", + "check_logic": "对比 initial_state 与 current_state 中的 connectionRequests,筛选 id 不在初始状态的新请求;检查是否存在 fromUserId='user_admin'、toUserId='user_5'、status='pending' 的请求;调用 is_personalized_note() 检查备注规范化后长度≥10(不再检测关键词)", + "pass_condition": "存在一个新的待处理连接请求,从 user_admin 发给 user_5,且备注非空(规范化后长度≥10)" + }, + { + "name": "Component B1 — New lead existence", + "weight": 0.1, + "description": "验证 Salesforce 中恰好新增了一个可识别为 Priya Nair @ NorthBeam Logistics 的 lead", + "check_logic": "对比 initial_state 与 current_state 中的 leads,筛选 leadId 不在初始状态的新 lead;调用 is_priya_lead() 检查 firstName='priya'、lastName='nair' 且 company 包含 'northbeam';要求恰好 1 个匹配", + "pass_condition": "新增 leads 中恰好有 1 个匹配 Priya Nair @ NorthBeam Logistics" + }, + { + "name": "Component B2 — Lead source", + "weight": 0.1, + "description": "验证新 lead 的来源为 LinkedIn", + "check_logic": "检查 B1 中找到的 new_lead 的 source 字段(转小写并去除空白)是否等于 'linkedin'", + "pass_condition": "source 字段等于 'linkedin'" + }, + { + "name": "Component B3 — Lead rating", + "weight": 0.1, + "description": "验证新 lead 的评级为 Warm", + "check_logic": "检查 new_lead 的 rating 字段(转小写并去除空白)是否等于 'warm'", + "pass_condition": "rating 字段等于 'warm'" + }, + { + "name": "Component B4 — Lead status, owner and title", + "weight": 0.1, + "description": "验证新 lead 的状态为 New、负责人为 user-1、职称为 VP of Engineering", + "check_logic": "检查 status 转小写后等于 'new';ownerId 去除空白后等于 'user-1';title 经 is_vp_engineering_title() 正则匹配 VP/Engineering 模式", + "pass_condition": "status='new' 且 ownerId='user-1' 且 title 匹配 VP of Engineering" + }, + { + "name": "Component C1 — Follow-up task subject", + "weight": 0.1, + "description": "验证 Salesforce 中新增了 subject 提及向 Priya/Nair 发送介绍邮件的 task", + "check_logic": "对比 initial_state 与 current_state 中的 activities,筛选 activityId 不在初始状态的新活动;查找 type='task' 且 subject 经 is_intro_email_subject() 检查包含 'priya' 或 'nair',以及 'intro'/'introduction'/'email'/'mail' 等词", + "pass_condition": "存在新的 task 类型活动,subject 同时提及 Priya/Nair 和介绍/邮件相关词汇" + }, + { + "name": "Component C2 — Task due date and status", + "weight": 0.1, + "description": "验证任务截止日期为运行时本地日期两天后且状态为开放/待处理", + "check_logic": "解析 task 的 dueDate(支持 ISO 格式和多种分隔符),与 datetime.now().date() + timedelta(days=2) 的年月日比较;检查 status 经 is_open_task_status() 匹配 'open'/'pending'/'not started'/'new'/'todo'/'to do'", + "pass_condition": "dueDate 的年月日等于当前日期+2 天,且 status 为 open/pending/not started/new/todo/to do" + }, + { + "name": "Component C3 — Task relation and assignment", + "weight": 0.1, + "description": "验证任务关联到新建的 lead 且指派给 user-1", + "check_logic": "检查 task 的 relatedToType 转小写后等于 'lead';assignedToId 等于 'user-1';relatedToId 等于 B1 中新建 lead 的 leadId", + "pass_condition": "relatedToType='lead' 且 assignedToId='user-1' 且 relatedToId 与 B1 的新 leadId 一致" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各子组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 sid 时打印 CRITICAL 并返回 0.0", + "无法从 linkedin_mock 或 salesforce_mock 拉取状态时返回 0.0", + "current_state 缺失时返回 0.0", + "Component A 中无新的 user_admin->user_5 待处理请求或备注不个性化则不得 0.30 分", + "Component B1 中无新增 Priya Nair lead 或数量不为 1 则不得 0.10 分(数量>1 时仍继续评估 B2-B4)", + "Component B2-B4 中任一字段不匹配则对应子项不得分", + "Component C1 中无匹配的新 task 则 C1-C3 均不得分", + "Component C2 中 dueDate 不匹配或 status 非 open 则不得 0.10 分", + "Component C3 中关联对象或负责人不匹配则不得 0.10 分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求分别拉取 linkedin_mock 和 salesforce_mock 的 initial_state 与 current_state。若任一环节失败则直接返回 0.0。评分时仅对比当前状态相对于初始状态的新增内容:Component A 检查 LinkedIn 新增的 connectionRequests,寻找从 user_admin 到 user_5 的 pending 请求,并验证备注包含 Priya/Nair 人名及 NorthBeam/Engineering 等上下文;Component B 检查 Salesforce 新增的 leads,先确认恰好有一个 Priya Nair @ NorthBeam Logistics 的 lead,再逐项验证其 source 为 LinkedIn、rating 为 Warm、status 为 New 且 ownerId 为 user-1、title 为 VP of Engineering;Component C 检查 Salesforce 新增的 activities,寻找 type 为 task 且 subject 提及向 Priya/Nair 发送介绍邮件的任务,验证其 dueDate 为当前日期+2 天、status 为开放状态,并且 relatedToType 为 lead、relatedToId 指向 B1 的新 lead、assignedToId 为 user-1。各子项分值累加,最终钳制在 1.0 以内输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: sdr_source_lead_001`\n2. **Domain**: `Domain: mock_websites`\n3. **Summary**: 验证将 LinkedIn 潜在客户 Priya Nair 导入 Salesforce 并创建跟进任务的行为\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `linkedin_mock` (通过 `http://28.7.186.212:8157`)\n - `salesforce_mock` (通过 `http://28.7.186.212:8175`)\n\n6. **Scoring components**:\n - Component A (0.30): LinkedIn 向 Priya Nair 发送连接请求并附带个性化备注\n - A1 (0.30): 新的待处理请求,fromUserId=user_admin, toUserId=user_5,且 note 非空并个性化\n - Component B (0.40): Salesforce 新建 Priya Nair 潜在客户\n - B1 (0.10): 恰好一个 NEW 的 Priya Nair @ NorthBeam Logistics 潜在客户\n - B2 (0.10): source == 'LinkedIn'\n - B3 (0.10): rating == 'Warm'\n - B4 (0.10): status == 'New' AND ownerId == 'user-1' AND title == 'VP of Engineering'\n - Component C (0.30): Salesforce 跟进任务\n - C1 (0.10): 新的 task,subject 提及向 Priya/Nair 发送介绍邮件\n - C2 (0.10): dueDate 是奖励运行时的本地日期两天后,且状态为 open/pending\n - C3 (0.10): relatedToType 为 'lead' 指向新创建的 lead,且 assignedToId 为 'user-1'\n\n7. **Score aggregation**: 各组件分数相加,最终用 `min(total_score, 1.0)` 钳制到上限 1.0,并四舍五入到 4 位小数\n\n8. **Failure modes**:\n - 无法从 `/tmp/task_web_sid` 读取 sid -> 退出,0.0\n - 无法从 LinkedIn 或 Salesforce mock 获取状态 -> 退出,0.0\n - current_state 缺失 -> 退出,0.0\n - 各组件检查失败会打印 FAIL 但不退出,只是不得分\n - 异常会被捕获并打印 ERROR,但不退出\n\n9. **Scoring logic explanation**: 需要详细说明执行顺序:\n - 读取 sid\n - 获取 LinkedIn 和 Salesforce 的 initial_state 和 current_state\n - 对比初始状态和当前状态,找出新增内容\n - Component A: 检查 LinkedIn 新增连接请求,验证 from/to 和个性化备注\n - Component B: 检查 Salesforce 新增 leads,找出 Priya Nair 的 lead,验证 source/rating/status/owner/title\n - Component C: 检查 Salesforce 新增 activities,找出 task 类型且 subject 匹配,验证 dueDate、状态、关联 lead 和负责人\n - 汇总得分,钳制到 1.0\n\n10. **Confidence**: 1.0,因为代码逻辑非常清晰\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"sdr_source_lead_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证将 LinkedIn 潜在客户 Priya Nair 导入 Salesforce 并创建跟进任务的任务行为\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"linkedin_mock\",\n \"salesforce_mock\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component A — LinkedIn connection request\",\n \"weight\": 0.3,\n \"description\": \"验证向 Priya Nair 发送了新的 LinkedIn 连接请求并附带个性化备注\",\n \"check_logic\": \"对比 initial_state 与 current_state 中的 connectionRequests,筛选出 id 不在初始状态的新请求;检查是否存在 fromUserId='user_admin'、toUserId='user_5'、status='pending' 的请求;调用 is_personalized_note() 检查备注是否包含 Priya/Nair 的人名以及 NorthBeam/Logistics 公司名或 engineering 等上下文关键词\",\n \"pass_condition\": \"存在一个新的待处理连接请求,从 user_admin 发给 user_5,且备注非空并包含 Priya/Nair 以及公司或工程上下文信息\"\n },\n {\n \"name\": \"Component B1 — New lead existence\",\n \"weight\": 0.1,\n \"description\": \"验证 Salesforce 中恰好新增了一个可识别为 Priya Nair @ NorthBeam Logistics 的 lead\",\n \"check_logic\": \"对比 initial_state 与 current_state 中的 leads,筛选 leadId 不在初始状态的新 lead;调用 is_priya_lead() 检查 firstName='priya'、lastName='nair' 且 company 包含 'northbeam';要求恰好 1 个匹配\",\n \"pass_condition\": \"新增 leads 中恰好有 1 个匹配 Priya Nair @ NorthBeam Logistics\"\n },\n {\n \"name\": \"Component B2 — Lead source\",\n \"weight\": 0.1,\n \"description\": \"验证新 lead 的来源为 LinkedIn\",\n \"check_logic\": \"检查 B1 中找到的 new_lead 的 source 字段(转小写并去除空白)是否等于 'linkedin'\",\n \"pass_condition\": \"source 字段等于 'linkedin'\"\n },\n {\n \"name\": \"Component B3 — Lead rating\",\n \"weight\": 0.1,\n \"description\": \"验证新 lead 的评级为 Warm\",\n \"check_logic\": \"检查 new_lead 的 rating 字段(转小写并去除空白)是否等于 'warm'\",\n \"pass_condition\": \"rating 字段等于 'warm'\"\n },\n {\n \"name\": \"Component B4 — Lead status, owner and title\",\n \"weight\": 0.1,\n \"description\": \"验证新 lead 的状态为 New、负责人为 user-1、职称为 VP of Engineering\",\n \"check_logic\": \"检查 status 转小写后等于 'new';ownerId 去除空白后等于 'user-1';title 经 is_vp_engineering_title() 正则匹配 VP/Engineering 模式\",\n \"pass_condition\": \"status='new' 且 ownerId='user-1' 且 title 匹配 VP of Engineering\"\n },\n {\n \"name\": \"Component C1 — Follow-up task subject\",\n \"weight\": 0.1,\n \"description\": \"验证 Salesforce 中新增了 subject 提及向 Priya/Nair 发送介绍邮件的 task\",\n \"check_logic\": \"对比 initial_state 与 current_state 中的 activities,筛选 activityId 不在初始状态的新活动;查找 type='task' 且 subject 经 is_intro_email_subject() 检查包含 'priya' 或 'nair',以及 'intro'/'introduction'/'email'/'mail' 等词\",\n \"pass_condition\": \"存在新的 task 类型活动,subject 同时提及 Priya/Nair 和介绍/邮件相关词汇\"\n },\n {\n \"name\": \"Component C2 — Task due date and status\",\n \"weight\": 0.1,\n \"description\": \"验证任务截止日期为运行时本地日期两天后且状态为开放/待处理\",\n \"check_logic\": \"解析 task 的 dueDate(支持 ISO 格式和多种分隔符),与 datetime.now().date() + timedelta(days=2) 的年月日比较;检查 status 经 is_open_task_status() 匹配 'open'/'pending'/'not started'/'new'/'todo'/'to do'\",\n \"pass_condition\": \"dueDate 的年月日等于当前日期+2 天,且 status 为 open/pending/not started/new/todo/to do\"\n },\n {\n \"name\": \"Component C3 — Task relation and assignment\",\n \"weight\": 0.1,\n \"description\": \"验证任务关联到新建的 lead 且指派给 user-1\",\n \"check_logic\": \"检查 task 的 relatedToType 转小写后等于 'lead';assignedToId 等于 'user-1';relatedToId 等于 B1 中新建 lead 的 leadId\",\n \"pass_condition\": \"relatedToType='lead' 且 assignedToId='user-1' 且 relatedToId 与 B1 的新 leadId 一致\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各子组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"无法从 /tmp/task_web_sid 读取 sid 时打印 CRITICAL 并返回 0.0\",\n \"无法从 linkedin_mock 或 salesforce_mock 拉取状态时返回 0.0\",\n \"current_state 缺失时返回 0.0\",\n \"Component A 中无新的 user_admin->user_5 待处理请求或备注不个性化则不得 0.30 分\",\n \"Component B1 中无新增 Priya Nair lead 或数量不为 1 则不得 0.10 分(数量>1 时仍继续评估 B2-B4)\",\n \"Component B2-B4 中任一字段不匹配则对应子项不得分\",\n \"Component C1 中无匹配的新 task 则 C1-C3 均不得分\",\n \"Component C2 中 dueDate 不匹配或 status 非 open 则不得 0.10 分\",\n \"Component C3 中关联对象或负责人不匹配则不得 0.10 分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求分别拉取 linkedin_mock 和 salesforce_mock 的 initial_state 与 current_state。若任一环节失败则直接返回 0.0。评分时仅对比当前状态相对于初始状态的新增内容:Component A 检查 LinkedIn 新增的 connectionRequests,寻找从 user_admin 到 user_5 的 pending 请求,并验证备注包含 Priya/Nair 人名及 NorthBeam/Engineering 等上下文;Component B 检查 Salesforce 新增的 leads,先确认恰好有一个 Priya Nair @ NorthBeam Logistics 的 lead,再逐项验证其 source 为 LinkedIn、rating 为 Warm、status 为 New 且 ownerId 为 user-1、title 为 VP of Engineering;Component C 检查 Salesforce 新增的 activities,寻找 type 为 task 且 subject 提及向 Priya/Nair 发送介绍邮件的任务,验证其 dueDate 为当前日期+2 天、status 为开放状态,并且 relatedToType 为 lead、relatedToId 指向 B1 的新 lead、assignedToId 为 user-1。各子项分值累加,最终钳制在 1.0 以内输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查 JSON 格式:\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- 没有 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 没有额外解释\n\n确认 weight 总和:0.3 + 0.1*4 + 0.1*3 = 0.3 + 0.4 + 0.3 = 1.0,正确。\n\n确认字段名保留原样:fromUserId, toUserId, user_admin, user_5, connectionRequests, leadId, source, rating, status, ownerId, title, activities, activityId, type, subject, dueDate, relatedToType, assignedToId, relatedToId 等。\n\n确认 data_sources 包含:/tmp/task_web_sid, linkedin_mock, salesforce_mock。\n\n确认 is_placeholder 为 false。\n\n确认 summary 和 scoring_logic_explanation 为中文。\n\n看起来没问题。 {\"task_id\":\"sdr_source_lead_001\",\"domain\":\"mock_websites\",\"summary\":\"验证将 LinkedIn 潜在客户 Priya Nair 导入 Salesforce 并创建跟进任务的任务行为\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"linkedin_mock\",\"salesforce_mock\"],\"scoring_components\":[{\"name\":\"Component A — LinkedIn connection request\",\"weight\":0.3,\"description\":\"验证向 Priya Nair 发送了新的 LinkedIn 连接请求并附带个性化备注\",\"check_logic\":\"对比 initial_state 与 current_state 中的 connectionRequests,筛选 id 不在初始状态的新请求;检查是否存在 fromUserId='user_admin'、toUserId='user_5'、status='pending' 的请求;调用 is_personalized_note() 检查备注是否包含 Priya/Nair 人名以及 NorthBeam/Logistics 公司名或 engineering 等上下文关键词\",\"pass_condition\":\"存在一个新的待处理连接请求,从 user_admin 发给 user_5,且备注非空并包含 Priya/Nair 以及公司或工程上下文信息\"},{\"name\":\"Component B1 — New lead existence\",\"weight\":0.1,\"description\":\"验证 Salesforce 中恰好新增了一个可识别为 Priya Nair @ NorthBeam Logistics 的 lead\",\"check_logic\":\"对比 initial_state 与 current_state 中的 leads,筛选 leadId 不在初始状态的新 lead;调用 is_priya_lead() 检查 firstName='priya'、lastName='nair' 且 company 包含 'northbeam';要求恰好 1 个匹配\",\"pass_condition\":\"新增 leads 中恰好有 1 个匹配 Priya Nair @ NorthBeam Logistics\"},{\"name\":\"Component B2 — Lead source\",\"weight\":0.1,\"description\":\"验证新 lead 的来源为 LinkedIn\",\"check_logic\":\"检查 B1 中找到的 new_lead 的 source 字段(转小写并去除空白)是否等于 'linkedin'\",\"pass_condition\":\"source 字段等于 'linkedin'\"},{\"name\":\"Component B3 — Lead rating\",\"weight\":0.1,\"description\":\"验证新 lead 的评级为 Warm\",\"check_logic\":\"检查 new_lead 的 rating 字段(转小写并去除空白)是否等于 'warm'\",\"pass_condition\":\"rating 字段等于 'warm'\"},{\"name\":\"Component B4 — Lead status, owner and title\",\"weight\":0.1,\"description\":\"验证新 lead 的状态为 New、负责人为 user-1、职称为 VP of Engineering\",\"check_logic\":\"检查 status 转小写后等于 'new';ownerId 去除空白后等于 'user-1';title 经 is_vp_engineering_title() 正则匹配 VP/Engineering 模式\",\"pass_condition\":\"status='new' 且 ownerId='user-1' 且 title 匹配 VP of Engineering\"},{\"name\":\"Component C1 — Follow-up task subject\",\"weight\":0.1,\"description\":\"验证 Salesforce 中新增了 subject 提及向 Priya/Nair 发送介绍邮件的 task\",\"check_logic\":\"对比 initial_state 与 current_state 中的 activities,筛选 activityId 不在初始状态的新活动;查找 type='task' 且 subject 经 is_intro_email_subject() 检查包含 'priya' 或 'nair',以及 'intro'/'introduction'/'email'/'mail' 等词\",\"pass_condition\":\"存在新的 task 类型活动,subject 同时提及 Priya/Nair 和介绍/邮件相关词汇\"},{\"name\":\"Component C2 — Task due date and status\",\"weight\":0.1,\"description\":\"验证任务截止日期为运行时本地日期两天后且状态为开放/待处理\",\"check_logic\":\"解析 task 的 dueDate(支持 ISO 格式和多种分隔符),与 datetime.now().date() + timedelta(days=2) 的年月日比较;检查 status 经 is_open_task_status() 匹配 'open'/'pending'/'not started'/'new'/'todo'/'to do'\",\"pass_condition\":\"dueDate 的年月日等于当前日期+2 天,且 status 为 open/pending/not started/new/todo/to do\"},{\"name\":\"Component C3 — Task relation and assignment\",\"weight\":0.1,\"description\":\"验证任务关联到新建的 lead 且指派给 user-1\",\"check_logic\":\"检查 task 的 relatedToType 转小写后等于 'lead';assignedToId 等于 'user-1';relatedToId 等于 B1 中新建 lead 的 leadId\",\"pass_condition\":\"relatedToType='lead' 且 assignedToId='user-1' 且 relatedToId 与 B1 的新 leadId 一致\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各子组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 sid 时打印 CRITICAL 并返回 0.0\",\"无法从 linkedin_mock 或 salesforce_mock 拉取状态时返回 0.0\",\"current_state 缺失时返回 0.0\",\"Component A 中无新的 user_admin->user_5 待处理请求或备注不个性化则不得 0.30 分\",\"Component B1 中无新增 Priya Nair lead 或数量不为 1 则不得 0.10 分(数量>1 时仍继续评估 B2-B4)\",\"Component B2-B4 中任一字段不匹配则对应子项不得分\",\"Component C1 中无匹配的新 task 则 C1-C3 均不得分\",\"Component C2 中 dueDate 不匹配或 status 非 open 则不得 0.10 分\",\"Component C3 中关联对象或负责人不匹配则不得 0.10 分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求分别拉取 linkedin_mock 和 salesforce_mock 的 initial_state 与 current_state。若任一环节失败则直接返回 0.0。评分时仅对比当前状态相对于初始状态的新增内容:Component A 检查 LinkedIn 新增的 connectionRequests,寻找从 user_admin 到 user_5 的 pending 请求,并验证备注包含 Priya/Nair 人名及 NorthBeam/Engineering 等上下文;Component B 检查 Salesforce 新增的 leads,先确认恰好有一个 Priya Nair @ NorthBeam Logistics 的 lead,再逐项验证其 source 为 LinkedIn、rating 为 Warm、status 为 New 且 ownerId 为 user-1、title 为 VP of Engineering;Component C 检查 Salesforce 新增的 activities,寻找 type 为 task 且 subject 提及向 Priya/Nair 发送介绍邮件的任务,验证其 dueDate 为当前日期+2 天、status 为开放状态,并且 relatedToType 为 lead、relatedToId 指向 B1 的新 lead、assignedToId 为 user-1。各子项分值累加,最终钳制在 1.0 以内输出。\",\"confidence\":1.0}" +}