diff --git a/ae_pipeline_review_004__long/_cua_gym_vm_bridge.sh b/ae_pipeline_review_004__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ae_pipeline_review_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/ae_pipeline_review_004__long/initial_setup.py b/ae_pipeline_review_004__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..244c175ef6c7a08ab2be759a65162a69ab79af24 --- /dev/null +++ b/ae_pipeline_review_004__long/initial_setup.py @@ -0,0 +1,799 @@ +""" +Initial Setup: T05_salesforce_oppty_followups — Pipeline Review sync into Salesforce +Task ID: ae_pipeline_review_004__long +Mocks: salesforce_mock,google_sheets_mock,slack_mock + +The 'Pipeline Review' Google Sheet lists opportunities (rows 2+: +OppName, Account, Amount, Stage, CloseDate). For each row the agent must find +the matching Salesforce Opportunity by NAME and apply the decision rules: + - Stage 'Closed Won' -> SF stage 'Closed Won' + Task 'Kickoff: ' (Status 'Not Started') + + reassign the opportunity Owner to 'Morgan Avery' (onboarding lead) + - Stage 'Closed Lost' -> SF stage 'Closed Lost' (no task, owner unchanged) + - Stage 'Negotiation' AND Amount >= 50000 -> SF stage 'Negotiation' + Task 'Exec review: ' (owner unchanged) + - all other rows -> leave the SF opportunity UNCHANGED + - rows whose OppName has NO matching SF opportunity are SKIPPED +Then create a new Slack channel named 'backup', export the Salesforce +Opportunities report and the 'Pipeline Review' sheet to CSV, and upload BOTH +CSV files into the 'backup' channel. + +The opportunity STAGE is changed from the opportunity's own page (the stage path), +the follow-up TASK is created from the opportunity's Activity timeline, and the +OWNER reassignment is a bulk action that only appears once an opportunity row is +selected in the list -- all three are controls the agent has to discover. + +After syncing, the agent must create a new Slack channel named 'backup', export the +Salesforce Opportunities report to CSV and the 'Pipeline Review' sheet to CSV, and +upload BOTH CSV files into the 'backup' channel as a pipeline backup. + +Ground-truth (answer key) is PRECOMPUTED below and embedded into initial_state +so reward.py is the sole source of truth: + - google_sheets._task_adapter.task_sheets['Pipeline Review'] (source rows) + - google_sheets._task_adapter.expected (per-row decision: matched/final_stage/task_subject) + - google_sheets._task_adapter.matched_count == n + - salesforce._task_adapter.expected / .expected_by_name / .matched_count (mirror, co-located with the SF live state reward reads) + - slack._task_adapter.backup_channel == 'backup' and .required_csv_count == 2 +""" +import datetime +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --------------------------------------------------------------------------- +# sid +# --------------------------------------------------------------------------- +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 = '60c91d2c-31b7-490f-bc00-1317ca378c29' +SHEET_NAME = 'Pipeline Review' +HEADERS = ['OppName', 'Account', 'Amount', 'Stage', 'CloseDate'] + +# Owner reassignment target for Closed-Won opps (the "onboarding lead"). +# Opportunities are seeded owned by 'U1'; Closed-Won rows must end owned by U4. +SEEDED_OWNER_ID = 'U1' +ONBOARDING_OWNER_ID = 'U4' +ONBOARDING_OWNER_NAME = 'Morgan Avery' + +# --------------------------------------------------------------------------- +# Date helpers (relative to "today" so CloseDate values are realistic) +# --------------------------------------------------------------------------- +TODAY = datetime.date(2026, 6, 23) + + +def fdate(days_ahead): + return (TODAY + datetime.timedelta(days=days_ahead)).isoformat() + + +# Stage -> default probability for a Salesforce opportunity. +STAGE_PROB = { + 'Prospecting': 10, + 'Qualification': 25, + 'Needs Analysis': 35, + 'Value Proposition': 50, + 'Proposal': 65, + 'Negotiation': 80, + 'Closed Won': 100, + 'Closed Lost': 0, +} + +# --------------------------------------------------------------------------- +# Single source of truth for the scenario. Everything else (sheet cells, +# SF opportunities, the expected answer key, n) is DERIVED from this list, so +# the visible data and the embedded key can never drift apart. +# +# Each spec: +# opp_name : OppName in the sheet (== SF Opportunity.name when matched) +# account : Account in the sheet (drives the Task subject) +# amount : Amount in the sheet +# sheet_stage : Stage in the sheet (the DESIRED decision input) +# close_off : CloseDate = today + close_off days +# matched : True -> a SF opportunity with this name is pre-seeded +# False -> NO SF opportunity (agent must skip this row) +# sf_initial : the SF opportunity's stage AT INJECTION (only if matched). +# Chosen != the final stage for rows that require a change so +# the change is observable; == final stage for unchanged rows. +# --------------------------------------------------------------------------- +ROW_SPECS = [ + # --- Branch: Closed Won (set stage + create Kickoff task) --------------- + dict(opp_name='Acme Renewal', account='Acme Corp', amount=120000, + sheet_stage='Closed Won', close_off=7, matched=True, sf_initial='Proposal'), + # --- Branch: Closed Lost (set stage, no task) ---------------------------- + dict(opp_name='Globex Expansion', account='Globex Inc', amount=85000, + sheet_stage='Closed Lost', close_off=12, matched=True, sf_initial='Negotiation'), + # --- Branch: Negotiation & Amount >= 50000 (set stage + Exec review) ----- + dict(opp_name='Initech Platform', account='Initech LLC', amount=75000, + sheet_stage='Negotiation', close_off=18, matched=True, sf_initial='Qualification'), + # --- Branch: Negotiation & Amount < 50000 (unchanged; the 30000 case) ---- + dict(opp_name='Umbrella Rollout', account='Umbrella Corp', amount=30000, + sheet_stage='Negotiation', close_off=24, matched=True, sf_initial='Value Proposition'), + # --- Branch: Closed Won (second one, observe Negotiation -> Closed Won) --- + dict(opp_name='Soylent Upsell', account='Soylent Co', amount=60000, + sheet_stage='Closed Won', close_off=9, matched=True, sf_initial='Negotiation'), + # --- Branch: Closed Lost (second one) ------------------------------------ + dict(opp_name='Stark Integration', account='Stark Industries', amount=95000, + sheet_stage='Closed Lost', close_off=15, matched=True, sf_initial='Proposal'), + # --- Branch: other stage 'Proposal' (unchanged) -------------------------- + dict(opp_name='Wayne Migration', account='Wayne Enterprises', amount=40000, + sheet_stage='Proposal', close_off=30, matched=True, sf_initial='Proposal'), + # --- Branch: other stage 'Prospecting' (unchanged) ----------------------- + dict(opp_name='Hooli Renewal', account='Hooli Inc', amount=150000, + sheet_stage='Prospecting', close_off=40, matched=True, sf_initial='Prospecting'), + # --- No matching SF opportunity (must be SKIPPED) ------------------------ + dict(opp_name='Pied Piper Deal', account='Pied Piper', amount=50000, + sheet_stage='Closed Won', close_off=20, matched=False, sf_initial=None), + dict(opp_name='Vehement Capital', account='Vehement Partners', amount=70000, + sheet_stage='Negotiation', close_off=22, matched=False, sf_initial=None), +] + + +def decide(spec): + """Apply the task's decision rules -> (final_stage, task_subject, task_status, + task_status_required, requires_change, requires_task). + + final_stage is the stage the SF opp must END at; for matched rows that do + NOT require a change this equals sf_initial (so reward checks 'no drift'). + task_status_required encodes that the instruction only mandates a Status + ('Not Started') for the Kickoff task; the Exec review task's subject is the + binding requirement (status defaults to the natural 'Not Started'). + """ + stage = spec['sheet_stage'] + amount = spec['amount'] + initial = spec['sf_initial'] + account = spec['account'] + + if stage == 'Closed Won': + final_stage = 'Closed Won' + task_subject = f'Kickoff: {account}' + task_status = 'Not Started' + task_status_required = True + requires_task = True + final_owner = ONBOARDING_OWNER_ID # Closed Won -> reassign owner + elif stage == 'Closed Lost': + final_stage = 'Closed Lost' + task_subject = None + task_status = None + task_status_required = False + requires_task = False + final_owner = SEEDED_OWNER_ID # owner unchanged + elif stage == 'Negotiation' and amount >= 50000: + final_stage = 'Negotiation' + task_subject = f'Exec review: {account}' + task_status = 'Not Started' + task_status_required = False + requires_task = True + final_owner = SEEDED_OWNER_ID # owner unchanged + else: + # all other rows -> leave the SF opportunity unchanged + final_stage = initial + task_subject = None + task_status = None + task_status_required = False + requires_task = False + final_owner = SEEDED_OWNER_ID # owner unchanged + + requires_change = bool(initial is not None and final_stage != initial) + requires_owner_change = bool(final_owner != SEEDED_OWNER_ID) + return (final_stage, task_subject, task_status, + task_status_required, requires_change, requires_task, + final_owner, requires_owner_change) + + +# --------------------------------------------------------------------------- +# PRECOMPUTE: expected answer key + matched count (n) + SF opportunities +# --------------------------------------------------------------------------- +expected = [] # full per-row key (incl. unmatched rows) +sf_opportunities = [] # matched rows -> a seeded SF opportunity +sf_accounts = [] # one account per matched opp + decoys +sheet_rows_dict = [] # for _task_adapter.task_sheets + +acc_counter = 0 +opp_counter = 0 +for spec in ROW_SPECS: + (final_stage, task_subject, task_status, task_status_required, + requires_change, requires_task, final_owner, requires_owner_change) = decide(spec) + + opportunity_id = None + account_id = None + if spec['matched']: + opp_counter += 1 + acc_counter += 1 + opportunity_id = f'opp-{opp_counter}' + account_id = f'acc-{acc_counter}' + sf_accounts.append({ + 'accountId': account_id, + 'name': spec['account'], + 'type': 'Customer', + 'industry': 'Technology', + 'revenue': spec['amount'] * 10, + 'employees': 200 + opp_counter * 25, + 'ownerId': 'U1', + 'billingStreet': '', 'billingCity': '', 'billingState': '', + 'billingZip': '', 'billingCountry': 'United States', + 'shippingStreet': '', 'shippingCity': '', 'shippingState': '', + 'shippingZip': '', 'shippingCountry': 'United States', + 'phone': '', 'website': '', 'description': '', + 'createdDate': '2026-05-01T00:00:00Z', + 'modifiedDate': '2026-05-01T00:00:00Z', + }) + sf_opportunities.append({ + 'opportunityId': opportunity_id, + 'name': spec['opp_name'], + 'accountId': account_id, + 'contactId': '', + 'amount': spec['amount'], + 'closeDate': fdate(spec['close_off']), + 'stage': spec['sf_initial'], + 'probability': STAGE_PROB.get(spec['sf_initial'], 10), + 'ownerId': 'U1', + 'type': 'Existing Customer - Upgrade', + 'leadSource': 'Partner', + 'description': '', + 'createdDate': '2026-05-05T00:00:00Z', + 'modifiedDate': '2026-05-05T00:00:00Z', + }) + + expected.append({ + 'oppName': spec['opp_name'], + 'account': spec['account'], + 'amount': spec['amount'], + 'sheet_stage': spec['sheet_stage'], + 'matched': spec['matched'], + 'opportunityId': opportunity_id, + 'initial_stage': spec['sf_initial'], + 'final_stage': final_stage, + 'task_subject': task_subject, + 'task_status': task_status, + 'task_status_required': task_status_required, + 'requires_change': requires_change, + 'requires_task': requires_task, + 'initial_owner': SEEDED_OWNER_ID if spec['matched'] else None, + 'final_owner': final_owner if spec['matched'] else None, + 'requires_owner_change': requires_owner_change if spec['matched'] else False, + }) + + sheet_rows_dict.append({ + 'OppName': spec['opp_name'], + 'Account': spec['account'], + 'Amount': spec['amount'], + 'Stage': spec['sheet_stage'], + 'CloseDate': fdate(spec['close_off']), + }) + +matched_count = sum(1 for e in expected if e['matched']) # n +expected_message = f'Synced {matched_count} opportunities' +expected_by_name = { + e['oppName']: { + 'final_stage': e['final_stage'], + 'task_subject': e['task_subject'], + 'task_status': e['task_status'], + 'task_status_required': e['task_status_required'], + 'requires_change': e['requires_change'], + 'requires_task': e['requires_task'], + 'initial_owner': e['initial_owner'], + 'final_owner': e['final_owner'], + 'requires_owner_change': e['requires_owner_change'], + } + for e in expected if e['matched'] +} + +# Decoy SF opportunities NOT present in the sheet (watermark; never graded). +sf_accounts.append({ + 'accountId': 'acc-d1', 'name': 'Cyberdyne Systems', 'type': 'Prospect', + 'industry': 'Robotics', 'revenue': 9000000, 'employees': 800, 'ownerId': 'U2', + 'billingStreet': '', 'billingCity': '', 'billingState': '', 'billingZip': '', + 'billingCountry': 'United States', 'shippingStreet': '', 'shippingCity': '', + 'shippingState': '', 'shippingZip': '', 'shippingCountry': 'United States', + 'phone': '', 'website': '', 'description': '', + 'createdDate': '2026-05-01T00:00:00Z', 'modifiedDate': '2026-05-01T00:00:00Z', +}) +sf_accounts.append({ + 'accountId': 'acc-d2', 'name': 'Tyrell Corporation', 'type': 'Customer', + 'industry': 'Biotech', 'revenue': 25000000, 'employees': 1200, 'ownerId': 'U3', + 'billingStreet': '', 'billingCity': '', 'billingState': '', 'billingZip': '', + 'billingCountry': 'United States', 'shippingStreet': '', 'shippingCity': '', + 'shippingState': '', 'shippingZip': '', 'shippingCountry': 'United States', + 'phone': '', 'website': '', 'description': '', + 'createdDate': '2026-05-01T00:00:00Z', 'modifiedDate': '2026-05-01T00:00:00Z', +}) +sf_opportunities.append({ + 'opportunityId': 'opp-d1', 'name': 'Cyberdyne Support Renewal', 'accountId': 'acc-d1', + 'contactId': '', 'amount': 22000, 'closeDate': fdate(55), 'stage': 'Qualification', + 'probability': 25, 'ownerId': 'U2', 'type': 'Existing Customer - Renewal', + 'leadSource': 'Web', 'description': '', 'createdDate': '2026-05-05T00:00:00Z', + 'modifiedDate': '2026-05-05T00:00:00Z', +}) +sf_opportunities.append({ + 'opportunityId': 'opp-d2', 'name': 'Tyrell New Business', 'accountId': 'acc-d2', + 'contactId': '', 'amount': 310000, 'closeDate': fdate(70), 'stage': 'Proposal', + 'probability': 65, 'ownerId': 'U3', 'type': 'New Business', + 'leadSource': 'Referral', 'description': '', 'createdDate': '2026-05-05T00:00:00Z', + 'modifiedDate': '2026-05-05T00:00:00Z', +}) + +# Decoy activities — present (Rule: "activities array present") but NONE has a +# subject equal to any expected Kickoff/Exec-review subject, and none is tied to +# a graded opportunity, so they cannot create false positives at injection. +sf_activities = [ + {'activityId': 'activity-1', 'type': 'event', 'subject': 'Discovery call — Cyberdyne Systems', + 'status': 'Completed', 'priority': 'Normal', + 'startDateTime': '2026-06-18T15:00:00Z', 'endDateTime': '2026-06-18T15:30:00Z', + 'relatedToType': 'opportunity', 'relatedToId': 'opp-d1', 'assignedToId': 'U2', + 'description': ''}, + {'activityId': 'activity-2', 'type': 'task', 'subject': 'Send NDA to Tyrell Corporation', + 'status': 'Completed', 'priority': 'High', 'dueDate': fdate(-2), + 'relatedToType': 'opportunity', 'relatedToId': 'opp-d2', 'assignedToId': 'U3', + 'description': ''}, +] + +# --------------------------------------------------------------------------- +# Salesforce users +# --------------------------------------------------------------------------- +sf_users = [ + {'userId': 'U1', 'firstName': 'John', 'lastName': 'Smith', 'email': 'john.smith@company.com', + 'phone': '(555) 123-4567', 'title': 'RevOps Manager', 'department': 'Sales', 'role': 'Manager', + 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York', + 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'U2', 'firstName': 'Sarah', 'lastName': 'Chen', 'email': 'sarah.chen@company.com', + 'phone': '', 'title': 'Account Executive', 'department': 'Sales', 'role': 'Rep', + 'avatar': 'https://i.pravatar.cc/150?u=U2', 'timezone': 'America/New_York', + 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'U3', 'firstName': 'Diego', 'lastName': 'Ruiz', 'email': 'diego.ruiz@company.com', + 'phone': '', 'title': 'Account Executive', 'department': 'Sales', 'role': 'Rep', + 'avatar': 'https://i.pravatar.cc/150?u=U3', 'timezone': 'America/Chicago', + 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'U4', 'firstName': 'Morgan', 'lastName': 'Avery', 'email': 'morgan.avery@company.com', + 'phone': '', 'title': 'Customer Onboarding Lead', 'department': 'Customer Success', 'role': 'Manager', + 'avatar': 'https://i.pravatar.cc/150?u=U4', 'timezone': 'America/New_York', + 'locale': 'en-US', 'theme': 'lightning'}, +] + +salesforce_state = { + 'user': sf_users[0], + 'users': sf_users, + 'leads': [], + 'accounts': sf_accounts, + 'contacts': [], + 'opportunities': sf_opportunities, + 'cases': [], + 'activities': sf_activities, + 'chatterPosts': [], + 'files': [], + 'dashboards': [], + 'following': [], + 'recentlyViewed': [], + 'dismissedNotifications': [], + '_task_adapter': { + 'task_id': TASK_ID, + 'variant': 'eval', + 'matched_count': matched_count, + 'expected': expected, + 'expected_by_name': expected_by_name, + 'onboarding_owner_id': ONBOARDING_OWNER_ID, + 'onboarding_owner_name': ONBOARDING_OWNER_NAME, + 'seeded_owner_id': SEEDED_OWNER_ID, + }, +} + +# --------------------------------------------------------------------------- +# Google Sheets — 'Pipeline Review' workbook +# --------------------------------------------------------------------------- +COL_LETTERS = ['A', 'B', 'C', 'D', 'E'] + + +def header_cell(text): + return {'value': text, 'formula': text, 'computed': text, + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}} + + +def text_cell(text): + return {'value': text, 'formula': text, 'computed': text} + + +def num_cell(n): + return {'value': str(n), 'formula': str(n), 'computed': n} + + +sheet_data = {} +# Header row (row 1) +for col, head in zip(COL_LETTERS, HEADERS): + sheet_data[f'{col}1'] = header_cell(head) +# Data rows (rows 2..N) +for idx, row in enumerate(sheet_rows_dict): + r = idx + 2 + sheet_data[f'A{r}'] = text_cell(row['OppName']) + sheet_data[f'B{r}'] = text_cell(row['Account']) + sheet_data[f'C{r}'] = num_cell(row['Amount']) + sheet_data[f'D{r}'] = text_cell(row['Stage']) + sheet_data[f'E{r}'] = text_cell(row['CloseDate']) + +google_sheets_state = { + 'id': 'workbook_t05_pipeline_review', + 'title': 'Pipeline Review', + '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': SHEET_NAME, + 'data': sheet_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': 'rows_dict', + 'task_id': TASK_ID, + 'variant': 'eval', + 'task_sheets': {SHEET_NAME: {'headers': HEADERS, 'rows': sheet_rows_dict}}, + 'headers_by_sheet': {SHEET_NAME: HEADERS}, + 'sheet_names': [SHEET_NAME], + 'expected': expected, + 'expected_by_name': expected_by_name, + 'matched_count': matched_count, + 'expected_message': expected_message, + }, +} + +# --------------------------------------------------------------------------- +# Slack — the 'backup' channel must NOT exist yet (Rule 3); the agent creates +# it and uploads the two CSVs. Pre-existing channels are decoy chatter only. +# --------------------------------------------------------------------------- +slack_state = { + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements and work-based matters', 'topic': 'Welcome to Acme Corp!', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'announcements', 'name': 'announcements', 'description': 'Important company updates', 'topic': 'Read-mostly. Big news only.', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'random', 'name': 'random', 'description': 'Non-work banter and watercooler chat', 'topic': 'Coffee, memes, weekend plans', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_3', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'revops', 'name': 'revops', 'description': 'Revenue operations — pipeline hygiene and sync confirmations', 'topic': 'Drop a note when you finish a pipeline sync', 'isPrivate': False, 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1', 'createdAt': '2026-06-04T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'RevOps Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + 'users': [ + {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'RevOps Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya', 'email': 'maya.lindqvist@company.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'People Ops', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'Europe/Stockholm'}, + {'userId': 'user_3', 'fullName': 'Hiroshi Tanabe', 'displayName': 'Hiroshi', 'email': 'hiroshi.tanabe@company.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Engineering', 'status': 'away', 'statusMessage': 'In a meeting', 'statusEmoji': ':calendar:', 'timeZone': 'Asia/Tokyo'}, + {'userId': 'user_4', 'fullName': 'Olivia Becker', 'displayName': 'Olivia', 'email': 'olivia.becker@company.com', 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Marketing', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + ], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': 'Morning everyone — reminder that the office will be closed next Friday for the holiday.', 'timestamp': '2026-06-18T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_2', 'senderId': 'user_4', 'content': 'Thanks Maya! Long weekend incoming :tada:', 'timestamp': '2026-06-18T13:05:00Z', 'reactions': [{'emoji': '\U0001F389', 'users': ['user_1', 'user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_3', 'senderId': 'user_3', 'content': 'Quick heads-up: the staging environment is being rebuilt today, expect slowness 10:00–11:00 JST.', 'timestamp': '2026-06-19T01:12:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_4', 'senderId': 'user_1', 'content': "Got it, I'll hold off on the pipeline review until after.", 'timestamp': '2026-06-19T01:15:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'announcements': [ + {'messageId': 'm_a_1', 'senderId': 'user_2', 'content': 'Q2 all-hands has been scheduled for June 28 at 10:00 PT. Calendar invite goes out today.', 'timestamp': '2026-06-17T16:30:00Z', 'reactions': [{'emoji': '✅', 'users': ['user_1', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_a_2', 'senderId': 'user_2', 'content': 'New laptop refresh policy is live on the People Ops wiki. TL;DR: 3-year cycle, request via the IT portal.', 'timestamp': '2026-06-19T09:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'random': [ + {'messageId': 'm_r_1', 'senderId': 'user_4', 'content': 'Anyone tried the new ramen place on 3rd? Verdict?', 'timestamp': '2026-06-18T18:50:00Z', 'reactions': [{'emoji': '\U0001F35C', 'users': ['user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_2', 'senderId': 'user_3', 'content': "10/10, get the spicy miso. Bring tissues though, it's no joke.", 'timestamp': '2026-06-18T18:55:00Z', 'reactions': [{'emoji': '\U0001F605', 'users': ['user_1', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_3', 'senderId': 'user_1', 'content': 'My cat has decided my keyboard is her new bed. Send help.', 'timestamp': '2026-06-19T08:20:00Z', 'reactions': [{'emoji': '\U0001F63A', 'users': ['user_2', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + # Decoy channel — not graded. The gradable artefact is the NEW 'backup' + # channel (created by the agent), which must be ABSENT at injection. + 'revops': [], + }, + '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', + 'backup_channel': 'backup', # agent must CREATE this channel (absent at injection) + 'required_csv_count': 2, # SF opportunities CSV + Pipeline Review sheet CSV + 'matched_count': matched_count, + }, +} + +# Rule 3 guard: the 'backup' channel must NOT exist at injection (gradable output absent). +assert not any(str(c.get('name', '')).strip().lower() == 'backup' for c in slack_state['channels']), \ + "'backup' channel must be absent at injection" + +# --------------------------------------------------------------------------- +# (url, state) — EXACT app_urls from task_config.json +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8175', salesforce_state), # salesforce_mock + ('http://28.7.184.198:8145', google_sheets_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}') + +print(f'Precomputed matched_count (n) = {matched_count}; ' + f'backup_channel = backup; required_csv_count = 2') + + +# 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_pipeline_review_004__long/reward.py b/ae_pipeline_review_004__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..11e5cd3d2ed4834d45ad2909c7f271199d68fdec --- /dev/null +++ b/ae_pipeline_review_004__long/reward.py @@ -0,0 +1,586 @@ +""" +Reward Script: T05 — Pipeline Review sync into Salesforce opportunities +Task ID: ae_pipeline_review_004__long +Mocks: salesforce_mock,google_sheets_mock,slack_mock +Scoring (positives sum to 1.0; leak penalties subtracted): + 0.40 stage set correctly over the rows that require a stage change. + 0.25 follow-up Task with exact Subject (+ Status 'Not Started' where required) + created for the requires_task rows (and absent on the others). + 0.20 owner reassigned to 'Morgan Avery' on the Closed-Won rows. + 0.15 Slack: a NEW 'backup' channel exists (absent at injection) and holds the + two exported CSV files as attachments (0.4 create + 0.6 for 2 CSVs). + penalties: stage-drift 0.15, forbidden-task 0.10, owner-drift 0.10 (each frac). +Answer key: read from salesforce.initial_state._task_adapter (.expected / .matched_count) + and slack.initial_state._task_adapter (.backup_channel / .required_csv_count). +""" +import copy +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 = {'salesforce': 'http://28.7.184.198:8175', '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 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): + if not isinstance(msg, dict): + return '' + return msg.get('content') or msg.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) if isinstance(slack_state, dict) else [] + target = None + for ch in channels: + if isinstance(ch, dict) and 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 target.get('id'), []) or [] + return [] + + +def _to_float(v): + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _sheet_rows(sheet): + if not isinstance(sheet, dict): + return [] + rows = sheet.get('rows', []) + return rows if isinstance(rows, list) else [] + + +def _sheet_tabs(sheets): + if isinstance(sheets, dict): + return sheets + if isinstance(sheets, list): + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') + if name: + out[name] = sh + return out + return {} + + +def _jaccard(a, b): + if not a and not b: + return 1.0 + u = a | b + return (len(a & b) / len(u)) if u else 1.0 + + +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 [], + # Preserve uploaded-file attachments (the 'backup' CSV uploads + # land here when a message is sent into messages[channelId]). + 'attachments': m.get('attachments') if isinstance(m.get('attachments'), 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 +# +# Answer key (precomputed at setup) lives in salesforce.initial_state._task_adapter: +# .expected -> list of 10 row dicts (8 matched + 2 unmatched). Each matched +# dict carries oppName, account, opportunityId, initial_stage, +# final_stage, task_subject, task_status, task_status_required, +# requires_change, requires_task. +# .matched_count -> n = 8. +# slack.initial_state._task_adapter: +# .backup_channel -> 'backup'; .required_csv_count -> 2. +# +# We score CURRENT state of each mock against this key. The salesforce materializer +# leaves opportunities/activities/_task_adapter untouched (no task_leads/task_accounts +# keys present), so we read them in their native shape. +# ============================================================================= +def reward(go): + sf = go('salesforce') + sf_init = sf.get('initial_state', {}) if isinstance(sf.get('initial_state'), dict) else {} + sf_cur = sf.get('current_state', {}) if isinstance(sf.get('current_state'), dict) else {} + adapter = sf_init.get('_task_adapter', {}) if isinstance(sf_init.get('_task_adapter'), dict) else {} + + expected = adapter.get('expected') if isinstance(adapter.get('expected'), list) else [] + matched = [e for e in expected if isinstance(e, dict) and e.get('matched')] + + n = adapter.get('matched_count') + if not isinstance(n, int) or n <= 0: + n = len(matched) + if n == 0 or not matched: + print('DEBUG_T05 no matched rows in answer key — cannot grade') + return 0.0 + + # --- current SF opportunities indexed by name --- + opp_by_name = {} + for o in (sf_cur.get('opportunities') or []): + if isinstance(o, dict): + opp_by_name[norm(o.get('name'))] = o + + # --- current SF activities: normalized subject -> list of normalized statuses --- + act_subjects = set() + subj_statuses = {} + for a in (sf_cur.get('activities') or []): + if not isinstance(a, dict): + continue + s = norm(a.get('subject')) + if not s: + continue + act_subjects.add(s) + subj_statuses.setdefault(s, []).append(norm(a.get('status'))) + + # Partition matched rows by what the answer key says each REQUIRES. + change_rows = [e for e in matched if e.get('requires_change')] + keep_stage_rows = [e for e in matched if not e.get('requires_change')] + task_rows = [e for e in matched if e.get('requires_task')] + notask_rows = [e for e in matched if not e.get('requires_task')] + owner_rows = [e for e in matched if e.get('requires_owner_change')] + keep_owner_rows = [e for e in matched if not e.get('requires_owner_change')] + + # ---- Component 1 (0.40): stage set correctly, scored ONLY over rows that + # require a stage change. Rows already at their target earn NO credit. ---- + stage_ok = 0 + for e in change_rows: + opp = opp_by_name.get(norm(e.get('oppName'))) + if opp is not None and norm(opp.get('stage')) == norm(e.get('final_stage')): + stage_ok += 1 + stage_frac = frac(stage_ok, len(change_rows)) if change_rows else 1.0 + + # stage-leak penalty: a must-keep-stage row whose stage drifted from injection. + stage_leak = 0 + for e in keep_stage_rows: + opp = opp_by_name.get(norm(e.get('oppName'))) + baseline = e.get('initial_stage') + if baseline is None: + baseline = e.get('final_stage') + if opp is not None and norm(opp.get('stage')) != norm(baseline): + stage_leak += 1 + stage_leak_frac = frac(stage_leak, len(keep_stage_rows)) if keep_stage_rows else 0.0 + + # ---- Component 2 (0.25): follow-up Task created, scored ONLY over rows that + # require a task. Creating a forbidden task on other rows is penalized. ---- + task_ok = 0 + for e in task_rows: + want_subj = norm(e.get('task_subject')) + present = bool(want_subj) and want_subj in act_subjects + if present and e.get('task_status_required'): + present = any(st == norm('Not Started') for st in subj_statuses.get(want_subj, [])) + if present: + task_ok += 1 + task_frac = frac(task_ok, len(task_rows)) if task_rows else 1.0 + + # task-leak penalty: a no-task matched row that nonetheless gained a + # 'Kickoff: ' / 'Exec review: ' task. + task_leak = 0 + for e in notask_rows: + account = e.get('account') + forbidden = {norm(f'Kickoff: {account}'), norm(f'Exec review: {account}')} + if forbidden & act_subjects: + task_leak += 1 + task_leak_frac = frac(task_leak, len(notask_rows)) if notask_rows else 0.0 + + # ---- Component 3 (0.20): owner reassigned, scored ONLY over rows that + # require an owner change (Closed Won). Other rows must keep their owner. ---- + owner_ok = 0 + for e in owner_rows: + opp = opp_by_name.get(norm(e.get('oppName'))) + want_owner = norm(e.get('final_owner')) + if opp is not None and want_owner and norm(opp.get('ownerId')) == want_owner: + owner_ok += 1 + owner_frac = frac(owner_ok, len(owner_rows)) if owner_rows else 1.0 + + # owner-leak penalty: a must-keep-owner row whose owner drifted from seeded. + owner_leak = 0 + for e in keep_owner_rows: + opp = opp_by_name.get(norm(e.get('oppName'))) + baseline = norm(e.get('initial_owner')) + if opp is not None and baseline and norm(opp.get('ownerId')) != baseline: + owner_leak += 1 + owner_leak_frac = frac(owner_leak, len(keep_owner_rows)) if keep_owner_rows else 0.0 + + # ---- Component 4 (0.15): Slack 'backup' channel created + 2 CSV files uploaded ---- + slack_payload = go('slack') + slack_cur = slack_payload.get('current_state', {}) if isinstance(slack_payload.get('current_state'), dict) else {} + slack_init = slack_payload.get('initial_state', {}) if isinstance(slack_payload.get('initial_state'), dict) else {} + s_adapter = slack_init.get('_task_adapter', {}) if isinstance(slack_init.get('_task_adapter'), dict) else {} + backup_channel = s_adapter.get('backup_channel') or 'backup' + required_csv = s_adapter.get('required_csv_count') + if not isinstance(required_csv, int) or required_csv <= 0: + required_csv = 2 + + def _channel_exists(state, name): + chans = state.get('channels', []) if isinstance(state, dict) else [] + return any(isinstance(c, dict) and norm(c.get('name')) == norm(name) for c in chans) + + def _is_csv_attachment(att): + if not isinstance(att, dict): + return False + nm = norm(att.get('name') or att.get('fileName') or att.get('filename')) + mt = norm(att.get('mimeType') or att.get('mime') or att.get('type')) + url = norm(att.get('url')) + return nm.endswith('.csv') or 'csv' in mt or url.endswith('.csv') + + # Channel must be NEWLY created (absent at injection, present now). + backup_exists_now = _channel_exists(slack_cur, backup_channel) + backup_existed_init = _channel_exists(slack_init, backup_channel) + channel_ok = bool(backup_exists_now and not backup_existed_init) + + # Count distinct CSV files uploaded into the backup channel. + csv_count = 0 + if backup_exists_now: + for m in _slack_channel_messages(slack_cur, backup_channel): + for att in (m.get('attachments') or []) if isinstance(m, dict) else []: + if _is_csv_attachment(att): + csv_count += 1 + + # Sub-score: 0.4 for creating the channel, 0.6 for uploading >= required CSVs + # (proportional credit for 1 of 2). Only counts CSVs inside the new channel. + slack_ok = 0.0 + if channel_ok: + slack_ok = 0.4 + 0.6 * min(csv_count, required_csv) / required_csv + + # ---- Combine: positives (0 in do-nothing) minus leak penalties (0 in do-nothing) ---- + # Weights: stage 0.40 + task 0.25 + owner 0.20 + slack 0.15 = 1.0. The Slack + # backup step was raised 0.05 -> 0.15 (it now requires creating a channel AND + # uploading two exported CSVs), so the SF-core components were trimmed 0.10 total. + s_stage = 0.40 * stage_frac + s_task = 0.25 * task_frac + s_owner = 0.20 * owner_frac + s_slack = 0.15 * slack_ok + positive = s_stage + s_task + s_owner + s_slack + penalty = 0.15 * stage_leak_frac + 0.10 * task_leak_frac + 0.10 * owner_leak_frac + score = clamp01(positive - penalty) + + print( + 'DEBUG_T05 ' + f'n={n} stage_ok={stage_ok}/{len(change_rows)} stage_leak={stage_leak}/{len(keep_stage_rows)} ' + f'task_ok={task_ok}/{len(task_rows)} task_leak={task_leak}/{len(notask_rows)} ' + f'owner_ok={owner_ok}/{len(owner_rows)} owner_leak={owner_leak}/{len(keep_owner_rows)} ' + f'backup_channel_ok={int(channel_ok)} csv_count={csv_count}/{required_csv} slack_ok={round(slack_ok, 3)} ' + f'w_stage={round(s_stage, 4)} w_task={round(s_task, 4)} w_owner={round(s_owner, 4)} ' + f'w_slack={round(s_slack, 4)} 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/am_renewal_hubspot_004__long/_cua_gym_vm_bridge.sh b/am_renewal_hubspot_004__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/am_renewal_hubspot_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/am_renewal_hubspot_004__long/initial_setup.py b/am_renewal_hubspot_004__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..54b6f54d6db659abf71a8f169b778f5d853d6b2a --- /dev/null +++ b/am_renewal_hubspot_004__long/initial_setup.py @@ -0,0 +1,688 @@ +""" +Initial Setup: T04 — HubSpot renewal outreach across HubSpot + Gmail + Google Calendar + (hidden-access-point edition) +Task ID: am_renewal_hubspot_004__long +Mocks: hubspot_mock, gmail_mock, google_calendar_mock + +Assume today is 2026-05-04 (a Monday). A deal QUALIFIES for renewal outreach iff +ALL hold: + - stage == 'closed_won' (label "Closed Won") + - dealType == 'existing_business' + - 2025-05-01 <= closeDate <= 2025-07-31 (inclusive) + - amount >= 10000 + +For every QUALIFYING deal the agent must perform SIX sub-actions across the three +apps, several of which are reachable only through HARD-TO-FIND ("hidden") controls: + + HubSpot (both edits live in the slide-in panel opened by clicking the deal NAME): + (H1) append the line 'Renewal outreach sent 2026-05-04.' to the deal Description + (keeping the existing text). + (H2) reassign the deal owner — the free-text "Assigned To" field — from + 'Admin User' to 'Renewals Team'. + Gmail: + (G1) send an email to the deal's primary contact with Subject 'Renewal: ' + and a body containing the company name, the original amount formatted as + $#,##0, and the original closeDate. (Obstacle: the email has to be found in HubSpot's contacts list. The contact is in the deal) + (G2) apply the 'Renewals' label to that sent email. The Label button only appears + in the toolbar AFTER an email row is selected (selection-gated control). + Google Calendar: + (C1) create a 'Renewal call: ' event one week out (2026-05-11). + (C2) add the contact's email as a GUEST. The guest field is buried inside the + event editor and the contact is NOT in the autocomplete list, so the email + must be typed in. + +Distractors (5 near-miss deals) each miss exactly ONE qualifying condition and must +be left untouched (no description edit, no owner change, no email, no label, no event). + +Ground truth is PRECOMPUTED below in Python so the embedded answer key (hidden `_*` +fields on hubspot deals) is internally consistent with the visible deal/company/ +contact data. reward.py reads `deals[*]._qualifies` (+ helper `_*` fields) from +initial_state as the sole source of truth. +""" +import os +import shlex +import subprocess +import time +import uuid +from datetime import date + +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 constants +# --------------------------------------------------------------------------- # +TODAY = date(2026, 5, 4) +TODAY_STR = TODAY.isoformat() # '2026-05-04' +RENEWAL_LINE = f'Renewal outreach sent {TODAY_STR}.' +WINDOW_START = date(2025, 5, 1) +WINDOW_END = date(2025, 7, 31) +MIN_AMOUNT = 10000 + +NEW_OWNER = 'Renewals Team' # H2: owner reassignment target +ORIG_OWNER = 'Admin User' # owner at injection +RENEWALS_LABEL_ID = 'l3' # G2: label to apply (seeded below) +RENEWALS_LABEL_NAME = 'Renewals' +EVENT_DATE_STR = '2026-05-11' # C1: one week from today (a Monday) + + +# --------------------------------------------------------------------------- # +# Builder helpers (keep many similar records terse) +# --------------------------------------------------------------------------- # +def company(cid, name, domain, industry, city, st, employees, revenue): + return { + 'id': cid, 'name': name, 'domain': domain, 'industry': industry, + 'phone': f'+1 (555) 1{cid[-1]}0-00{cid[-1]}0', + 'city': city, 'state': st, 'country': 'United States', + 'numberOfEmployees': employees, 'annualRevenue': revenue, + 'lifecycleStage': 'customer', 'owner': ORIG_OWNER, + 'description': f'{name} — {industry} customer account', + 'createDate': '2023-08-10T09:00:00Z', + } + + +def contact(cid, first, last, email, title, company_id, city, st): + return { + 'id': cid, 'firstName': first, 'lastName': last, 'email': email, + 'phone': '+1 (555) 010-0000', 'jobTitle': title, 'companyId': company_id, + 'lifecycleStage': 'customer', 'leadStatus': 'connected', + 'owner': ORIG_OWNER, 'city': city, 'state': st, 'country': 'United States', + 'createDate': '2023-08-15T10:30:00Z', 'lastActivityDate': '2026-04-20T14:00:00Z', + 'timeline': [], + } + + +def deal(did, name, stage, amount, close_date, deal_type, company_id, contact_ids, + description, priority='medium'): + return { + 'id': did, 'name': name, 'stage': stage, 'amount': amount, + 'closeDate': close_date, 'dealType': deal_type, 'priority': priority, + 'owner': ORIG_OWNER, 'companyId': company_id, 'contactIds': contact_ids, + 'probability': 100 if stage == 'closed_won' else (0 if stage == 'closed_lost' else 60), + 'description': description, + 'createDate': '2024-04-01T10:00:00Z', 'lastActivityDate': '2025-07-15T14:00:00Z', + } + + +def gmail_email(eid, frm, to, subject, body, folder='inbox', timestamp='2026-04-30T09:00:00Z'): + return { + 'id': eid, 'threadId': f'thread_{eid}', + 'from': frm, 'to': to, 'cc': [], 'bcc': [], + 'subject': subject, 'body': body, 'snippet': body[:120], + 'timestamp': timestamp, 'read': True, 'starred': False, 'important': False, + 'labels': [], 'category': 'primary', 'folder': folder, 'attachments': [], + } + + +def cal_event(eid, calendar_id, title, start_iso, end_iso, location, description, guests): + """A calendar event in the shape google_calendar_mock stores them.""" + return { + 'id': eid, 'calendarId': calendar_id, 'title': title, + 'start': start_iso, 'end': end_iso, + 'allDay': False, 'location': location, 'description': description, + 'guests': guests, 'color': '#33B679', 'recurring': 'none', + 'reminders': [{'type': 'popup', 'minutes': 10}], + } + + +# --------------------------------------------------------------------------- # +# Companies (one per deal; comp1..comp4 are the qualifying accounts) +# --------------------------------------------------------------------------- # +companies = [ + company('comp1', 'Acme', 'acme.com', 'Technology', 'San Francisco', 'CA', 250, 15000000), + company('comp2', 'Globex', 'globex.com', 'Manufacturing', 'New York', 'NY', 500, 32000000), + company('comp3', 'Initech', 'initech.com', 'Technology', 'Austin', 'TX', 120, 8000000), + company('comp4', 'Umbrella', 'umbrella.com', 'Healthcare', 'Boston', 'MA', 800, 55000000), + company('comp5', 'Wayne', 'wayne.com', 'Finance', 'Chicago', 'IL', 1200, 90000000), + company('comp6', 'Hooli', 'hooli.com', 'Technology', 'Palo Alto', 'CA', 900, 60000000), + company('comp7', 'Stark', 'stark.com', 'Manufacturing', 'Los Angeles', 'CA', 1500, 120000000), + company('comp8', 'Cyberdyne', 'cyberdyne.com', 'Technology', 'Sunnyvale', 'CA', 700, 40000000), + company('comp9', 'Wonka', 'wonka.com', 'Other', 'Chicago', 'IL', 300, 18000000), +] + +# Contacts. Each QUALIFYING company (comp1..comp4) has exactly ONE contact, so +# "first contact whose companyId matches" is unambiguous on the graded slice. +# Non-qualifying companies carry a couple of extra decoy contacts (realism). +contacts = [ + contact('c1', 'Alice', 'Chen', 'alice.chen@acme.com', 'VP Operations', 'comp1', 'San Francisco', 'CA'), + contact('c2', 'Bob', 'Martin', 'bob.martin@globex.com', 'Procurement Lead', 'comp2', 'New York', 'NY'), + contact('c3', 'Carol', 'Diaz', 'carol.diaz@initech.com', 'IT Director', 'comp3', 'Austin', 'TX'), + contact('c4', 'Dan', 'Wong', 'dan.wong@umbrella.com', 'Head of Research', 'comp4', 'Boston', 'MA'), + contact('c5', 'Eve', 'Parker', 'eve.parker@wayne.com', 'CFO', 'comp5', 'Chicago', 'IL'), + contact('c6', 'Frank', 'Lee', 'frank.lee@hooli.com', 'Eng Manager', 'comp6', 'Palo Alto', 'CA'), + contact('c7', 'Grace', 'Kim', 'grace.kim@stark.com', 'Plant Director', 'comp7', 'Los Angeles', 'CA'), + contact('c8', 'Henry', 'Cole', 'henry.cole@cyberdyne.com', 'CTO', 'comp8', 'Sunnyvale', 'CA'), + contact('c9', 'Iris', 'Shah', 'iris.shah@wonka.com', 'COO', 'comp9', 'Chicago', 'IL'), + # decoy second contacts on NON-qualifying accounts only + contact('c10', 'Mia', 'Stone', 'mia.stone@wayne.com', 'Controller', 'comp5', 'Chicago', 'IL'), + contact('c11', 'Leo', 'Burns', 'leo.burns@stark.com', 'Ops Analyst', 'comp7', 'Los Angeles', 'CA'), +] + + +# --------------------------------------------------------------------------- # +# Deals — 4 qualifying + 5 near-miss distractors +# d1 Acme QUALIFIES (existing, 2025-05-15, $24,000) +# d2 Globex QUALIFIES (existing, 2025-06-30, $15,000) +# d3 Initech QUALIFIES (existing, 2025-07-31 high boundary, $50,000) +# d4 Umbrella QUALIFIES (existing, 2025-05-01 low boundary, $12,000) +# d5 Wayne NO -> new_business (right window+stage, $30,000) +# d6 Hooli NO -> amount 8000 < 10000 (existing, in window) +# d7 Stark NO -> closeDate 2025-04-15 just BEFORE window +# d8 Cyberdyne NO -> stage closed_lost (existing, in window, $35,000) +# d9 Wonka NO -> closeDate 2025-08-15 just AFTER window +# --------------------------------------------------------------------------- # +deals = [ + deal('d1', 'Acme - Platform Subscription', 'closed_won', 24000, '2025-05-15', + 'existing_business', 'comp1', ['c1'], + 'Annual platform subscription, 250 seats. Renewed last cycle without issues.', 'high'), + deal('d2', 'Globex - Support Contract', 'closed_won', 15000, '2025-06-30', + 'existing_business', 'comp2', ['c2'], + 'Gold support contract covering all manufacturing sites.', 'medium'), + deal('d3', 'Initech - Enterprise Plan', 'closed_won', 50000, '2025-07-31', + 'existing_business', 'comp3', ['c3'], + 'Enterprise plan with premium SLA and onboarding.', 'high'), + deal('d4', 'Umbrella - Compliance Module', 'closed_won', 12000, '2025-05-01', + 'existing_business', 'comp4', ['c4'], + 'Compliance reporting module add-on for research division.', 'medium'), + # ---- distractors ---- + deal('d5', 'Wayne - New Analytics Suite', 'closed_won', 30000, '2025-06-10', + 'new_business', 'comp5', ['c5'], + 'First-time purchase of the analytics suite for finance ops.', 'high'), + deal('d6', 'Hooli - Small Add-on', 'closed_won', 8000, '2025-06-20', + 'existing_business', 'comp6', ['c6'], + 'Minor seat expansion add-on, below renewal threshold.', 'low'), + deal('d7', 'Stark - Spring Renewal', 'closed_won', 40000, '2025-04-15', + 'existing_business', 'comp7', ['c7'], + 'Renewal that closed in April, outside the summer window.', 'high'), + deal('d8', 'Cyberdyne - Lost Renewal', 'closed_lost', 35000, '2025-06-05', + 'existing_business', 'comp8', ['c8'], + 'Renewal that lapsed; customer churned to a competitor.', 'medium'), + deal('d9', 'Wonka - Late Summer Renewal', 'closed_won', 22000, '2025-08-15', + 'existing_business', 'comp9', ['c9'], + 'Renewal closing in late August, just after the window.', 'medium'), +] + + +# --------------------------------------------------------------------------- # +# PRECOMPUTE the ground truth and embed hidden `_*` answer-key fields. +# --------------------------------------------------------------------------- # +def parse_date(s): + y, m, d = (int(x) for x in s.split('-')) + return date(y, m, d) + + +def primary_contact_email(company_id): + """companies[].name -> contacts where companyId matches, first such email.""" + for c in contacts: + if c['companyId'] == company_id: + return c['email'] + return None + + +def fmt_amount(amount): + """Original amount formatted as $#,##0 (e.g. 24000 -> '$24,000').""" + return f'${amount:,}' + + +n_qualifying = 0 +for d in deals: + cd = parse_date(d['closeDate']) + qualifies = ( + d['stage'] == 'closed_won' + and d['dealType'] == 'existing_business' + and WINDOW_START <= cd <= WINDOW_END + and d['amount'] >= MIN_AMOUNT + ) + company_name = next(c['name'] for c in companies if c['id'] == d['companyId']) + contact_email = primary_contact_email(d['companyId']) + d['_qualifies'] = qualifies + d['_company_name'] = company_name + d['_primary_contact_email'] = contact_email + d['_orig_owner'] = ORIG_OWNER + d['_email_subject'] = f'Renewal: {company_name}' # ALL deals (leak shape) + d['_event_title'] = f'Renewal call: {company_name}' # ALL deals (leak shape) + if qualifies: + n_qualifying += 1 + # --- HubSpot answer key --- + d['_renewal_line'] = RENEWAL_LINE + d['_expected_description'] = d['description'] + '\n' + RENEWAL_LINE + d['_new_owner'] = NEW_OWNER + # --- Gmail answer key --- + d['_amount_fmt'] = fmt_amount(d['amount']) + d['_close_date'] = d['closeDate'] + # Body must contain ALL of these substrings. + d['_email_body_must_contain'] = [company_name, fmt_amount(d['amount']), d['closeDate']] + d['_renewals_label_id'] = RENEWALS_LABEL_ID + d['_renewals_label_name'] = RENEWALS_LABEL_NAME + # --- Calendar answer key --- + d['_event_date'] = EVENT_DATE_STR + d['_event_guest_email'] = contact_email + else: + # Distractors must receive NO edits, NO email, NO label, NO event. + d['_renewal_line'] = None + +assert n_qualifying == 4, f'expected 4 qualifying deals, got {n_qualifying}' +print(f'Precomputed ground truth: {n_qualifying} qualifying deals ' + f'({[d["id"] for d in deals if d["_qualifies"]]})') + + +# Standard 7-stage pipeline configuration (default labels; "Closed Won" column). +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}, +} + + +# --------------------------------------------------------------------------- # +# Gmail account (sales rep doing the outreach). NO renewal mail pre-seeded: +# the 'sent' folder contains no 'Renewal: ' subjects (Rule 3). A few +# read inbox emails act as watermark / realism only. A 'Renewals' label is +# pre-created (l3) so the agent can APPLY it; no email carries it at injection. +# --------------------------------------------------------------------------- # +gmail_user = { + 'userId': 'u1', 'username': 'Jordan Avery', + 'email': 'jordan.avery@ourcompany.com', + 'avatar': 'https://picsum.photos/200/200?random=7', +} +gmail_emails = [ + gmail_email('m1', + {'name': 'Alice Chen', 'email': 'alice.chen@acme.com', 'avatar': ''}, + [{'name': 'Jordan Avery', 'email': 'jordan.avery@ourcompany.com'}], + 'Re: Q1 usage report', + 'Thanks for the usage report — numbers look healthy on our end.', + folder='inbox', timestamp='2026-04-28T09:15:00Z'), + gmail_email('m2', + {'name': 'Billing', 'email': 'billing@globex.com', 'avatar': ''}, + [{'name': 'Jordan Avery', 'email': 'jordan.avery@ourcompany.com'}], + 'Invoice received', + 'Confirming we received the latest support invoice. No action needed.', + folder='inbox', timestamp='2026-04-29T11:00:00Z'), + gmail_email('m3', + {'name': 'Jordan Avery', 'email': 'jordan.avery@ourcompany.com', 'avatar': ''}, + [{'name': 'Carol Diaz', 'email': 'carol.diaz@initech.com'}], + 'Onboarding follow-up', + 'Glad onboarding went smoothly. Reach out anytime with questions.', + folder='sent', timestamp='2026-04-22T16:30:00Z'), +] +gmail_labels = [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': RENEWALS_LABEL_ID, 'name': RENEWALS_LABEL_NAME, 'color': '#16a34a'}, +] + + +# --------------------------------------------------------------------------- # +# Google Calendar account. today = 2026-05-04. A couple of decoy events for +# realism on the Work calendar; NONE titled 'Renewal call:' (Rule 3 — the +# gradable output must be absent at injection). +# --------------------------------------------------------------------------- # +# NOTE: use timezone-NAIVE local ISO (no trailing 'Z') to match the shape the +# calendar mock stores when the user creates events through the UI. Mixing +# UTC-suffixed injected events with naive-local user-created events makes the +# newly created event appear on a different day/time-slot in the week grid +# (or vanish entirely from the visible viewport). See the working reference +# in demo_tasks/.../975bd1cb-.../initial_setup.py. +calendar_events = [ + cal_event('evt_standup', 'c2', 'Team Standup', + '2026-05-04T09:30:00', '2026-05-04T10:00:00', + 'Conference Room A', 'Daily sync', ['teammate@ourcompany.com']), + cal_event('evt_pipeline', 'c2', 'Pipeline Review', + '2026-05-06T14:00:00', '2026-05-06T15:00:00', + 'Zoom', 'Weekly pipeline review', []), + cal_event('evt_lunch', 'c1', 'Lunch with Sarah', + '2026-05-05T12:00:00', '2026-05-05T13:00:00', + 'Downtown Cafe', '', []), +] + + +# --------------------------------------------------------------------------- # +# APP_STATES — full key set per mock; answer key embedded in hubspot.deals[*]. +# --------------------------------------------------------------------------- # +APP_STATES = [ + ('http://28.7.184.198:8150', { # hubspot_mock + 'contacts': contacts, + 'companies': companies, + 'deals': deals, + 'tickets': [], + 'tasks': [], + 'notes': [], + 'templates': [], + 'meetings': [], + 'forms': [], + 'dealStages': DEAL_STAGES, + 'ticketStatuses': TICKET_STATUSES, + 'appState': { + 'sidebarOpen': True, + 'currentUser': {'name': 'Admin User', 'email': 'admin@example.com', 'avatar': None}, + }, + '_task_adapter': {'task_id': 'T04_hubspot_renewal_outreach_3app', 'variant': 'eval'}, + }), + ('http://28.7.184.198:8138', { # gmail_mock — sent folder has NO renewal mail + 'user': gmail_user, + 'emails': gmail_emails, + 'labels': gmail_labels, + 'drafts': [], + 'settings': { + 'density': 'default', 'undoSend': 10, + 'categoryTabs': {'primary': True, 'social': True, 'promotions': True, + 'updates': False, 'forums': False}, + }, + 'today': TODAY_STR, + }), + ('http://28.7.184.198:8141', { # google_calendar_mock — no 'Renewal call:' events + 'user': {'id': 'u1', 'username': 'Jordan Avery', + 'email': 'jordan.avery@ourcompany.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + # WeekView renders event chips with backgroundColor=. The React component only accepts hex strings ('#RRGGBB'); + # tailwind class names like 'bg-green-500' are invalid CSS colors, so the + # event blocks render but are invisible on the grid (though the click + # popup still shows the correct data). Use hex to match the working + # setup in demo_tasks/.../975bd1cb-.../initial_setup.py. + 'calendars': [ + {'id': 'c1', 'name': 'Personal', 'color': '#039BE5', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1', + 'isDefault': True}, + {'id': 'c2', 'name': 'Work', 'color': '#33B679', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1', + 'isDefault': False}, + ], + 'events': calendar_events, + 'view': 'week', + # naive local ISO (no trailing Z), matches events[*].start above + 'currentDate': '2026-05-04T00:00:00', + 'sidebarOpen': True, + 'settings': { + 'weekStart': 0, 'defaultDuration': 60, 'defaultView': 'week', + 'defaultReminder': {'type': 'popup', 'minutes': 10}, + }, + 'today': TODAY_STR, + }), +] + + +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/am_renewal_hubspot_004__long/reward.py b/am_renewal_hubspot_004__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea30d188e58904e62e88d99e1a3bfefd35efe19 --- /dev/null +++ b/am_renewal_hubspot_004__long/reward.py @@ -0,0 +1,727 @@ +""" +Reward Script: T04 — HubSpot renewal outreach across HubSpot + Gmail + Google Calendar + (hidden-access-point edition) +Task ID: am_renewal_hubspot_004__long +Mocks: hubspot_mock,gmail_mock,google_calendar_mock +Scoring (per qualifying deal unless noted; frac over the qualifying set). +Positive components sum to 1.0 and are each 0 in a do-nothing run; leakage is a +PENALTY (subtracted), so a do-nothing agent scores exactly 0.0: + 0.22 HubSpot: current description endswith _renewal_line AND still contains the + original text (hidden: slide-in panel) + 0.17 HubSpot: deal owner reassigned from 'Admin User' to 'Renewals Team' + (hidden: "Assigned To" field) + 0.22 Gmail: a sent email exists with subject == 'Renewal: ' and body + contains company + $amount + closeDate + 0.17 Gmail: that renewal email carries the 'Renewals' label (hidden: selection-gated + Label button; matched by label NAME so an agent-created label also counts) + 0.11 Calendar: a 'Renewal call: ' event exists on 2026-05-11 + (hidden: must create event; TZ-robust date match) + 0.11 Calendar: that renewal-call event lists the contact's email as a guest + (hidden: guest field buried in the event editor; contact not in the picker) + -0.15 PENALTY (max): scaled by the fraction of non-qualifying deals that were + wrongly touched (description/owner edit, 'Renewal:' email, or 'Renewal call:' event). +Answer key: hubspot_mock initial_state deals[*] hidden `_*` fields (sole source of truth). +""" +import copy +import re +import sys + +import requests + +from datetime import datetime, timezone, timedelta + +TZ_PLUS_8 = timezone(timedelta(hours=8)) + + +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +APP_URLS = { + 'hubspot': 'http://28.7.184.198:8150', + 'gmail': 'http://28.7.184.198:8138', + 'google_calendar': 'http://28.7.184.198:8141', +} +_GO_CACHE = {} + + +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def 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(m): + if not isinstance(m, dict): + return '' + return m.get('content') or m.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + """Return messages for a channel, handling channels[*].messages AND the + top-level messages[channelId] map.""" + if not isinstance(slack_state, dict): + return [] + target = norm(channel_name).lstrip('#') + out = [] + messages_map = slack_state.get('messages') if isinstance(slack_state.get('messages'), dict) else {} + for ch in slack_state.get('channels', []) or []: + if not isinstance(ch, dict): + continue + nm = norm(ch.get('name')).lstrip('#') + if nm != target: + continue + msgs = ch.get('messages') + if isinstance(msgs, list): + out.extend(m for m in msgs if isinstance(m, dict)) + cid = ch.get('channelId') or ch.get('id') + if cid and isinstance(messages_map.get(cid), list): + out.extend(m for m in messages_map[cid] if isinstance(m, dict)) + return out + + +def _sheet_rows(sheets_state, sheet_name=None): + """Rows from a materialized sheets dict {name: {headers, rows}}.""" + if isinstance(sheets_state, dict): + if sheet_name and isinstance(sheets_state.get(sheet_name), dict): + return sheets_state[sheet_name].get('rows', []) or [] + for v in sheets_state.values(): + if isinstance(v, dict) and 'rows' in v: + return v.get('rows', []) or [] + return [] + + +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) + + return f"{to} {email.get('subject', '')} {email.get('body', '')}" + + +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 _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 === +# +# Ground truth lives in hubspot_mock initial_state deals[*] hidden `_*` fields: +# _qualifies (bool) -> THE qualifying set (d1-d4 True; d5-d9 False) +# _renewal_line (str) -> exact line to append (qualifying only) +# _expected_description (str) -> original + "\n" + _renewal_line (qualifying) +# _orig_owner (str) -> 'Admin User' (owner at injection, ALL deals) +# _new_owner (str) -> 'Renewals Team' (qualifying only) +# _email_subject (str) -> "Renewal: " (ALL deals; leak shape) +# _email_body_must_contain -> [company, $amount, closeDate] (qualifying only) +# _renewals_label_name (str) -> 'Renewals' (qualifying only) +# _event_title (str) -> "Renewal call: " (ALL deals; leak shape) +# _event_date (str) -> '2026-05-11' (qualifying only) +# _event_guest_email (str) -> contact email to add as guest (qualifying only) +# Original description = initial_state deals[i].description (pre-edit visible field). + +# Positive components (each requires an agent action -> all 0 in do-nothing). +# Weights sum to exactly 1.0. Leakage onto non-qualifying deals is a PENALTY +# (subtracted, 0 in do-nothing) rather than positive credit, so a do-nothing +# agent scores exactly 0. +WEIGHT_DESC = 0.22 +WEIGHT_OWNER = 0.17 +WEIGHT_EMAIL = 0.22 +WEIGHT_LABEL = 0.17 +WEIGHT_EVENT = 0.11 +WEIGHT_GUEST = 0.11 +WEIGHT_LEAK_PENALTY = 0.15 # max penalty if EVERY non-qualifying deal is touched + + +def _email_full_text(e): + """subject + HTML-stripped body + snippet, for substring search.""" + if not isinstance(e, dict): + return '' + subj = e.get('subject') or '' + body = e.get('body') or '' + body_text = re.sub(r'<[^>]+>', ' ', body) + snippet = e.get('snippet') or '' + return f'{subj}\n{body_text}\n{snippet}' + + +def _desc_match(cur_desc, orig_desc, renewal_line, expected_desc): + """current description endswith renewal_line AND still contains original text.""" + cur = cur_desc or '' + rl = (renewal_line or '').strip() + if not rl: + return False + cur_stripped = cur.rstrip() + ends = cur_stripped.endswith(rl) or norm(cur_stripped).endswith(norm(rl)) + orig = (orig_desc or '').strip() + contains_orig = (norm(orig) in norm(cur)) if orig else True + if ends and contains_orig: + return True + # fallback: exact match to the embedded expected description + if expected_desc and norm(cur) == norm(expected_desc): + return True + return False + + +def _renewal_emails_by_subject(sent_emails, subject): + """All sent emails whose subject == subject (case-insensitive).""" + want_subj = norm(subject) + if not want_subj: + return [] + return [e for e in (sent_emails or []) + if isinstance(e, dict) and norm(e.get('subject')) == want_subj] + + +def _email_body_ok(e, needles): + text = norm(_email_full_text(e)) + return all(norm(nd) in text for nd in (needles or []) if nd) + + +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 + + +# ---- Calendar helpers (TZ-robust date matching, guest subset) ---- +def _parse_as_utc(s, default_tz=TZ_PLUS_8): + if not s: + return None + s = str(s).strip() + if s.endswith('Z'): + s = s[:-1] + '+00:00' + try: + dt = datetime.fromisoformat(s) + except Exception: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=default_tz) + return dt + + +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 _event_on_date(ev, target_date): + """True if the event's start matches target_date under EITHER the literal + wall-clock reading OR the UTC->UTC+8 conversion (robust to datetime-local + -> toISOString() tz shifts the calendar mock performs).""" + start = ev.get('start') + target = norm(target_date) + if not target: + return True + if norm(_raw_date_part(start)) == target: + return True + dt = _parse_as_utc(start) + if dt is not None: + if dt.astimezone(TZ_PLUS_8).date().isoformat() == target: + return True + if dt.astimezone(timezone.utc).date().isoformat() == target: + return True + return False + + +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): + hub = go('hubspot') + hub_i = hub.get('initial_state', {}) or {} + hub_c = hub.get('current_state', {}) or {} + gmail_c = go('gmail').get('current_state', {}) or {} + cal_c = go('google_calendar').get('current_state', {}) or {} + + deals_i = [d for d in (hub_i.get('deals', []) or []) if isinstance(d, dict)] + deals_c_by_id = by_id([d for d in (hub_c.get('deals', []) or []) if isinstance(d, dict)]) + sent_emails = _gmail_sent_emails(gmail_c) + cur_events = [e for e in (cal_c.get('events', []) or []) if isinstance(e, dict)] + + # label id -> name map (current gmail labels), for robust label-name matching + label_id_to_name = {} + for lab in (gmail_c.get('labels', []) or []): + if isinstance(lab, dict) and lab.get('id'): + label_id_to_name[lab['id']] = lab.get('name') or lab['id'] + + qualifying = [d for d in deals_i if d.get('_qualifies') is True] + nonqual = [d for d in deals_i if d.get('_qualifies') is not True] + n_q = len(qualifying) + n_nq = len(nonqual) + + # --- Component 1: HubSpot description appended (0.20) --- + desc_ok = 0 + desc_flags = [] + for d in qualifying: + did = d.get('id') + cur = deals_c_by_id.get(did, {}) or {} + ok = _desc_match( + cur.get('description') or '', + d.get('description') or '', + d.get('_renewal_line') or '', + d.get('_expected_description') or '', + ) + desc_ok += 1 if ok else 0 + desc_flags.append(f"{did}={'Y' if ok else 'N'}") + s_desc = WEIGHT_DESC * frac(desc_ok, n_q) + + # --- Component 2: HubSpot owner reassigned (0.15) --- + owner_ok = 0 + owner_flags = [] + for d in qualifying: + did = d.get('id') + cur = deals_c_by_id.get(did, {}) or {} + want = norm(d.get('_new_owner') or '') + ok = bool(want) and norm(cur.get('owner')) == want + owner_ok += 1 if ok else 0 + owner_flags.append(f"{did}={'Y' if ok else 'N'}") + s_owner = WEIGHT_OWNER * frac(owner_ok, n_q) + + # --- Component 3: Gmail renewal email sent (0.20) --- + email_ok = 0 + email_flags = [] + for d in qualifying: + did = d.get('id') + matches = _renewal_emails_by_subject(sent_emails, d.get('_email_subject') or '') + ok = any(_email_body_ok(e, d.get('_email_body_must_contain') or []) for e in matches) + email_ok += 1 if ok else 0 + email_flags.append(f"{did}={'Y' if ok else 'N'}") + s_email = WEIGHT_EMAIL * frac(email_ok, n_q) + + # --- Component 4: Gmail 'Renewals' label applied to the renewal email (0.15) --- + label_ok = 0 + label_flags = [] + for d in qualifying: + did = d.get('id') + want_label = norm(d.get('_renewals_label_name') or '') + matches = _renewal_emails_by_subject(sent_emails, d.get('_email_subject') or '') + ok = bool(want_label) and any( + want_label in _label_name_set(e, label_id_to_name) for e in matches + ) + label_ok += 1 if ok else 0 + label_flags.append(f"{did}={'Y' if ok else 'N'}") + s_label = WEIGHT_LABEL * frac(label_ok, n_q) + + # --- Component 5: Calendar 'Renewal call: ' event on the right date (0.10) --- + event_ok = 0 + event_flags = [] + for d in qualifying: + did = d.get('id') + title = norm(d.get('_event_title') or '') + date_str = d.get('_event_date') or '' + ok = bool(title) and any( + norm(ev.get('title')) == title and _event_on_date(ev, date_str) + for ev in cur_events + ) + event_ok += 1 if ok else 0 + event_flags.append(f"{did}={'Y' if ok else 'N'}") + s_event = WEIGHT_EVENT * frac(event_ok, n_q) + + # --- Component 6: Calendar contact added as guest on the renewal-call event (0.10) --- + guest_ok = 0 + guest_flags = [] + for d in qualifying: + did = d.get('id') + title = norm(d.get('_event_title') or '') + want_guest = norm(d.get('_event_guest_email') or '') + ok = bool(title) and bool(want_guest) and any( + norm(ev.get('title')) == title and want_guest in _event_guests(ev) + for ev in cur_events + ) + guest_ok += 1 if ok else 0 + guest_flags.append(f"{did}={'Y' if ok else 'N'}") + s_guest = WEIGHT_GUEST * frac(guest_ok, n_q) + + # --- Penalty: leakage onto non-qualifying deals (0 in do-nothing) --- + # A non-qualifying deal is "leaked" if the agent edited its description, changed + # its owner, sent it a 'Renewal:' email, or created its 'Renewal call:' event. + leaked = 0 + leak_flags = [] + for d in nonqual: + did = d.get('id') + cur = deals_c_by_id.get(did, {}) or {} + desc_leak = norm(cur.get('description') or '') != norm(d.get('description') or '') + owner_leak = norm(cur.get('owner')) != norm(d.get('_orig_owner') or '') + email_leak = len(_renewal_emails_by_subject(sent_emails, d.get('_email_subject') or '')) > 0 + evt_title = norm(d.get('_event_title') or '') + event_leak = bool(evt_title) and any(norm(ev.get('title')) == evt_title for ev in cur_events) + if desc_leak or owner_leak or email_leak or event_leak: + leaked += 1 + leak_flags.append(f"{did}=d{int(desc_leak)}o{int(owner_leak)}e{int(email_leak)}c{int(event_leak)}") + leak_penalty = WEIGHT_LEAK_PENALTY * (0.0 if n_nq == 0 else frac(leaked, n_nq)) + + positive = s_desc + s_owner + s_email + s_label + s_event + s_guest + score = clamp01(positive - leak_penalty) + + print( + 'DEBUG_T04_hubspot_renewal_outreach_3app ' + f'n_qual={n_q} n_nonqual={n_nq} sent_emails={len(sent_emails)} cal_events={len(cur_events)} ' + f'desc={desc_ok}/{n_q}[{",".join(desc_flags)}] ' + f'owner={owner_ok}/{n_q}[{",".join(owner_flags)}] ' + f'email={email_ok}/{n_q}[{",".join(email_flags)}] ' + f'label={label_ok}/{n_q}[{",".join(label_flags)}] ' + f'event={event_ok}/{n_q}[{",".join(event_flags)}] ' + f'guest={guest_ok}/{n_q}[{",".join(guest_flags)}] ' + f'leaked={leaked}/{n_nq}[{",".join(leak_flags)}] ' + f'w_desc={round(s_desc, 4)} w_owner={round(s_owner, 4)} w_email={round(s_email, 4)} ' + f'w_label={round(s_label, 4)} w_event={round(s_event, 4)} w_guest={round(s_guest, 4)} ' + f'leak_penalty={round(leak_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/am_renewal_outreach_002/_cua_gym_vm_bridge.sh b/am_renewal_outreach_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/am_renewal_outreach_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/am_renewal_outreach_002/initial_setup.py b/am_renewal_outreach_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..89b45079aad12965a9b580e3cfa2004261003c1d --- /dev/null +++ b/am_renewal_outreach_002/initial_setup.py @@ -0,0 +1,583 @@ +# --- 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: Renewal check-in for Northwind Traders (Salesforce task + Gmail outreach + Slack closure) +Task ID: am_renewal_outreach_002 +Domain: mock_websites +Mocks: salesforce_mock, gmail_mock, slack_mock +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Network egress: this VM has no direct internet; web egress to the mocks +# is routed through the cluster proxy. Probe once (fast) to decide whether a +# proxy is needed, then reuse the decision. Override the proxy with WEB_PROXY. --- +PROXY = os.environ.get('WEB_PROXY') or None +PROXIES = None + +_PROBE_URL = 'http://28.7.184.198:8138/go?sid=__probe__' + + +def _decide_proxy(): + try: + requests.get(_PROBE_URL, timeout=4) + return None # direct works + except requests.exceptions.RequestException: + return PROXIES # fall back to proxy + + +_ACTIVE_PROXIES = _decide_proxy() +print(f'Network mode: {"proxy " + PROXY if _ACTIVE_PROXIES else "direct"}') + + +def http_post(url, payload): + return requests.post(url, json=payload, timeout=30, proxies=_ACTIVE_PROXIES) + + +def http_get(url): + return requests.get(url, timeout=30, proxies=_ACTIVE_PROXIES) + + +# --- Config --- +SALESFORCE_URL = 'http://28.7.184.198:8175' +GMAIL_URL = 'http://28.7.184.198:8138' +SLACK_URL = 'http://28.7.184.198:8178' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid={sid}') + +# Use a fresh Chrome profile per task session. This avoids stale Salesforce +# modal/localStorage state (for example a lingering "New Task" dialog) from a +# previous run blocking the task flow or making state detection flaky. +CHROME_PROFILE_DIR = f'/tmp/cua_chrome_profile_{sid}' +os.makedirs(CHROME_PROFILE_DIR, exist_ok=True) + + +# --------------------------------------------------------------------------- +# SALESFORCE STATE +# --------------------------------------------------------------------------- +def build_salesforce_state(): + jordan = { + "userId": "user-1", + "firstName": "Jordan", + "lastName": "Avery", + "email": "jordan.avery@vertexcloud.example.com", + "phone": "(555) 204-1180", + "title": "Account Manager", + "department": "Sales", + "role": "Account Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + } + users = [ + jordan, + { + "userId": "user-2", "firstName": "Priya", "lastName": "Nair", + "email": "priya.nair@vertexcloud.example.com", "phone": "(555) 204-1181", + "title": "Sales Director", "department": "Sales", "role": "Director", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + }, + { + "userId": "user-3", "firstName": "Diego", "lastName": "Morales", + "email": "diego.morales@vertexcloud.example.com", "phone": "(555) 204-1182", + "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM", + "avatar": "https://i.pravatar.cc/150?u=user-3", + "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning", + }, + ] + + accounts = [ + { + "accountId": "account-1", "name": "Northwind Traders", "type": "Customer", + "industry": "Logistics", "revenue": 48000000, "employees": 320, "ownerId": "user-1", + "phone": "(206) 555-0142", "website": "https://www.northwind-traders.example.com", + "billingStreet": "401 Harbor Way", "billingCity": "Seattle", "billingState": "WA", + "billingZip": "98101", "billingCountry": "USA", + "shippingStreet": "401 Harbor Way", "shippingCity": "Seattle", "shippingState": "WA", + "shippingZip": "98101", "shippingCountry": "USA", + "createdDate": "2024-02-10T00:00:00.000Z", "modifiedDate": "2026-05-20T00:00:00.000Z", + }, + { + "accountId": "account-2", "name": "Globex Corporation", "type": "Customer", + "industry": "Manufacturing", "revenue": 92000000, "employees": 540, "ownerId": "user-1", + "phone": "(312) 555-0177", "website": "https://www.globex.example.com", + "billingStreet": "88 Industrial Blvd", "billingCity": "Chicago", "billingState": "IL", + "billingZip": "60601", "billingCountry": "USA", + "shippingStreet": "88 Industrial Blvd", "shippingCity": "Chicago", "shippingState": "IL", + "shippingZip": "60601", "shippingCountry": "USA", + "createdDate": "2023-11-04T00:00:00.000Z", "modifiedDate": "2026-04-18T00:00:00.000Z", + }, + { + "accountId": "account-3", "name": "Initech", "type": "Customer", + "industry": "Technology", "revenue": 27000000, "employees": 180, "ownerId": "user-1", + "phone": "(512) 555-0190", "website": "https://www.initech.example.com", + "billingStreet": "1200 Congress Ave", "billingCity": "Austin", "billingState": "TX", + "billingZip": "78701", "billingCountry": "USA", + "shippingStreet": "1200 Congress Ave", "shippingCity": "Austin", "shippingState": "TX", + "shippingZip": "78701", "shippingCountry": "USA", + "createdDate": "2024-06-22T00:00:00.000Z", "modifiedDate": "2026-03-30T00:00:00.000Z", + }, + ] + + contacts = [ + { + "contactId": "contact-1", "accountId": "account-1", "firstName": "Karen", + "lastName": "Walsh", "title": "VP Operations", "department": "Operations", + "email": "karen.walsh@northwind-traders.example.com", "phone": "(206) 555-0148", + "ownerId": "user-1", + }, + { + "contactId": "contact-2", "accountId": "account-2", "firstName": "Hank", + "lastName": "Scorpio", "title": "COO", "department": "Executive", + "email": "hank.scorpio@globex.example.com", "phone": "(312) 555-0178", + "ownerId": "user-1", + }, + { + "contactId": "contact-3", "accountId": "account-3", "firstName": "Bill", + "lastName": "Lumbergh", "title": "Director of IT", "department": "IT", + "email": "bill.lumbergh@initech.example.com", "phone": "(512) 555-0191", + "ownerId": "user-1", + }, + ] + + opportunities = [ + { + "opportunityId": "opp-1", "name": "Northwind Traders – Annual Renewal", + "accountId": "account-1", "contactId": "contact-1", "amount": 120000, + "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 75, + "ownerId": "user-1", "type": "Renewal", + "createdDate": "2026-04-01T00:00:00.000Z", "modifiedDate": "2026-05-28T00:00:00.000Z", + }, + { + "opportunityId": "opp-2", "name": "Globex Corp – Platform Renewal", + "accountId": "account-2", "contactId": "contact-2", "amount": 210000, + "closeDate": "2026-09-30", "stage": "Qualification", "probability": 40, + "ownerId": "user-1", "type": "Renewal", + "createdDate": "2026-05-02T00:00:00.000Z", "modifiedDate": "2026-05-30T00:00:00.000Z", + }, + { + "opportunityId": "opp-3", "name": "Initech – Renewal & Upsell", + "accountId": "account-3", "contactId": "contact-3", "amount": 85000, + "closeDate": "2026-08-20", "stage": "Value Proposition", "probability": 55, + "ownerId": "user-1", "type": "Renewal", + "createdDate": "2026-05-10T00:00:00.000Z", "modifiedDate": "2026-06-01T00:00:00.000Z", + }, + ] + + # Distractor activities — old COMPLETED tasks unrelated to the renewal. + activities = [ + { + "activityId": "activity-1", "type": "task", "subject": "Send onboarding deck to Globex", + "status": "Completed", "priority": "Normal", "dueDate": "2026-04-12", + "relatedToType": "opportunity", "relatedToId": "opp-2", "assignedToId": "user-1", + }, + { + "activityId": "activity-2", "type": "task", "subject": "Update Initech billing contact", + "status": "Completed", "priority": "Low", "dueDate": "2026-05-05", + "relatedToType": "account", "relatedToId": "account-3", "assignedToId": "user-1", + }, + { + "activityId": "activity-3", "type": "event", "subject": "Quarterly business review (internal)", + "status": "Completed", "priority": "Normal", + "startDateTime": "2026-05-18T15:00:00.000Z", "endDateTime": "2026-05-18T16:00:00.000Z", + "relatedToType": "account", "relatedToId": "account-1", "assignedToId": "user-1", + }, + ] + + return { + "user": jordan, + "users": users, + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": activities, + "chatterPosts": [], + "files": [], + "following": ["user-2", "user-3"], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# --------------------------------------------------------------------------- +# GMAIL STATE +# --------------------------------------------------------------------------- +def build_gmail_state(): + jordan_user = { + "userId": "u1", + "username": "Jordan Avery", + "email": "jordan.avery@vertexcloud.example.com", + "avatar": "https://i.pravatar.cc/150?u=jordan-avery", + } + # Distractor prior thread from Karen Walsh about general account questions. + emails = [ + { + "id": "email_1", "threadId": "thread_1", + "from": {"name": "Karen Walsh", "email": "karen.walsh@northwind-traders.example.com"}, + "to": [{"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}], + "cc": [], "bcc": [], + "subject": "Question about our account users", + "body": "

Hi Jordan,

Quick question — a couple of our new ops analysts need " + "access to the reporting dashboards. Can you point me to where I add seats?

" + "

Thanks,
Karen

", + "timestamp": "2026-06-10T14:05:00Z", + "read": True, "starred": False, "important": False, + "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": [], + }, + { + "id": "email_2", "threadId": "thread_1", + "from": {"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}, + "to": [{"name": "Karen Walsh", "email": "karen.walsh@northwind-traders.example.com"}], + "cc": [], "bcc": [], + "subject": "Re: Question about our account users", + "body": "

Hi Karen,

Happy to help — you can add seats under Settings → " + "Users → Invite. Let me know if you hit any snags.

Best,
Jordan

", + "timestamp": "2026-06-10T16:20:00Z", + "read": True, "starred": False, "important": False, + "labels": ["l1"], "category": "primary", "folder": "sent", "attachments": [], + }, + { + "id": "email_3", "threadId": "thread_2", + "from": {"name": "Vertex Cloud Billing", "email": "billing@vertexcloud.example.com"}, + "to": [{"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}], + "cc": [], "bcc": [], + "subject": "June invoice summary", + "body": "

Your June account summary is now available in the billing portal.

", + "timestamp": "2026-06-15T09:00:00Z", + "read": False, "starred": False, "important": False, + "labels": ["l4"], "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"}, + ] + return {"user": jordan_user, "emails": emails, "labels": labels, "drafts": []} + + +# --------------------------------------------------------------------------- +# SLACK STATE +# --------------------------------------------------------------------------- +def build_slack_state(): + jordan = { + "userId": "user_1", "fullName": "Jordan Avery", "displayName": "Jordan", + "email": "jordan.avery@vertexcloud.example.com", + "avatar": "https://picsum.photos/200/200?random=1", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York", + } + users = [ + jordan, + {"userId": "user_2", "fullName": "Priya Nair", "displayName": "Priya", + "email": "priya.nair@vertexcloud.example.com", + "avatar": "https://picsum.photos/200/200?random=2", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_3", "fullName": "Diego Morales", "displayName": "Diego", + "email": "diego.morales@vertexcloud.example.com", + "avatar": "https://picsum.photos/200/200?random=3", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"}, + {"userId": "user_4", "fullName": "Mei Lin", "displayName": "Mei", + "email": "mei.lin@vertexcloud.example.com", + "avatar": "https://picsum.photos/200/200?random=4", "status": "away", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"}, + ] + channels = [ + {"channelId": "general", "name": "general", "description": "Company-wide announcements", + "topic": "", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_2", + "createdAt": "2025-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "random", "name": "random", "description": "Non-work banter", + "topic": "", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_2", + "createdAt": "2025-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "customer-success", "name": "customer-success", + "description": "Customer Success team — renewals, onboarding, escalations", + "topic": "Keeping customers happy and renewing", "isPrivate": False, "isStarred": True, + "members": ["user_1", "user_2", "user_3"], "createdBy": "user_3", + "createdAt": "2025-02-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ] + messages = { + "general": [ + {"messageId": "msg_1", "senderId": "user_2", "content": "Morning team! Don't forget the all-hands at 11.", + "timestamp": "2026-06-22T13:30:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + "random": [ + {"messageId": "msg_2", "senderId": "user_4", "content": "Anyone tried the new coffee place on 3rd?", + "timestamp": "2026-06-21T18:10:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + "customer-success": [ + {"messageId": "msg_3", "senderId": "user_3", + "content": "Reminder: please keep renewal notes updated in Salesforce as you work accounts.", + "timestamp": "2026-06-19T15:45:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + } + return { + "currentUser": jordan, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Vertex Cloud", "icon": ""}, + "users": users, + "channels": channels, + "messages": messages, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + + +def inject(url, state, label): + resp = http_post(f'{url}/post?sid={sid}', {'action': 'set', 'state': state}) + assert resp.status_code == 200, f'{label} injection failed: {resp.status_code} {resp.text}' + go = http_get(f'{url}/go?sid={sid}').json() + assert go.get('initial_state') is not None, f'{label} initial_state is None after injection' + print(f'{label} state injected and verified.') + + +inject(SALESFORCE_URL, build_salesforce_state(), 'Salesforce') +inject(GMAIL_URL, build_gmail_state(), 'Gmail') +inject(SLACK_URL, build_slack_state(), 'Slack') + + +# --- Launch browser (primary mock = Salesforce) --- +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'] + if _parts and 'google-chrome' in _parts[0] \ + and not any(p.startswith('--user-data-dir') for p in _parts): + _parts[1:1] = [f'--user-data-dir={CHROME_PROFILE_DIR}'] + _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 = SALESFORCE_URL +launch_gui(f'google-chrome "{SALESFORCE_URL}/?sid={sid}"', delay_sec=2.0) +_open_remaining_mock_tabs(_primary_mock_url) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {SALESFORCE_URL}/?sid={sid}') diff --git a/am_renewal_outreach_002/reward.py b/am_renewal_outreach_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..b21b127577b94575e73302faa81046b702265de6 --- /dev/null +++ b/am_renewal_outreach_002/reward.py @@ -0,0 +1,427 @@ +# --- 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: AM Renewal Outreach — Northwind Traders renewal check-in +Task ID: am_renewal_outreach_002 +Domain: mock_websites (salesforce_mock + gmail_mock + slack_mock) + +Scoring (1.0 total), all programmatic / deterministic — verifies only the +NEW artifacts the agent must create (identified by id-set diff vs initial_state, +so pre-existing distractor records — incl. the old sent email to Karen Walsh and +the old customer-success message — never earn points): + + SALESFORCE task (0.34): + - 0.18 NEW 'task' activity related to the Northwind renewal (opp-1 / account-1), + with renewal/check-in intent and assigned to Jordan (user-1 when present) + - 0.16 that task has dueDate 2026-07-01 AND status 'Open' (not completed) + GMAIL email (0.33): + - 0.13 NEW email in 'sent' folder addressed to karen.walsh@northwind-traders.example.com + - 0.10 its subject matches the explicitly required subject, allowing case/spacing/punctuation variants + - 0.10 its body proposes a renewal call before the renewal timing/date + SLACK message (0.33): + - 0.16 NEW message posted by Jordan (user_1) in the 'customer-success' channel + - 0.17 that message says Northwind/Karen renewal outreach is underway/sent +""" +import html +import os +import re +import sys +from datetime import date + +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) + +MOCKS = { + 'salesforce': 'http://28.7.184.198:8175', + 'gmail': 'http://28.7.184.198:8138', + 'slack': 'http://28.7.184.198:8178', +} + +# --------------------------------------------------------------------------- +# Egress proxy helper (mandatory) +# --------------------------------------------------------------------------- +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def resolve_proxy(probe_url): + try: + requests.get(probe_url, timeout=8) + return None + except Exception: + pass + for candidate in PROXY_CANDIDATES: + if not candidate: + continue + try: + requests.get(probe_url, timeout=12, + proxies={'http': candidate, 'https': candidate}) + return candidate + except Exception: + continue + return None + + +PROXY = resolve_proxy(f"{MOCKS['salesforce']}/go?sid=conn-probe") +PROXIES = {'http': PROXY, 'https': PROXY} if PROXY else None + + +def fetch(name): + url = MOCKS[name] + data = requests.get(f'{url}/go?sid={sid}', timeout=20, proxies=PROXIES).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + + +# --------------------------------------------------------------------------- +# Fetch all three mock states up front (precondition gate) +# --------------------------------------------------------------------------- +try: + sf_init, sf_cur = fetch('salesforce') + gm_init, gm_cur = fetch('gmail') + sl_init, sl_cur = fetch('slack') +except Exception as e: + print(f'CRITICAL: Cannot fetch mock state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def strip_html(s): + return re.sub(r'<[^>]+>', ' ', str(s or '')) + + +TARGET_EMAIL_SUBJECT = 'Northwind Traders renewal call before July 15' +EXPECTED_TASK_DUE_DATE = date(2026, 7, 1) +EXPECTED_RENEWAL_DATE = date(2026, 7, 15) + + +def norm(s): + text = html.unescape(strip_html(s)) + text = re.sub(r'[\u2010-\u2015]', '-', text) + return re.sub(r'\s+', ' ', text).strip().casefold() + + +def loose(s): + """Normalize user-entered prose for case/whitespace/punctuation-tolerant matching.""" + return re.sub(r'\s+', ' ', re.sub(r'[^a-z0-9]+', ' ', norm(s))).strip() + + +def contains_any(text, phrases): + haystack = f" {loose(text)} " + return any(f" {loose(phrase)} " in haystack for phrase in phrases) + + +def text_blob(*values): + return ' '.join(str(v or '') for v in values) + + +def canonical_subject(s): + return loose(s) + + +def subject_matches_target(subject): + return canonical_subject(subject) == canonical_subject(TARGET_EMAIL_SUBJECT) + + +def norm_channel_name(s): + return norm(s).lstrip('#').strip() + + +MONTH_NAMES = { + 1: ('january', 'jan'), 2: ('february', 'feb'), 3: ('march', 'mar'), + 4: ('april', 'apr'), 5: ('may', 'may'), 6: ('june', 'jun'), + 7: ('july', 'jul'), 8: ('august', 'aug'), 9: ('september', 'sep'), + 10: ('october', 'oct'), 11: ('november', 'nov'), 12: ('december', 'dec'), +} + + +def ordinal(n): + if 10 <= n % 100 <= 20: + suffix = 'th' + else: + suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th') + return f'{n}{suffix}' + + +def mentions_date(text, expected): + t = norm(text) + month_full, month_short = MONTH_NAMES[expected.month] + day = expected.day + year = expected.year + variants = { + f'{month_full} {day}', f'{month_full} {ordinal(day)}', + f'{month_full} {day}, {year}', f'{month_full} {ordinal(day)}, {year}', + f'{month_full} {day} {year}', f'{month_full} {ordinal(day)} {year}', + f'{month_short} {day}', f'{month_short} {ordinal(day)}', + f'{month_short} {day}, {year}', f'{month_short} {ordinal(day)}, {year}', + f'{month_short} {day} {year}', f'{month_short} {ordinal(day)} {year}', + f'{day} {month_full}', f'{ordinal(day)} {month_full}', + f'{day} {month_short}', f'{ordinal(day)} {month_short}', + f'{day} {month_full} {year}', f'{ordinal(day)} {month_full} {year}', + f'{day} {month_short} {year}', f'{ordinal(day)} {month_short} {year}', + expected.isoformat(), + } + if any(v in t for v in variants): + return True + + m = expected.month + numeric_patterns = [ + rf'\b0?{m}[/.-]0?{day}(?:[/.-]{year})?\b', + rf'\b{year}[/.-]0?{m}[/.-]0?{day}\b', + rf'\b0?{day}[/.-]0?{m}(?:[/.-]{year})?\b', + ] + return any(re.search(p, t) for p in numeric_patterns) + + +def mentions_renewal_timing(text): + return mentions_date(text, EXPECTED_RENEWAL_DATE) or contains_any(text, [ + 'renewal date', 'renewal deadline', 'renewal close date', 'close date', + 'before renewal', 'before the renewal', 'before your renewal', + 'ahead of renewal', 'ahead of the renewal', 'prior to renewal', + 'prior to the renewal', 'before it renews', 'before the contract renews', + ]) + + +def proposes_call(text): + call_intent = contains_any(text, [ + 'call', 'meeting', 'meet', 'chat', 'connect', 'sync', 'discussion', + 'discuss', 'conversation', 'touch base', 'talk', 'speak', + 'schedule time', 'set up time', + ]) + renewal_context = contains_any(text, ['renewal', 'renew', 'account']) \ + or mentions_renewal_timing(text) + return call_intent and renewal_context + + +def date_field_matches(value, expected): + if not value: + return False + text = norm(value) + if text[:10] == expected.isoformat(): + return True + return mentions_date(text, expected) + + +total_score = 0.0 + +# =========================================================================== +# SALESFORCE — new renewal check-in task (0.34) +# =========================================================================== +try: + init_ids = {a.get('activityId') for a in sf_init.get('activities', [])} + new_acts = [a for a in sf_cur.get('activities', []) + if a.get('activityId') not in init_ids] + + # Candidate = NEW task related to the Northwind renewal (opp-1 or account-1) + # with renewal/check-in intent. The relation preserves the customer/opportunity + # signal, so the subject can use natural wording like "call Karen" or + # "renewal follow-up" without requiring exact tokens. + sf_task = None + for a in new_acts: + if norm(a.get('type')) != 'task': + continue + task_text = text_blob(a.get('subject'), a.get('description'), a.get('comments'), a.get('notes')) + related_type = norm(a.get('relatedToType')) + related_ok = (related_type == 'opportunity' and a.get('relatedToId') == 'opp-1') \ + or (related_type == 'account' and a.get('relatedToId') == 'account-1') + assigned_ok = not a.get('assignedToId') or a.get('assignedToId') == 'user-1' + intent_ok = contains_any(task_text, [ + 'renewal', 'renew', 'check in', 'check-in', 'follow up', + 'follow-up', 'outreach', 'call', 'meeting', 'touch base', + 'karen', 'walsh', + ]) + if related_ok and assigned_ok and intent_ok: + sf_task = a + break + + # Component SF-1 (0.18): correct new task exists, right relation/owner/intent + if sf_task is not None: + print(f"PASS: SF new renewal task on Northwind (id={sf_task.get('activityId')}, " + f"subject={sf_task.get('subject')!r}, related={sf_task.get('relatedToId')}) (0.18)") + total_score += 0.18 + + # Component SF-2 (0.16): dueDate 2026-07-01 AND status Open + due_ok = date_field_matches(sf_task.get('dueDate'), EXPECTED_TASK_DUE_DATE) + status_ok = norm(sf_task.get('status')) in ('open', 'not started', 'in progress', 'pending') + if due_ok and status_ok: + print(f"PASS: SF task dueDate=2026-07-01 and status Open " + f"(status={sf_task.get('status')!r}) (0.16)") + total_score += 0.16 + else: + print(f"FAIL: SF task date/status — dueDate={sf_task.get('dueDate')!r} " + f"(want 2026-07-01), status={sf_task.get('status')!r} (want Open)") + else: + print(f"FAIL: SF — no NEW task related to opp-1/account-1 with " + f"renewal/check-in intent assigned to user-1 when present " + f"(new activities: {[a.get('activityId') for a in new_acts]})") +except Exception as e: + print(f'ERROR: Salesforce component — {e}') + +# =========================================================================== +# GMAIL — new renewal outreach email to Karen Walsh (0.33) +# =========================================================================== +KAREN = 'karen.walsh@northwind-traders.example.com' +try: + init_ids = {e.get('id') for e in gm_init.get('emails', [])} + new_emails = [e for e in gm_cur.get('emails', []) + if e.get('id') not in init_ids] + + # NEW sent email addressed to Karen Walsh; prefer the explicitly named + # outreach email but keep body scoring independent so one subject typo + # does not erase otherwise correct outreach content. + sent_to_karen = None + sent_to_karen_emails = [] + exact_subject_email = None + for e in new_emails: + if norm(e.get('folder')) != 'sent': + continue + recips = [norm(t.get('email')) for t in e.get('to', [])] + if KAREN in recips: + sent_to_karen_emails.append(e) + if sent_to_karen is None: + sent_to_karen = e + if subject_matches_target(e.get('subject')): + exact_subject_email = e + + # Component GM-1 (0.13): new sent email to Karen Walsh exists + if sent_to_karen is not None: + print(f"PASS: Gmail NEW sent email to Karen Walsh " + f"(id={sent_to_karen.get('id')}, subject={sent_to_karen.get('subject')!r}) (0.13)") + total_score += 0.13 + + # Component GM-2 (0.10): subject matches the explicitly required instruction. + if exact_subject_email is not None: + print(f"PASS: Gmail subject matches required subject {TARGET_EMAIL_SUBJECT!r} (0.10)") + total_score += 0.10 + else: + print(f"FAIL: Gmail subject — expected required subject {TARGET_EMAIL_SUBJECT!r}; " + f"got {[e.get('subject') for e in sent_to_karen_emails]}") + + # Component GM-3 (0.10): body proposes a renewal call before the renewal timing. + # The fixed July-15 signal may appear in the required subject, while the body + # can naturally say "before your renewal date". + def email_body_ok(e): + body = strip_html(e.get('body')) + timing_ok = mentions_renewal_timing(body) or subject_matches_target(e.get('subject')) + return proposes_call(body) and timing_ok + + body_email = next((e for e in ([exact_subject_email] if exact_subject_email else []) + if e and email_body_ok(e)), None) + if body_email is None: + body_email = next((e for e in sent_to_karen_emails if email_body_ok(e)), None) + + if body_email is not None: + print("PASS: Gmail body proposes a renewal call before the renewal timing/date (0.10)") + total_score += 0.10 + else: + print("FAIL: Gmail body — need a sent-to-Karen email body proposing a renewal " + "call/meeting before the renewal timing/date") + else: + print(f"FAIL: Gmail — no NEW sent email addressed to {KAREN} " + f"(new emails: {[e.get('id') for e in new_emails]})") +except Exception as e: + print(f'ERROR: Gmail component — {e}') + +# =========================================================================== +# SLACK — new message in #customer-success (0.33) +# =========================================================================== +try: + # Resolve the customer-success channel id/name; the UI may expose the + # channel as either "customer-success" or "#customer-success". + def customer_success_keys(state): + keys = set() + for c in state.get('channels', []): + name = c.get('name') + channel_id = c.get('channelId') + if norm_channel_name(name) == 'customer-success' \ + or norm_channel_name(channel_id) == 'customer-success': + for value in (channel_id, name, norm_channel_name(name), + f"#{norm_channel_name(name)}"): + if value: + keys.add(value) + return keys + + cs_keys = customer_success_keys(sl_cur) or customer_success_keys(sl_init) + + if not cs_keys: + print("FAIL: Slack — 'customer-success' channel not found") + else: + def messages_for_channel(state, keys): + allowed = {norm_channel_name(k) for k in keys if k} + messages = [] + seen = set() + for key, vals in (state.get('messages') or {}).items(): + if key in keys or norm_channel_name(key) in allowed: + for m in vals or []: + msg_id = m.get('messageId') or id(m) + if msg_id not in seen: + seen.add(msg_id) + messages.append(m) + return messages + + init_msgs = messages_for_channel(sl_init, cs_keys) + cur_msgs = messages_for_channel(sl_cur, cs_keys) + init_msg_ids = {m.get('messageId') for m in init_msgs} + new_msgs = [m for m in cur_msgs if m.get('messageId') not in init_msg_ids] + + # Component SL-1 (0.16): NEW message by Jordan (user_1) in customer-success + my_new = [m for m in new_msgs if m.get('senderId') == 'user_1'] + if my_new: + print(f"PASS: Slack NEW message by user_1 in #customer-success " + f"({len(my_new)} new) (0.16)") + total_score += 0.16 + + # Component SL-2 (0.17): content says renewal outreach to + # Northwind/Karen is underway/sent. The instruction does not require + # the Slack note to repeat the fixed July-15 date. + def content_ok(m): + t = m.get('content') + customer = contains_any(t, ['northwind', 'karen walsh', 'karen', 'walsh']) + renewal = contains_any(t, ['renewal', 'renew', 'renewing', 'outreach', + 'check in', 'check-in', 'call', 'meeting']) + underway = contains_any(t, [ + 'underway', 'kicked off', 'kicked-off', 'reached out', 'reach out', + 'emailed', 'email sent', 'sent email', 'contacted', 'check-in', + 'check in', 'sent', 'outreach', 'started', 'initiated', + 'in progress', 'following up', 'followed up', 'handled', 'done', + ]) + return customer and renewal and underway + + good = next((m for m in my_new if content_ok(m)), None) + if good is not None: + print("PASS: Slack message reports Northwind/Karen renewal outreach underway (0.17)") + total_score += 0.17 + else: + print(f"FAIL: Slack message content — need Northwind/Karen + renewal/check-in " + f"+ outreach-underway/sent. Contents: {[norm(m.get('content'))[:80] for m in my_new]}") + else: + print(f"FAIL: Slack — no NEW message by user_1 in #customer-success " + f"(new msgs: {[m.get('messageId') for m in new_msgs]})") +except Exception as e: + print(f'ERROR: Slack component — {e}') + +# =========================================================================== +final_score = round(min(total_score, 1.0), 4) +print(f'\nScore: {total_score}/1.0') +print(f'REWARD: {final_score}') diff --git a/am_renewal_outreach_002/reward_label.json b/am_renewal_outreach_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..c0157a70bc3d21c6615559a9ea70f2311aad39f8 --- /dev/null +++ b/am_renewal_outreach_002/reward_label.json @@ -0,0 +1,85 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_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 20:16:52", + "label": { + "task_id": "am_renewal_outreach_002", + "domain": "mock_websites", + "summary": "验证代理是否在Salesforce中创建Northwind续签任务、在Gmail中发送给Karen Walsh的续签邮件、并在Slack customer-success频道发布续签外展消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "salesforce_mock", + "gmail_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "SF-1: 新建Salesforce续签任务", + "weight": 0.18, + "description": "检查是否存在新增的Task活动,与Northwind续签相关,分配给Jordan,且意图匹配", + "check_logic": "通过id-set diff找出sf_cur中新增的activities;筛选type为task、relatedToId为opp-1或account-1、assignedToId为空或user-1、且subject/description/comments/notes中包含renewal/renew/check in/check-in/follow up/follow-up/outreach/call/meeting/touch base/karen/walsh等关键词的记录", + "pass_condition": "存在至少一条满足上述全部条件的新增task记录" + }, + { + "name": "SF-2: 任务截止日期与状态", + "weight": 0.16, + "description": "检查上述新建任务的dueDate为2026-07-01且状态为未完成", + "check_logic": "对SF-1中找到的task,检查dueDate字段是否匹配2026-07-01(支持ISO格式或自然语言变体),且status归一化后为open/not started/in progress/pending之一", + "pass_condition": "dueDate匹配2026-07-01且status为Open(或其同义词)" + }, + { + "name": "GM-1: 新建发送给Karen的邮件", + "weight": 0.13, + "description": "检查Gmail sent文件夹中是否存在新增的发送给Karen Walsh的邮件", + "check_logic": "通过id-set diff找出gm_cur中新增的emails;筛选folder为sent且to列表中包含karen.walsh@northwind-traders.example.com的邮件", + "pass_condition": "存在至少一封新增的发送给指定Karen邮箱的sent邮件" + }, + { + "name": "GM-2: 邮件主题匹配", + "weight": 0.1, + "description": "检查邮件主题是否与要求的主题匹配(忽略大小写、空格、标点)", + "check_logic": "对发送给Karen的邮件,使用canonical_subject(loose归一化)比较是否等于'Northwind Traders renewal call before July 15'的loose归一化结果", + "pass_condition": "至少一封邮件的主题经loose归一化后与目标主题完全一致" + }, + { + "name": "GM-3: 邮件正文提议续签通话", + "weight": 0.1, + "description": "检查邮件正文是否提议在续签日期前进行通话/会议", + "check_logic": "对候选邮件(优先主题完全匹配的邮件,否则所有发给Karen的邮件),检查body经strip_html后:proposes_call(包含call/meeting等意图词且包含renewal/account或提及续签时间)且timing_ok(正文提及renewal timing或主题已完全匹配目标主题)", + "pass_condition": "至少一封邮件正文表达通话/会议意图,并关联续签上下文或提及续签日期" + }, + { + "name": "SL-1: Slack新建消息", + "weight": 0.16, + "description": "检查在customer-success频道中是否有user_1(Jordan)发布的新消息", + "check_logic": "通过channel名称或ID定位customer-success频道;通过id-set diff找出该频道下新增的消息;筛选senderId为user_1的消息", + "pass_condition": "存在至少一条user_1在customer-success频道的新增消息" + }, + { + "name": "SL-2: 消息内容报告续签外展状态", + "weight": 0.17, + "description": "检查消息内容是否表明Northwind/Karen的续签外展正在进行或已发送", + "check_logic": "对SL-1中user_1的新消息,检查content是否同时满足:customer(包含northwind/karen walsh/karen/walsh)、renewal(包含renewal/renew/renewing/outreach/check in/check-in/call/meeting)、underway(包含underway/kicked off/reached out/emailed/sent email/contacted/sent/started/initiated/in progress/following up/handled/done等)", + "pass_condition": "至少一条消息内容同时包含客户标识、续签意图和外展已进行/已发送的表述" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终用min(total_score, 1.0)钳制到上限1.0,并四舍五入到4位小数", + "failure_modes": [ + "无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0", + "无法从任一mock服务拉取状态时打印CRITICAL并返回0.0", + "Salesforce中未找到符合条件的新增task时SF组件不得分", + "Gmail中未找到新增sent邮件或收件人不是Karen时GM组件不得分", + "Slack中未找到customer-success频道时Slack组件不得分", + "Slack中未找到user_1的新消息时SL组件不得分", + "各子组件字段检查失败(如日期、状态、主题、正文、内容不匹配)时对应子组件不得分", + "各模块异常被捕获后打印ERROR,该模块不得分但不影响其他模块" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接退出并返回0.0。接着通过HTTP GET拉取salesforce_mock、gmail_mock、slack_mock的initial_state和current_state,拉取失败同样返回0.0。评分采用id-set差分策略:将current_state中的记录ID与initial_state对比,仅对新增的artifacts进行评分,排除预存干扰项。Salesforce模块(0.34分)先检查新增task是否关联opp-1/account-1、分配给user-1且意图匹配续签/检查(0.18分),再检查该task的dueDate为2026-07-01且status为Open(0.16分)。Gmail模块(0.33分)检查新增sent邮件是否发给karen.walsh@northwind-traders.example.com(0.13分),主题是否匹配'Northwind Traders renewal call before July 15'(0.10分),正文是否提议续签通话并关联续签时间(0.10分)。Slack模块(0.33分)先定位customer-success频道,检查user_1的新消息(0.16分),再验证消息内容同时提及Northwind/Karen、续签以及外展正在进行/已发送(0.17分)。各组件独立评分,累加后通过min(total_score, 1.0)钳制上限并四舍五入输出最终REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: am_renewal_outreach_002\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (salesforce_mock + gmail_mock + slack_mock)\",所以 domain 是 mock_websites\n3. **summary**: 一句话概括。这个脚本验证代理是否在 Salesforce 中创建了新的 Northwind 续签任务、在 Gmail 中发送了给 Karen Walsh 的续签邮件、在 Slack 的 customer-success 频道发布了续签外展消息。\n4. **is_placeholder**: false,因为脚本有详细的评分逻辑,不是占位脚本。\n5. **data_sources**: 脚本从 /tmp/task_web_sid 读取 sid,从 salesforce_mock (http://28.7.186.212:8195)、gmail_mock (http://28.7.186.212:8158)、slack_mock (http://28.7.186.212:8198) 获取状态。\n6. **scoring_components**: \n - Salesforce 任务 (0.34 total):\n - Component SF-1 (0.18): 新的 task 活动,与 Northwind 续签相关 (opp-1/account-1),有续签/检查意图,分配给 Jordan (user-1)\n - Component SF-2 (0.16): 该任务的 dueDate 是 2026-07-01 且状态为 Open (或 not started/in progress/pending)\n - Gmail 邮件 (0.33 total):\n - Component GM-1 (0.13): 新的 sent 邮件发送给 karen.walsh@northwind-traders.example.com\n - Component GM-2 (0.10): 主题匹配 'Northwind Traders renewal call before July 15'(允许大小写/空格/标点变化)\n - Component GM-3 (0.10): 正文提议在续签日期前进行续签通话\n - Slack 消息 (0.33 total):\n - Component SL-1 (0.16): user_1 (Jordan) 在 customer-success 频道发布的新消息\n - Component SL-2 (0.17): 消息内容表明 Northwind/Karen 的续签外展正在进行/已发送\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后用 `round(min(total_score, 1.0), 4)` 钳制到上限 1.0。\n9. **failure_modes**: \n - 无法从 /tmp/task_web_sid 读取 sid → CRITICAL,REWARD: 0.0,sys.exit(0)\n - 无法获取 mock 状态 → CRITICAL,REWARD: 0.0,sys.exit(0)\n - 找不到 customer-success 频道 → 打印 FAIL,该组件不得分\n - 各组件检查失败会打印 FAIL 并跳过加分\n - 异常会被捕获打印 ERROR 但不退出\n\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 解析代理设置,尝试直连或经代理访问三个 mock 服务。\n - 并行(顺序)拉取 salesforce、gmail、slack 的 initial_state 和 current_state,失败则返回 0.0。\n - 通过 id-set diff 识别每个 mock 中新增的 artifacts,排除预存在的干扰记录。\n - Salesforce: 检查新增 task 是否关联 opp-1/account-1、分配给 user-1、意图匹配续签/检查;再检查 dueDate 和状态。\n - Gmail: 检查新增 sent 邮件是否发给 Karen Walsh;主题是否匹配目标;正文是否提议续签通话并提及续签时间。\n - Slack: 定位 customer-success 频道,检查 user_1 的新消息;内容是否包含 Northwind/Karen、续签、外展进行中/已发送。\n - 累加各通过组件分值,最终用 min(total_score, 1.0) 钳制并四舍五入到 4 位小数。\n\n11. **confidence**: 1.0,因为代码非常清晰完整。\n\n让我再仔细检查一下各个组件的权重和逻辑:\n\nSalesforce:\n- SF-1: 0.18 (new task, related to opp-1/account-1, assigned to user-1 when present, intent matches)\n- SF-2: 0.16 (dueDate 2026-07-01 AND status Open)\n- Total: 0.34\n\nGmail:\n- GM-1: 0.13 (new sent email to KAREN)\n- GM-2: 0.10 (subject matches target)\n- GM-3: 0.10 (body proposes renewal call before renewal timing)\n- Total: 0.33\n\nSlack:\n- SL-1: 0.16 (new message by user_1 in customer-success)\n- SL-2: 0.17 (content says Northwind/Karen renewal outreach underway/sent)\n- Total: 0.33\n\nGrand total: 0.34 + 0.33 + 0.33 = 1.0\n\nFailure modes:\n- sid read failure\n- mock fetch failure\n- slack channel not found (causes fail for slack components)\n- missing new artifacts\n- incorrect fields/dates/status/subject/body/content\n\n我需要确保 JSON 格式完全符合要求,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"am_renewal_outreach_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证代理是否在Salesforce中创建Northwind续签任务、在Gmail中发送给Karen Walsh的续签邮件、并在Slack customer-success频道发布续格外展消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"salesforce_mock\",\n \"gmail_mock\",\n \"slack_mock\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"SF-1: 新建Salesforce续签任务\",\n \"weight\": 0.18,\n \"description\": \"检查是否存在新增的Task活动,与Northwind续签相关,分配给Jordan,且意图匹配\",\n \"check_logic\": \"通过id-set diff找出sf_cur中新增的activities;筛选type为task、relatedToId为opp-1或account-1、assignedToId为空或user-1、且subject/description/comments/notes中包含renewal/renew/check in/check-in/follow up/follow-up/outreach/call/meeting/touch base/karen/walsh等关键词的记录\",\n \"pass_condition\": \"存在至少一条满足上述全部条件的新增task记录\"\n },\n {\n \"name\": \"SF-2: 任务截止日期与状态\",\n \"weight\": 0.16,\n \"description\": \"检查上述新建任务的dueDate为2026-07-01且状态为未完成\",\n \"check_logic\": \"对SF-1中找到的task,检查dueDate字段是否匹配2026-07-01(支持ISO格式或自然语言变体),且status归一化后为open/not started/in progress/pending之一\",\n \"pass_condition\": \"dueDate匹配2026-07-01且status为Open(或其同义词)\"\n },\n {\n \"name\": \"GM-1: 新建发送给Karen的邮件\",\n \"weight\": 0.13,\n \"description\": \"检查Gmail sent文件夹中是否存在新增的发送给Karen Walsh的邮件\",\n \"check_logic\": \"通过id-set diff找出gm_cur中新增的emails;筛选folder为sent且to列表中包含karen.walsh@northwind-traders.example.com的邮件\",\n \"pass_condition\": \"存在至少一封新增的发送给指定Karen邮箱的sent邮件\"\n },\n {\n \"name\": \"GM-2: 邮件主题匹配\",\n \"weight\": 0.10,\n \"description\": \"检查邮件主题是否与要求的主题匹配(忽略大小写、空格、标点)\",\n \"check_logic\": \"对发送给Karen的邮件,使用canonical_subject(loose归一化)比较是否等于'Northwind Traders renewal call before July 15'的loose归一化结果\",\n \"pass_condition\": \"至少一封邮件的主题经loose归一化后与目标主题完全一致\"\n },\n {\n \"name\": \"GM-3: 邮件正文提议续签通话\",\n \"weight\": 0.10,\n \"description\": \"检查邮件正文是否提议在续签日期前进行通话/会议\",\n \"check_logic\": \"对候选邮件(优先主题完全匹配的邮件,否则所有发给Karen的邮件),检查body经strip_html后:proposes_call(包含call/meeting等意图词且包含renewal/account或提及续签时间)且timing_ok(正文提及renewal timing或主题已完全匹配目标主题)\",\n \"pass_condition\": \"至少一封邮件正文表达通话/会议意图,并关联续签上下文或提及续签日期\"\n },\n {\n \"name\": \"SL-1: Slack新建消息\",\n \"weight\": 0.16,\n \"description\": \"检查在customer-success频道中是否有user_1(Jordan)发布的新消息\",\n \"check_logic\": \"通过channel名称或ID定位customer-success频道;通过id-set diff找出该频道下新增的消息;筛选senderId为user_1的消息\",\n \"pass_condition\": \"存在至少一条user_1在customer-success频道的新增消息\"\n },\n {\n \"name\": \"SL-2: 消息内容报告续签外展状态\",\n \"weight\": 0.17,\n \"description\": \"检查消息内容是否表明Northwind/Karen的续签外展正在进行或已发送\",\n \"check_logic\": \"对SL-1中user_1的新消息,检查content是否同时满足:customer(包含northwind/karen walsh/karen/walsh)、renewal(包含renewal/renew/renewing/outreach/check in/check-in/call/meeting)、underway(包含underway/kicked off/reached out/emailed/sent email/contacted/sent/started/initiated/in progress/following up/handled/done等)\",\n \"pass_condition\": \"至少一条消息内容同时包含客户标识、续签意图和外展已进行/已发送的表述\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终用min(total_score, 1.0)钳制到上限1.0,并四舍五入到4位小数\",\n \"failure_modes\": [\n \"无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0\",\n \"无法从任一mock服务拉取状态时打印CRITICAL并返回0.0\",\n \"Salesforce中未找到符合条件的新增task时SF组件不得分\",\n \"Gmail中未找到新增sent邮件或收件人不是Karen时GM组件不得分\",\n \"Slack中未找到customer-success频道时Slack组件不得分\",\n \"Slack中未找到user_1的新消息时SL组件不得分\",\n \"各子组件字段检查失败(如日期、状态、主题、正文、内容不匹配)时对应子组件不得分\",\n \"各模块异常被捕获后打印ERROR,该模块不得分但不影响其他模块\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接退出并返回0.0。接着通过HTTP GET拉取salesforce_mock、gmail_mock、slack_mock的initial_state和current_state,拉取失败同样返回0.0。评分采用id-set差分策略:将current_state中的记录ID与initial_state对比,仅对新增的artifacts进行评分,排除预存干扰项。Salesforce模块(0.34分)先检查新增task是否关联opp-1/account-1、分配给user-1且意图匹配续签/检查(0.18分),再检查该task的dueDate为2026-07-01且status为Open(0.16分)。Gmail模块(0.33分)检查新增sent邮件是否发给karen.walsh@northwind-traders.example.com(0.13分),主题是否匹配'Northwind Traders renewal call before July 15'(0.10分),正文是否提议续签通话并关联续签时间(0.10分)。Slack模块(0.33分)先定位customer-success频道,检查user_1的新消息(0.16分),再验证消息内容同时提及Northwind/Karen、续签以及外展正在进行/已发送(0.17分)。各组件独立评分,累加后通过min(total_score, 1.0)钳制上限并四舍五入输出最终REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n我需要确保:\n- 没有 markdown 代码块标记\n- 第一个字符是 {\n- 最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- JSON 格式正确\n\n让我再检查一下 `data_sources` 字段。代码中 MOCKS 定义了三个服务的 URL,但通常我们称它们为 salesforce_mock、gmail_mock、slack_mock。文件路径也提到了这些。还有 `/tmp/task_web_sid`。\n\n`scoring_components` 中的 `check_logic` 和 `pass_condition` 需要准确反映代码逻辑。\n\n对于 SF-1:\n- `related_ok`: relatedToType 为 opportunity 且 relatedToId 为 opp-1,或 relatedToType 为 account 且 relatedToId 为 account-1\n- `assigned_ok`: assignedToId 为空或为 user-1\n- `intent_ok`: task_text 包含特定关键词\n- 代码中 `if related_ok and assigned_ok and intent_ok`\n\n对于 SF-2:\n- `due_ok`: date_field_matches 检查 dueDate\n- `status_ok`: norm(status) in ('open', 'not started', 'in progress', 'pending')\n- 注意:代码中 `if due_ok and status_ok` 才加分\n\n对于 GM-1:\n- `sent_to_karen`: folder 为 sent,to 列表包含 KAREN\n\n对于 GM-2:\n- `exact_subject_email`: subject_matches_target\n- `subject_matches_target`: canonical_subject(subject) == canonical_subject(TARGET_EMAIL_SUBJECT)\n\n对于 GM-3:\n- `email_body_ok`: body 的 timing_ok 和 proposes_call\n- `timing_ok`: mentions_renewal_timing(body) or subject_matches_target(e.get('subject'))\n- `proposes_call`: call_intent and renewal_context\n- 注意:代码优先检查 exact_subject_email,然后检查 sent_to_karen_emails\n\n对于 SL-1:\n- `my_new`: new_msgs 中 senderId == 'user_1'\n\n对于 SL-2:\n- `content_ok`: customer and renewal and underway\n\n一切看起来都正确。\n\n关于 `failure_modes`:\n- 代码中 Slack 频道未找到时打印 \"FAIL: Slack — 'customer-success' channel not found\",然后进入 else 分支?不,代码是:\n```python\n if not cs_keys:\n print(\"FAIL: Slack — 'customer-success' channel not found\")\n else:\n ...\n```\n所以如果没有 cs_keys,Slack 组件不得分,但不会崩溃。\n\n关于 `score_aggregation`: 代码是 `final_score = round(min(total_score, 1.0), 4)`,所以是累加后钳制。\n\n关于 `is_placeholder`: false,因为脚本有完整的评分逻辑。\n\n关于 `confidence`: 1.0,因为代码非常清晰。\n\n让我再确认一下 domain。docstring 中写的是 \"Domain: mock_websites (salesforce_mock + gmail_mock + slack_mock)\"。按照要求,domain 应该是 mock_websites。\n\ntask_id: am_renewal_outreach_002\n\nsummary 需要一句话概括。\n\n好的,我认为 JSON 已经准备好了。 {\"task_id\":\"am_renewal_outreach_002\",\"domain\":\"mock_websites\",\"summary\":\"验证代理是否在Salesforce中创建Northwind续签任务、在Gmail中发送给Karen Walsh的续签邮件、并在Slack customer-success频道发布续签外展消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"salesforce_mock\",\"gmail_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"SF-1: 新建Salesforce续签任务\",\"weight\":0.18,\"description\":\"检查是否存在新增的Task活动,与Northwind续签相关,分配给Jordan,且意图匹配\",\"check_logic\":\"通过id-set diff找出sf_cur中新增的activities;筛选type为task、relatedToId为opp-1或account-1、assignedToId为空或user-1、且subject/description/comments/notes中包含renewal/renew/check in/check-in/follow up/follow-up/outreach/call/meeting/touch base/karen/walsh等关键词的记录\",\"pass_condition\":\"存在至少一条满足上述全部条件的新增task记录\"},{\"name\":\"SF-2: 任务截止日期与状态\",\"weight\":0.16,\"description\":\"检查上述新建任务的dueDate为2026-07-01且状态为未完成\",\"check_logic\":\"对SF-1中找到的task,检查dueDate字段是否匹配2026-07-01(支持ISO格式或自然语言变体),且status归一化后为open/not started/in progress/pending之一\",\"pass_condition\":\"dueDate匹配2026-07-01且status为Open(或其同义词)\"},{\"name\":\"GM-1: 新建发送给Karen的邮件\",\"weight\":0.13,\"description\":\"检查Gmail sent文件夹中是否存在新增的发送给Karen Walsh的邮件\",\"check_logic\":\"通过id-set diff找出gm_cur中新增的emails;筛选folder为sent且to列表中包含karen.walsh@northwind-traders.example.com的邮件\",\"pass_condition\":\"存在至少一封新增的发送给指定Karen邮箱的sent邮件\"},{\"name\":\"GM-2: 邮件主题匹配\",\"weight\":0.10,\"description\":\"检查邮件主题是否与要求的主题匹配(忽略大小写、空格、标点)\",\"check_logic\":\"对发送给Karen的邮件,使用canonical_subject(loose归一化)比较是否等于'Northwind Traders renewal call before July 15'的loose归一化结果\",\"pass_condition\":\"至少一封邮件的主题经loose归一化后与目标主题完全一致\"},{\"name\":\"GM-3: 邮件正文提议续签通话\",\"weight\":0.10,\"description\":\"检查邮件正文是否提议在续签日期前进行通话/会议\",\"check_logic\":\"对候选邮件(优先主题完全匹配的邮件,否则所有发给Karen的邮件),检查body经strip_html后:proposes_call(包含call/meeting等意图词且包含renewal/account或提及续签时间)且timing_ok(正文提及renewal timing或主题已完全匹配目标主题)\",\"pass_condition\":\"至少一封邮件正文表达通话/会议意图,并关联续签上下文或提及续签日期\"},{\"name\":\"SL-1: Slack新建消息\",\"weight\":0.16,\"description\":\"检查在customer-success频道中是否有user_1(Jordan)发布的新消息\",\"check_logic\":\"通过channel名称或ID定位customer-success频道;通过id-set diff找出该频道下新增的消息;筛选senderId为user_1的消息\",\"pass_condition\":\"存在至少一条user_1在customer-success频道的新增消息\"},{\"name\":\"SL-2: 消息内容报告续签外展状态\",\"weight\":0.17,\"description\":\"检查消息内容是否表明Northwind/Karen的续签外展正在进行或已发送\",\"check_logic\":\"对SL-1中user_1的新消息,检查content是否同时满足:customer(包含northwind/karen walsh/karen/walsh)、renewal(包含renewal/renew/renewing/outreach/check in/check-in/call/meeting)、underway(包含underway/kicked off/reached out/emailed/sent email/contacted/sent/started/initiated/in progress/following up/handled/done等)\",\"pass_condition\":\"至少一条消息内容同时包含客户标识、续签意图和外展已进行/已发送的表述\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终用min(total_score, 1.0)钳制到上限1.0,并四舍五入到4位小数\",\"failure_modes\":[\"无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0\",\"无法从任一mock服务拉取状态时打印CRITICAL并返回0.0\",\"Salesforce中未找到符合条件的新增task时SF组件不得分\",\"Gmail中未找到新增sent邮件或收件人不是Karen时GM组件不得分\",\"Slack中未找到customer-success频道时Slack组件不得分\",\"Slack中未找到user_1的新消息时SL组件不得分\",\"各子组件字段检查失败(如日期、状态、主题、正文、内容不匹配)时对应子组件不得分\",\"各模块异常被捕获后打印ERROR,该模块不得分但不影响其他模块\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接退出并返回0.0。接着通过HTTP GET拉取salesforce_mock、gmail_mock、slack_mock的initial_state和current_state,拉取失败同样返回0.0。评分采用id-set差分策略:将current_state中的记录ID与initial_state对比,仅对新增的artifacts进行评分,排除预存干扰项。Salesforce模块(0.34分)先检查新增task是否关联opp-1/account-1、分配给user-1且意图匹配续签/检查(0.18分),再检查该task的dueDate为2026-07-01且status为Open(0.16分)。Gmail模块(0.33分)检查新增sent邮件是否发给karen.walsh@northwind-traders.example.com(0.13分),主题是否匹配'Northwind Traders renewal call before July 15'(0.10分),正文是否提议续签通话并关联续签时间(0.10分)。Slack模块(0.33分)先定位customer-success频道,检查user_1的新消息(0.16分),再验证消息内容同时提及Northwind/Karen、续签以及外展正在进行/已发送(0.17分)。各组件独立评分,累加后通过min(total_score, 1.0)钳制上限并四舍五入输出最终REWARD。\",\"confidence\":1.0}" +} diff --git a/am_renewal_tracker_003/_cua_gym_vm_bridge.sh b/am_renewal_tracker_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/am_renewal_tracker_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/am_renewal_tracker_003/initial_setup.py b/am_renewal_tracker_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ed478bd4c3af7024bd0016bbdcb0c867a078bf2f --- /dev/null +++ b/am_renewal_tracker_003/initial_setup.py @@ -0,0 +1,486 @@ +# --- 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: Quarterly renewal review — Salesforce open renewals -> Notion tracker. +Task ID: am_renewal_tracker_003 +Domain: mock_websites (multi-mock: salesforce_mock + notion_mock) + +Persona: Jordan Avery (user-1), Account Manager / Renewals Manager at Vertex Cloud. + jordan.avery@vertexcloud.example.com. Today = 2026-06-24. + +PRE-TASK state ONLY. The Notion 'Renewal Tracker 2026' database MUST contain +ZERO rows (the agent's job is to add exactly three). Salesforce is read-only. + +DUAL-VM NOTE: /tmp is NOT shared between the initial_env and golden_env containers, +and the orchestrator does not sync the sid. This script therefore generates its OWN +sid, persists it on THIS VM, and injects the initial (pre-task) state under it. +golden_patch.py does the symmetric thing on the golden VM with its own sid. +""" +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', +} + +# --- Egress proxy --------------------------------------------------------- +# The mocks are only reachable via the cluster HTTPS proxy on this VM (no direct +# route to the public xlang.ai hosts). Auto-detect: try direct first, then the +# known cluster proxy. Chrome is launched through the same proxy. +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def _resolve_proxy(): + probe = f"{MOCKS['salesforce']}/go?sid=conn-probe" + try: + requests.get(probe, timeout=8) + return None + except Exception: + pass + for cand in PROXY_CANDIDATES: + if not cand: + continue + try: + requests.get(probe, timeout=12, proxies={'http': cand, 'https': cand}) + return cand + except Exception: + continue + raise RuntimeError('No working route to mock servers (direct and proxies all failed)') + + +PROXY = _resolve_proxy() +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + +# --- Session id (this VM only) ------------------------------------------- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid = {sid}') + + +# --------------------------------------------------------------------------- +# SALESFORCE initial state (read-only system of record for renewals) +# --------------------------------------------------------------------------- +def salesforce_state(): + user_1 = { + "userId": "user-1", "firstName": "Jordan", "lastName": "Avery", + "email": "jordan.avery@vertexcloud.example.com", "phone": "(555) 310-7742", + "title": "Account Manager", "department": "Renewals", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + } + + accounts = [ + {"accountId": "account-1", "name": "Northwind Traders", "type": "Customer", + "industry": "Logistics", "revenue": 58000000, "employees": 640, "ownerId": "user-1", + "billingStreet": "210 Commerce Blvd", "billingCity": "Columbus", "billingState": "OH", + "billingZip": "43004", "billingCountry": "USA"}, + {"accountId": "account-2", "name": "Globex Corp", "type": "Customer", + "industry": "Manufacturing", "revenue": 142000000, "employees": 2100, "ownerId": "user-1", + "billingStreet": "1 Globex Center", "billingCity": "San Jose", "billingState": "CA", + "billingZip": "95110", "billingCountry": "USA"}, + {"accountId": "account-3", "name": "Initech", "type": "Customer", + "industry": "Fintech", "revenue": 96000000, "employees": 880, "ownerId": "user-1", + "billingStreet": "4120 Office Park Dr", "billingCity": "Austin", "billingState": "TX", + "billingZip": "73301", "billingCountry": "USA"}, + {"accountId": "account-4", "name": "Soylent Industries", "type": "Customer", + "industry": "Food Tech", "revenue": 47000000, "employees": 410, "ownerId": "user-1", + "billingStreet": "88 Green Way", "billingCity": "Sacramento", "billingState": "CA", + "billingZip": "95814", "billingCountry": "USA"}, + {"accountId": "account-5", "name": "Umbrella Health", "type": "Customer", + "industry": "Healthcare", "revenue": 210000000, "employees": 3400, "ownerId": "user-1", + "billingStreet": "1200 Medical Pkwy", "billingCity": "Raleigh", "billingState": "NC", + "billingZip": "27601", "billingCountry": "USA"}, + {"accountId": "account-6", "name": "Hooli", "type": "Customer", + "industry": "Technology", "revenue": 320000000, "employees": 5200, "ownerId": "user-1", + "billingStreet": "500 Innovation Dr", "billingCity": "Palo Alto", "billingState": "CA", + "billingZip": "94301", "billingCountry": "USA"}, + ] + + contacts = [ + {"contactId": "contact-1", "accountId": "account-1", "firstName": "Karen", + "lastName": "Walsh", "title": "VP Operations", "department": "Operations", + "email": "karen.walsh@northwind-traders.example.com", "phone": "(555) 221-3380", + "ownerId": "user-1"}, + {"contactId": "contact-2", "accountId": "account-2", "firstName": "David", + "lastName": "Okafor", "title": "COO", "department": "Executive", + "email": "david.okafor@globex.example.com", "phone": "(555) 552-1140", + "ownerId": "user-1"}, + {"contactId": "contact-3", "accountId": "account-3", "firstName": "Priya", + "lastName": "Nair", "title": "VP Finance", "department": "Finance", + "email": "priya.nair@initech.example.com", "phone": "(555) 884-2201", + "ownerId": "user-1"}, + ] + + opportunities = [ + # QUALIFIES — closes 2026-07-15 (<= 2026-09-22), open (Negotiation), prob 75 -> Low + {"opportunityId": "opp-1", "name": "Northwind Traders – Annual Renewal", + "accountId": "account-1", "contactId": "contact-1", "amount": 120000, + "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 75, + "ownerId": "user-1"}, + # QUALIFIES — closes 2026-08-30, open (Proposal), prob 55 -> Medium + {"opportunityId": "opp-2", "name": "Globex Corp – Platform Renewal", + "accountId": "account-2", "contactId": "contact-2", "amount": 85000, + "closeDate": "2026-08-30", "stage": "Proposal", "probability": 55, + "ownerId": "user-1"}, + # QUALIFIES — closes 2026-09-10, open (Qualification), prob 35 -> High + {"opportunityId": "opp-3", "name": "Initech – Renewal & Upsell", + "accountId": "account-3", "contactId": "contact-3", "amount": 240000, + "closeDate": "2026-09-10", "stage": "Qualification", "probability": 35, + "ownerId": "user-1"}, + # DISTRACTOR — closes 2026-11-20 (AFTER 90-day window) + {"opportunityId": "opp-4", "name": "Soylent Industries – Renewal", + "accountId": "account-4", "contactId": None, "amount": 54000, + "closeDate": "2026-11-20", "stage": "Negotiation", "probability": 60, + "ownerId": "user-1"}, + # DISTRACTOR — closes 2026-12-31 (AFTER 90-day window) + {"opportunityId": "opp-5", "name": "Umbrella Health – Renewal", + "accountId": "account-5", "contactId": None, "amount": 300000, + "closeDate": "2026-12-31", "stage": "Value Proposition", "probability": 50, + "ownerId": "user-1"}, + # DISTRACTOR — already Closed Won (renewed in the past, 2026-05-30) + {"opportunityId": "opp-6", "name": "Hooli – Renewal", + "accountId": "account-6", "contactId": None, "amount": 95000, + "closeDate": "2026-05-30", "stage": "Closed Won", "probability": 100, + "ownerId": "user-1"}, + ] + + return { + "user": user_1, + "users": [user_1], + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# --------------------------------------------------------------------------- +# NOTION initial state — 'Renewal Tracker 2026' database with ZERO rows +# --------------------------------------------------------------------------- +DB_ID = "db-renewal-tracker-2026" + +NOTION_DB_PROPERTIES = [ + {"id": "prop-account", "name": "Account", "type": "text"}, + {"id": "prop-arr", "name": "ARR", "type": "number"}, + {"id": "prop-date", "name": "Renewal Date", "type": "date"}, + {"id": "prop-risk", "name": "Risk", "type": "select", + "options": ["Low", "Medium", "High"]}, + {"id": "prop-stage", "name": "Renewal Stage", "type": "select", + "options": ["Prospecting", "Qualification", "Needs Analysis", + "Value Proposition", "Proposal", "Negotiation"]}, +] + +NOTION_VISIBLE_PROPS = ["prop-account", "prop-arr", "prop-date", "prop-risk", "prop-stage"] + + +def notion_db_page(items): + return { + "id": DB_ID, + "title": "Renewal Tracker 2026", + "icon": "\U0001F4CA", + "cover": None, + "parentId": None, + "type": "database", + "viewType": "table", + "properties": NOTION_DB_PROPERTIES, + "views": [{ + "id": "view-table", "name": "Table View", "type": "table", + "filters": [], "sorts": [], "groupBy": None, + "visibleProperties": NOTION_VISIBLE_PROPS, + }], + "items": list(items), + "blockIds": [], + "favorite": False, + "createdDate": "2026-06-01T09:00:00.000Z", + } + + +def notion_state(): + return { + "user": {"id": "user-1", "name": "Jordan Avery", + "email": "jordan.avery@vertexcloud.example.com", "avatar": ""}, + "workspace": {"id": "ws-1", "name": "Vertex Cloud Renewals", "icon": "\U0001F3E2", + "members": ["user-1"]}, + "pages": { + DB_ID: notion_db_page([]), # ZERO rows pre-task + }, + "blocks": {}, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"}, + "notifications": [], + "pageOrder": [DB_ID], + } + + +# --------------------------------------------------------------------------- +# Inject initial state into BOTH mocks (action: "set") +# --------------------------------------------------------------------------- +STATE_BUILDERS = { + 'salesforce': salesforce_state, + 'notion': notion_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, proxies=PROXIES) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None after set' + print(f' injected {name}: initial_state OK') + +# Sanity: Notion tracker has zero rows pre-task +ng = requests.get(f'{MOCKS["notion"]}/go?sid={sid}', timeout=15, proxies=PROXIES).json() +rows = ng['current_state']['pages'][DB_ID]['items'] +assert rows == [], f'Expected 0 rows pre-task, found {len(rows)}' +print(f' notion tracker rows pre-task: {len(rows)} (correct)') + +print(f'Both mocks injected with sid={sid}') + + +# --------------------------------------------------------------------------- +# GUI-ready: launch Chrome on Salesforce (primary app) through the proxy +# --------------------------------------------------------------------------- +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 +_chrome_proxy = f'--proxy-server={PROXY}' if PROXY else '' +_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/am_renewal_tracker_003/reward.py b/am_renewal_tracker_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..06a95137a4aa270073b1b654594eac460879c2aa --- /dev/null +++ b/am_renewal_tracker_003/reward.py @@ -0,0 +1,427 @@ +# --- 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: Renewals tracker hygiene (Salesforce -> Notion 'Renewal Tracker 2026') +Task ID: am_renewal_tracker_003 +Domain: mock_websites (notion_mock) + +This task is FULLY DETERMINISTIC. The agent must add EXACTLY 3 rows to the +'Renewal Tracker 2026' Notion database, one per qualifying open renewal that +closes within 90 days of 2026-06-24 (i.e. closeDate <= 2026-09-22) and is still +open. Risk is derived from the opportunity's win probability. + +Expected rows (ground truth): + 1. Northwind Traders | ARR 120000 | 2026-07-15 | Risk Low | Stage Negotiation + 2. Globex Corp | ARR 85000 | 2026-08-30 | Risk Medium | Stage Proposal + 3. Initech | ARR 240000 | 2026-09-10 | Risk High | Stage Qualification + +Distractors that MUST NOT appear: Soylent Industries (renews 2026-11-20, outside +window), Umbrella Health (2026-12-31, outside window), Hooli (Closed Won, past). + +Scoring (programmatic only — NO LLM judge; the judge is unavailable here): + - 0.30 per correctly-populated expected row (ARR, Renewal Date, Risk, + Renewal Stage are parsed/normalized), keyed by Account name -> max 0.90 + - 0.10 cleanliness bonus: the database contains EXACTLY 3 rows AND none of the + distractor accounts are present. + Total = 1.0 + +Initial state has 0 rows -> every component fails -> 0.0. +""" + +import os +import re +import sys +from datetime import date, datetime, timedelta + +import requests + +NOTION_URL = 'http://28.7.184.198:8166' +DB_TITLE = 'Renewal Tracker 2026' +TODAY_TEXT = 'June 24, 2026' +WINDOW_DAYS = 90 + +# Ground-truth expected rows (derived from task_config business rules, not from peeking). +EXPECTED_ROWS = [ + {'Account': 'Northwind Traders', 'ARR': 120000, 'Renewal Date': '2026-07-15', 'Risk': 'Low', 'Renewal Stage': 'Negotiation'}, + {'Account': 'Globex Corp', 'ARR': 85000, 'Renewal Date': '2026-08-30', 'Risk': 'Medium', 'Renewal Stage': 'Proposal'}, + {'Account': 'Initech', 'ARR': 240000, 'Renewal Date': '2026-09-10', 'Risk': 'High', 'Renewal Stage': 'Qualification'}, +] +DISTRACTOR_ACCOUNTS = {'soylent industries', 'umbrella health', 'hooli'} + +# ---------------------------------------------------------------------------- +# Read sid +# ---------------------------------------------------------------------------- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +# ---------------------------------------------------------------------------- +# Egress proxy helper (MANDATORY) +# ---------------------------------------------------------------------------- +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def resolve_proxy(probe_url): + try: + requests.get(probe_url, timeout=8) + return None + except Exception: + pass + for candidate in PROXY_CANDIDATES: + if not candidate: + continue + try: + requests.get(probe_url, timeout=12, proxies={'http': candidate, 'https': candidate}) + return candidate + except Exception: + continue + return None + + +PROXY = resolve_proxy(f'{NOTION_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + +# ---------------------------------------------------------------------------- +# Fetch notion state +# ---------------------------------------------------------------------------- +try: + data = requests.get(f'{NOTION_URL}/go?sid={sid}', timeout=15, proxies=PROXIES).json() +except Exception as e: + print(f'CRITICAL: Cannot fetch notion state: {e}') + print('REWARD: 0.0') + sys.exit(0) + +current = data.get('current_state') or {} +if not current: + print('CRITICAL: current_state is None/empty') + print('REWARD: 0.0') + sys.exit(0) + +pages = current.get('pages') or {} + + +# ---------------------------------------------------------------------------- +# Helpers +# ---------------------------------------------------------------------------- +MONTHS = { + 'jan': 1, 'january': 1, 'feb': 2, 'february': 2, + 'mar': 3, 'march': 3, 'apr': 4, 'april': 4, 'may': 5, + 'jun': 6, 'june': 6, 'jul': 7, 'july': 7, + 'aug': 8, 'august': 8, 'sep': 9, 'sept': 9, 'september': 9, + 'oct': 10, 'october': 10, 'nov': 11, 'november': 11, + 'dec': 12, 'december': 12, +} + +PROPERTY_ALIASES = { + 'Account': ('Account', 'Account Name', 'Customer', 'Customer Name', 'Company'), + 'ARR': ('ARR', 'Annual Contract Value', 'Annual Recurring Revenue', 'Amount', 'Contract Value'), + 'Renewal Date': ('Renewal Date', 'Close Date', 'Closing Date', 'Renewal Close Date', 'Date'), + 'Risk': ('Risk', 'Risk Level', 'Renewal Risk'), + 'Renewal Stage': ('Renewal Stage', 'Current Sales Stage', 'Sales Stage', 'Stage'), +} + +RISK_ALIASES = { + 'Low': ('low', 'low risk', 'green', 'healthy'), + 'Medium': ('medium', 'medium risk', 'med', 'moderate', 'yellow'), + 'High': ('high', 'high risk', 'at risk', 'red'), +} + +STAGE_ALIASES = { + 'Negotiation': ('negotiation', 'negotiating', 'negotiate'), + 'Proposal': ('proposal', 'proposal sent', 'proposed'), + 'Qualification': ('qualification', 'qualified', 'qualifying'), +} + + +def text_from_value(v): + """Extract a display value from common Notion primitive/object shapes.""" + if v is None: + return '' + if isinstance(v, (int, float, bool, date, datetime)): + return str(v) + if isinstance(v, list): + parts = [text_from_value(x) for x in v] + return ' '.join(p for p in parts if p) + if isinstance(v, dict): + for key in ( + 'name', 'label', 'plain_text', 'text', 'content', 'title', 'start', + 'date', 'number', 'value', 'email', 'url', + ): + if key in v and v.get(key) not in (None, ''): + return text_from_value(v.get(key)) + for key in ('rich_text', 'select', 'status'): + if key in v and v.get(key) not in (None, ''): + return text_from_value(v.get(key)) + parts = [text_from_value(x) for x in v.values()] + return ' '.join(p for p in parts if p) + return str(v) + + +def norm_str(v): + return re.sub(r'\s+', ' ', text_from_value(v)).strip() + + +def canon_text(v): + return re.sub(r'[^a-z0-9]+', ' ', norm_str(v).lower()).strip() + + +def norm_num(v): + """Parse int/float or display strings like '$120,000', '120k', or 'USD 120000'.""" + if v is None: + return None + if isinstance(v, (int, float)): + return float(v) + s = norm_str(v).lower().replace(',', '') + s = s.replace('$', '').replace('usd', '').replace('arr', '') + match = re.search(r'-?\d+(?:\.\d+)?\s*([km])?', s) + if not match: + return None + try: + number = float(re.match(r'-?\d+(?:\.\d+)?', match.group(0)).group(0)) + except ValueError: + return None + suffix = match.group(1) + if suffix == 'k': + number *= 1000 + elif suffix == 'm': + number *= 1000000 + return number + + +def norm_date(v): + """Return a date object from common date/datetime strings and Notion date objects.""" + if v is None: + return None + if isinstance(v, datetime): + return v.date() + if isinstance(v, date): + return v + if isinstance(v, dict): + v = v.get('start') or v.get('date') or '' + s = norm_str(v) + if not s: + return None + s = re.sub(r'(\d)(st|nd|rd|th)\b', r'\1', s, flags=re.IGNORECASE) + iso = s.replace('Z', '+00:00') + try: + return datetime.fromisoformat(iso).date() + except ValueError: + pass + + numeric = re.search(r'\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b', s) + if numeric: + return build_date(numeric.group(1), numeric.group(2), numeric.group(3)) + + slash = re.search(r'\b(\d{1,2})[-/.](\d{1,2})[-/.](\d{2,4})\b', s) + if slash: + first, second, year = slash.groups() + if int(first) > 12: + day, month = first, second + else: + month, day = first, second + return build_date(year, month, day) + + month_first = re.search(r'\b([A-Za-z]+)\s+(\d{1,2})(?:,)?\s+(\d{4})\b', s) + if month_first and month_first.group(1).lower() in MONTHS: + month = MONTHS[month_first.group(1).lower()] + return build_date(month_first.group(3), month, month_first.group(2)) + + day_first = re.search(r'\b(\d{1,2})\s+([A-Za-z]+)(?:,)?\s+(\d{4})\b', s) + if day_first and day_first.group(2).lower() in MONTHS: + month = MONTHS[day_first.group(2).lower()] + return build_date(day_first.group(3), month, day_first.group(1)) + + return None + + +def build_date(year, month, day): + try: + year = int(year) + if year < 100: + year += 2000 + return date(year, int(month), int(day)) + except (TypeError, ValueError): + return None + + +def find_database(pages_map, title): + target = canon_text(title) + for pid, p in pages_map.items(): + if not isinstance(p, dict): + continue + if p.get('type') == 'database' and canon_text(p.get('title')) == target: + return pid, p + return None, None + + +def prop_id_by_alias(db, aliases): + """Resolve a property id from likely display names (case/punctuation-insensitive).""" + alias_keys = {canon_text(alias) for alias in aliases} + for prop in db.get('properties', []) or []: + if canon_text(prop.get('name')) in alias_keys: + return prop.get('id') + return None + + +def prop_value(row, prop_id, aliases=()): + props = row.get('properties', {}) or {} + if prop_id and prop_id in props: + return props.get(prop_id) + + alias_keys = {canon_text(alias) for alias in aliases} + for key, value in props.items(): + if canon_text(key) in alias_keys: + return value + for alias in aliases: + if alias in row: + return row.get(alias) + return None + + +def row_account_name(row, account_pid): + """Account may live in the Account property OR in the page title.""" + value = prop_value(row, account_pid, PROPERTY_ALIASES['Account']) + if value not in (None, ''): + return norm_str(value) + return norm_str(row.get('title')) + + +def account_matches(candidate, expected): + candidate_key = company_key(candidate) + expected_key = company_key(expected) + return ( + candidate_key == expected_key + or expected_key in candidate_key + or candidate_key in expected_key + ) + + +def company_key(value): + tokens = ['corp' if token == 'corporation' else token + for token in canon_text(value).split()] + return ' '.join(tokens) + + +def select_matches(value, expected, aliases): + value_key = canon_text(value) + expected_key = canon_text(expected) + if value_key == expected_key or expected_key in value_key: + return True + return any(canon_text(alias) == value_key or canon_text(alias) in value_key + for alias in aliases.get(expected, ())) + + +def verify_task(): + total_score = 0.0 + today = norm_date(TODAY_TEXT) + cutoff = today + timedelta(days=WINDOW_DAYS) if today else None + + # Precondition gate: the database must exist. + db_id, db = find_database(pages, DB_TITLE) + if db is None: + print(f"CRITICAL: database titled '{DB_TITLE}' not found") + print('REWARD: 0.0') + return 0.0 + + # Resolve property ids by name/alias (robust to differing prop-id schemes). + pid_account = prop_id_by_alias(db, PROPERTY_ALIASES['Account']) + pid_arr = prop_id_by_alias(db, PROPERTY_ALIASES['ARR']) + pid_date = prop_id_by_alias(db, PROPERTY_ALIASES['Renewal Date']) + pid_risk = prop_id_by_alias(db, PROPERTY_ALIASES['Risk']) + pid_stage = prop_id_by_alias(db, PROPERTY_ALIASES['Renewal Stage']) + + # Collect rows: prefer the database's ordered items list, fall back to + # any page whose parentId points at this database. + item_ids = db.get('items') or [] + rows = [pages[i] for i in item_ids if i in pages and isinstance(pages[i], dict)] + if not rows: + rows = [p for pid, p in pages.items() + if isinstance(p, dict) and p.get('parentId') == db_id and p.get('type') != 'database'] + + print(f'Found {len(rows)} row(s) in database "{DB_TITLE}"') + + # --- Components 1-3: each expected row, all required fields correct (0.30 each) --- + for idx, exp in enumerate(EXPECTED_ROWS, start=1): + try: + row = next( + (r for r in rows + if account_matches(row_account_name(r, pid_account), exp['Account'])), + None, + ) + if row is None: + print(f"FAIL: Component {idx} — row for account '{exp['Account']}' not found") + continue + + arr_value = prop_value(row, pid_arr, PROPERTY_ALIASES['ARR']) + date_value = prop_value(row, pid_date, PROPERTY_ALIASES['Renewal Date']) + risk_value = prop_value(row, pid_risk, PROPERTY_ALIASES['Risk']) + stage_value = prop_value(row, pid_stage, PROPERTY_ALIASES['Renewal Stage']) + + expected_date = norm_date(exp['Renewal Date']) + actual_date = norm_date(date_value) + arr_ok = norm_num(arr_value) == float(exp['ARR']) + date_ok = ( + actual_date == expected_date + and today is not None + and cutoff is not None + and today <= actual_date <= cutoff + ) + risk_ok = select_matches(risk_value, exp['Risk'], RISK_ALIASES) + stage_ok = select_matches(stage_value, exp['Renewal Stage'], STAGE_ALIASES) + + if arr_ok and date_ok and risk_ok and stage_ok: + print(f"PASS: Component {idx} — '{exp['Account']}' fully correct " + f"(ARR={exp['ARR']}, Date={exp['Renewal Date']}, Risk={exp['Risk']}, Stage={exp['Renewal Stage']}) (0.30 pts)") + total_score += 0.30 + else: + print(f"FAIL: Component {idx} — '{exp['Account']}' field mismatch: " + f"ARR_ok={arr_ok}(got {arr_value!r}), " + f"Date_ok={date_ok}(got {actual_date!r}), " + f"Risk_ok={risk_ok}(got {risk_value!r}), " + f"Stage_ok={stage_ok}(got {stage_value!r})") + except Exception as e: + print(f'ERROR: Component {idx} — {e}') + + # --- Component 4: cleanliness — exactly 3 rows AND no distractors (0.10) --- + try: + present_accounts = [row_account_name(r, pid_account) for r in rows] + distractors_present = { + distractor + for distractor in DISTRACTOR_ACCOUNTS + if any(account_matches(account, distractor) for account in present_accounts) + } + exact_count = (len(rows) == 3) + if exact_count and not distractors_present: + print('PASS: Component 4 — exactly 3 rows, no distractor accounts (0.10 pts)') + total_score += 0.10 + else: + print(f'FAIL: Component 4 — row_count={len(rows)} (expected 3), ' + f'distractors_present={sorted(distractors_present)}') + except Exception as e: + print(f'ERROR: Component 4 — {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/am_renewal_tracker_003/reward_label.json b/am_renewal_tracker_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..b9624a9bb4107d50f62e98739970aeac91ac85a6 --- /dev/null +++ b/am_renewal_tracker_003/reward_label.json @@ -0,0 +1,61 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_tracker_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 19:42:48", + "label": { + "task_id": "am_renewal_tracker_003", + "domain": "mock_websites", + "summary": "验证 agent 是否向 Notion 数据库 'Renewal Tracker 2026' 正确添加了恰好 3 条符合条件的续约跟踪记录,且未包含干扰项", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "notion_mock (http://28.7.186.212:8186)" + ], + "scoring_components": [ + { + "name": "Component 1 (Northwind Traders)", + "weight": 0.3, + "description": "检查是否存在 Northwind Traders 账户对应的记录,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期值完全匹配", + "check_logic": "在数据库行中通过 account_matches 查找账户名匹配的行,提取 ARR、Renewal Date、Risk、Renewal Stage 字段值,分别使用 norm_num、norm_date、select_matches 与预期值比较;其中日期还需满足 today(2026-06-24) <= actual_date <= cutoff(2026-09-22)", + "pass_condition": "找到该行且 arr_ok=True、date_ok=True、risk_ok=True、stage_ok=True" + }, + { + "name": "Component 2 (Globex Corp)", + "weight": 0.3, + "description": "检查是否存在 Globex Corp 账户对应的记录,且四个字段与预期值完全匹配", + "check_logic": "同 Component 1,预期 ARR=85000、Date=2026-08-30、Risk=Medium、Stage=Proposal", + "pass_condition": "找到该行且四个字段全部匹配" + }, + { + "name": "Component 3 (Initech)", + "weight": 0.3, + "description": "检查是否存在 Initech 账户对应的记录,且四个字段与预期值完全匹配", + "check_logic": "同 Component 1,预期 ARR=240000、Date=2026-09-10、Risk=High、Stage=Qualification", + "pass_condition": "找到该行且四个字段全部匹配" + }, + { + "name": "Component 4 (Cleanliness)", + "weight": 0.1, + "description": "检查数据库总行数是否恰好为 3,且不存在任何干扰账户", + "check_logic": "检查 len(rows)==3;遍历所有行的账户名,与 DISTRACTOR_ACCOUNTS ('soylent industries', 'umbrella health', 'hooli') 进行 account_matches 比对,确认无匹配项", + "pass_condition": "总行数等于 3 且 distractors_present 为空集合" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 计算,上限钳制在 1.0", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0", + "无法通过 HTTP GET 获取 notion_mock 状态 -> 打印 CRITICAL 并返回 0.0", + "current_state 为空或不存在 -> 打印 CRITICAL 并返回 0.0", + "未找到标题为 'Renewal Tracker 2026' 的数据库 -> 打印 CRITICAL 并返回 0.0", + "某预期账户对应的行未找到 -> 该 Component 不得分", + "某预期账户字段解析或匹配失败 -> 该 Component 不得分", + "数据库行数不等于 3 或存在干扰账户 -> Component 4 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求拉取 notion_mock 的当前状态。在返回的 JSON 中找到名为 'Renewal Tracker 2026' 的数据库,并收集其所有行记录(优先使用 db.items,否则回退到 parentId 匹配)。接着逐项检查 3 个预期账户(Northwind Traders、Globex Corp、Initech)是否存在,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期一致(日期还需落在 2026-06-24 至 2026-09-22 的 90 天窗口内),每通过一项加 0.30 分。最后检查清洁度:数据库必须恰好有 3 行且不含任何干扰账户(Soylent Industries、Umbrella Health、Hooli),通过则加 0.10 分。总分累加后通过 min 钳制在 1.0,再四舍五入到 4 位小数作为最终 REWARD 输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: am_renewal_tracker_001`\n2. **Domain**: 从 docstring 中可以看到 `Domain: mock_websites (notion_mock)`\n3. **Summary**: 这个任务要求 agent 向 Notion 数据库 \"Renewal Tracker 2026\" 添加恰好 3 行数据,对应特定的 Salesforce 续约机会。\n4. **is_placeholder**: false,因为脚本有详细的评分逻辑。\n5. **data_sources**: 脚本从 `/tmp/task_web_sid` 读取 sid,然后向 `http://28.7.186.212:8166/go?sid={sid}` 发送请求获取 Notion mock 状态。\n6. **scoring_components**:\n - Component 1-3: 每个预期行(Northwind Traders, Globex Corp, Initech)正确填充所有字段(ARR, Renewal Date, Risk, Renewal Stage),每个 0.30 分。\n - Component 4: 清洁度奖励,数据库恰好有 3 行且没有干扰账户,0.10 分。\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 累加,然后 `min(total_score, 1.0)` 并四舍五入到 4 位小数。\n9. **failure_modes**:\n - 无法读取 sid -> 0.0\n - 无法获取 Notion 状态 -> 0.0\n - current_state 为空 -> 0.0\n - 找不到数据库 -> 0.0\n - 行数不对或有干扰账户 -> Component 4 失败\n - 字段不匹配 -> 对应 Component 失败\n10. **scoring_logic_explanation**: 按执行顺序说明。\n11. **confidence**: 1.0,因为代码逻辑清晰。\n\n让我详细检查每个组件:\n\n**Component 1-3**:\n- 遍历 EXPECTED_ROWS(3个账户)\n- 在数据库行中查找匹配账户名的行\n- 检查 ARR: `norm_num(arr_value) == float(exp['ARR'])`\n- 检查 Date: `actual_date == expected_date` 且 `today <= actual_date <= cutoff`(2026-06-24 到 2026-09-22)\n- 检查 Risk: `select_matches` 使用 RISK_ALIASES\n- 检查 Stage: `select_matches` 使用 STAGE_ALIASES\n- 全部通过得 0.30\n\n**Component 4**:\n- `exact_count = (len(rows) == 3)`\n- 检查是否有 DISTRACTOR_ACCOUNTS 中的账户存在\n- 如果恰好3行且无干扰账户,得 0.10\n\n**数据获取**:\n- 从 `/tmp/task_web_sid` 读取 sid\n- 通过 `requests.get(f'{NOTION_URL}/go?sid={sid}')` 获取状态\n- 解析 `current_state.pages`\n- 查找数据库 `Renewal Tracker 2026`\n- 收集行:优先使用 `db.get('items')`,否则查找 `parentId == db_id` 的页面\n\n**字段解析**:\n- 支持多种属性名别名(PROPERTY_ALIASES)\n- 支持多种风险/阶段别名\n- 支持多种日期格式和数字格式\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"am_renewal_tracker_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证 agent 是否向 Notion 数据库 'Renewal Tracker 2026' 正确添加了恰好 3 条符合条件的续约跟踪记录,且未包含干扰项\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"notion_mock (http://28.7.186.212:8186)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 (Northwind Traders)\",\n \"weight\": 0.3,\n \"description\": \"检查是否存在 Northwind Traders 账户对应的记录,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期值完全匹配\",\n \"check_logic\": \"在数据库行中查找 account_matches 的行,提取 ARR、Renewal Date、Risk、Renewal Stage 字段值,分别用 norm_num、norm_date、select_matches 与预期值比较;日期还需满足 today(2026-06-24) <= actual_date <= cutoff(2026-09-22)\",\n \"pass_condition\": \"找到该行且 arr_ok=True, date_ok=True, risk_ok=True, stage_ok=True\"\n },\n {\n \"name\": \"Component 2 (Globex Corp)\",\n \"weight\": 0.3,\n \"description\": \"检查是否存在 Globex Corp 账户对应的记录,且四个字段与预期值完全匹配\",\n \"check_logic\": \"同 Component 1,预期 ARR=85000, Date=2026-08-30, Risk=Medium, Stage=Proposal\",\n \"pass_condition\": \"找到该行且四个字段全部匹配\"\n },\n {\n \"name\": \"Component 3 (Initech)\",\n \"weight\": 0.3,\n \"description\": \"检查是否存在 Initech 账户对应的记录,且四个字段与预期值完全匹配\",\n \"check_logic\": \"同 Component 1,预期 ARR=240000, Date=2026-09-10, Risk=High, Stage=Qualification\",\n \"pass_condition\": \"找到该行且四个字段全部匹配\"\n },\n {\n \"name\": \"Component 4 (Cleanliness)\",\n \"weight\": 0.1,\n \"description\": \"检查数据库总行数是否恰好为 3,且不存在任何干扰账户\",\n \"check_logic\": \"检查 len(rows)==3;遍历所有行的账户名,与 DISTRACTOR_ACCOUNTS ('soylent industries', 'umbrella health', 'hooli') 进行 account_matches 比对,确认无匹配\",\n \"pass_condition\": \"总行数等于 3 且 distractors_present 为空集合\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 计算,上限钳制在 1.0\",\n \"failure_modes\": [\n \"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0\",\n \"无法通过 HTTP GET 获取 notion mock 状态 -> 打印 CRITICAL 并返回 0.0\",\n \"current_state 为空或不存在 -> 打印 CRITICAL 并返回 0.0\",\n \"未找到标题为 'Renewal Tracker 2026' 的数据库 -> 打印 CRITICAL 并返回 0.0\",\n \"某预期账户对应的行未找到 -> 该 Component 不得分\",\n \"某预期账户字段解析或匹配失败 -> 该 Component 不得分\",\n \"数据库行数不等于 3 或存在干扰账户 -> Component 4 不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求拉取 notion_mock 的当前状态。在状态中找到名为 'Renewal Tracker 2026' 的数据库,收集其所有行记录。接着逐项检查 3 个预期账户(Northwind Traders、Globex Corp、Initech)是否存在且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期一致(日期还需落在 2026-06-24 至 2026-09-22 窗口内),每通过一项加 0.30 分。最后检查清洁度:数据库必须恰好有 3 行且不含任何干扰账户(Soylent Industries、Umbrella Health、Hooli),通过则加 0.10 分。总分累加后钳制在 1.0 并四舍五入到 4 位小数作为最终 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,没有 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名保留原样\n- weight 填写显式分值:0.30 和 0.10\n- is_placeholder: false\n\n确认 domain:docstring 写的是 `Domain: mock_websites (notion_mock)`,所以 domain 应该是 `mock_websites`。\n\n确认 task_id:`am_renewal_tracker_001`。\n\n确认 data_sources:`/tmp/task_web_sid` 和 `http://28.7.186.212:8166`(notion_mock)。\n\n确认评分逻辑中的日期检查:`today <= actual_date <= cutoff`,其中 today 是 2026-06-24,cutoff 是 today + 90 天 = 2026-09-22。这在代码中通过 `norm_date(TODAY_TEXT)` 和 `timedelta(days=WINDOW_DAYS)` 计算。\n\n确认数字解析:`norm_num` 会处理 `$120,000`、`120k` 等格式。\n\n确认属性别名:PROPERTY_ALIASES 中定义了多种可能的列名。\n\n一切看起来都正确。 {\"task_id\":\"am_renewal_tracker_001\",\"domain\":\"mock_websites\",\"summary\":\"验证 agent 是否向 Notion 数据库 'Renewal Tracker 2026' 正确添加了恰好 3 条符合条件的续约跟踪记录,且未包含干扰项\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"notion_mock (http://28.7.186.212:8186)\"],\"scoring_components\":[{\"name\":\"Component 1 (Northwind Traders)\",\"weight\":0.3,\"description\":\"检查是否存在 Northwind Traders 账户对应的记录,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期值完全匹配\",\"check_logic\":\"在数据库行中通过 account_matches 查找账户名匹配的行,提取 ARR、Renewal Date、Risk、Renewal Stage 字段值,分别使用 norm_num、norm_date、select_matches 与预期值比较;其中日期还需满足 today(2026-06-24) <= actual_date <= cutoff(2026-09-22)\",\"pass_condition\":\"找到该行且 arr_ok=True、date_ok=True、risk_ok=True、stage_ok=True\"},{\"name\":\"Component 2 (Globex Corp)\",\"weight\":0.3,\"description\":\"检查是否存在 Globex Corp 账户对应的记录,且四个字段与预期值完全匹配\",\"check_logic\":\"同 Component 1,预期 ARR=85000、Date=2026-08-30、Risk=Medium、Stage=Proposal\",\"pass_condition\":\"找到该行且四个字段全部匹配\"},{\"name\":\"Component 3 (Initech)\",\"weight\":0.3,\"description\":\"检查是否存在 Initech 账户对应的记录,且四个字段与预期值完全匹配\",\"check_logic\":\"同 Component 1,预期 ARR=240000、Date=2026-09-10、Risk=High、Stage=Qualification\",\"pass_condition\":\"找到该行且四个字段全部匹配\"},{\"name\":\"Component 4 (Cleanliness)\",\"weight\":0.1,\"description\":\"检查数据库总行数是否恰好为 3,且不存在任何干扰账户\",\"check_logic\":\"检查 len(rows)==3;遍历所有行的账户名,与 DISTRACTOR_ACCOUNTS ('soylent industries', 'umbrella health', 'hooli') 进行 account_matches 比对,确认无匹配项\",\"pass_condition\":\"总行数等于 3 且 distractors_present 为空集合\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 计算,上限钳制在 1.0\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0\",\"无法通过 HTTP GET 获取 notion_mock 状态 -> 打印 CRITICAL 并返回 0.0\",\"current_state 为空或不存在 -> 打印 CRITICAL 并返回 0.0\",\"未找到标题为 'Renewal Tracker 2026' 的数据库 -> 打印 CRITICAL 并返回 0.0\",\"某预期账户对应的行未找到 -> 该 Component 不得分\",\"某预期账户字段解析或匹配失败 -> 该 Component 不得分\",\"数据库行数不等于 3 或存在干扰账户 -> Component 4 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求拉取 notion_mock 的当前状态。在返回的 JSON 中找到名为 'Renewal Tracker 2026' 的数据库,并收集其所有行记录(优先使用 db.items,否则回退到 parentId 匹配)。接着逐项检查 3 个预期账户(Northwind Traders、Globex Corp、Initech)是否存在,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期一致(日期还需落在 2026-06-24 至 2026-09-22 的 90 天窗口内),每通过一项加 0.30 分。最后检查清洁度:数据库必须恰好有 3 行且不含任何干扰账户(Soylent Industries、Umbrella Health、Hooli),通过则加 0.10 分。总分累加后通过 min 钳制在 1.0,再四舍五入到 4 位小数作为最终 REWARD 输出。\",\"confidence\":1.0}" +} diff --git a/ar_approval_002/_cua_gym_vm_bridge.sh b/ar_approval_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_approval_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ar_approval_002/initial_setup.py b/ar_approval_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..5e267d458c1acf761a35503ee6cf387cb975934a --- /dev/null +++ b/ar_approval_002/initial_setup.py @@ -0,0 +1,240 @@ +""" +Initial Setup: Salesforce -> Slack discount-approval chain (Hooli Data Migration) +Task ID: ar_approval_002 +Domain: mock_websites (multi-mock: salesforce_mock + slack_mock) + +Initial state: + - Salesforce: opportunity 'Hooli Data Migration' (list price $90,000, + proposed/discounted amount $72,000, owner Jian Wu, account Hooli). + - Slack: #finance-approvals channel exists but contains NO approval message. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +SF_URL = 'http://28.7.184.198:8175' +SLACK_URL = 'http://28.7.184.198:8178' + +# --- Session id (shared across both mocks) --- +sid = str(uuid.uuid4()) +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' + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + + +# ===================================================================== +# Salesforce state +# ===================================================================== +sf_user = { + "userId": "user-1", "firstName": "John", "lastName": "Smith", + "email": "john.smith@company.com", "phone": "(555) 123-4567", + "title": "Sales Manager", "department": "Sales", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", +} +sf_users = [ + sf_user, + { + "userId": "user-2", "firstName": "Jian", "lastName": "Wu", + "email": "jian.wu@company.com", "phone": "(555) 234-5678", + "title": "Account Executive", "department": "Sales", "role": "User", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning", + }, + { + "userId": "user-3", "firstName": "Priya", "lastName": "Natarajan", + "email": "priya.natarajan@company.com", "phone": "(555) 345-6789", + "title": "Account Executive", "department": "Sales", "role": "User", + "avatar": "https://i.pravatar.cc/150?u=user-3", + "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning", + }, +] + +sf_accounts = [ + { + "accountId": "account-1", "name": "Hooli", "phone": "(650) 555-0142", + "website": "https://hooli.com", "type": "Customer", "industry": "Technology", + "revenue": 120000000, "employees": 1200, + "description": "Large technology company; active enterprise account.", + "ownerId": "user-2", + "billingStreet": "1100 Bridgepointe Pkwy", "billingCity": "San Mateo", + "billingState": "CA", "billingZip": "94404", "billingCountry": "United States", + "shippingStreet": "1100 Bridgepointe Pkwy", "shippingCity": "San Mateo", + "shippingState": "CA", "shippingZip": "94404", "shippingCountry": "United States", + "createdDate": "2025-02-11T09:00:00.000Z", "modifiedDate": "2026-06-01T09:00:00.000Z", + }, + { + "accountId": "account-2", "name": "Initech", "phone": "(512) 555-0199", + "website": "https://initech.com", "type": "Customer", "industry": "Finance", + "revenue": 40000000, "employees": 300, + "description": "Mid-market financial software firm.", + "ownerId": "user-3", + "billingStreet": "4120 Freidrich Ln", "billingCity": "Austin", + "billingState": "TX", "billingZip": "78744", "billingCountry": "United States", + "shippingStreet": "4120 Freidrich Ln", "shippingCity": "Austin", + "shippingState": "TX", "shippingZip": "78744", "shippingCountry": "United States", + "createdDate": "2025-08-20T09:00:00.000Z", "modifiedDate": "2026-05-15T09:00:00.000Z", + }, +] + +sf_contacts = [ + { + "contactId": "contact-1", "accountId": "account-1", "firstName": "Gavin", + "lastName": "Belson", "title": "CEO", "department": "Executive", + "email": "gavin.belson@hooli.com", "phone": "(650) 555-0143", "ownerId": "user-2", + }, + { + "contactId": "contact-2", "accountId": "account-2", "firstName": "Bill", + "lastName": "Lumbergh", "title": "VP Operations", "department": "Operations", + "email": "bill.lumbergh@initech.com", "phone": "(512) 555-0188", "ownerId": "user-3", + }, +] + +sf_opportunities = [ + { + "opportunityId": "opp-1", "name": "Hooli Data Migration", + "accountId": "account-1", "contactId": "contact-1", + "amount": 72000, + "closeDate": "2026-09-30T00:00:00.000Z", + "stage": "Negotiation", "probability": 75, "type": "New Business", + "leadSource": "Partner Referral", + "nextStep": "Finalize pricing and obtain discount approval", + "description": ( + "Enterprise data migration engagement for Hooli. Standard list price is " + "$90,000. Customer has requested a proposed (discounted) price of $72,000." + ), + "ownerId": "user-2", + "createdDate": "2026-05-05T09:00:00.000Z", "modifiedDate": "2026-06-28T09:00:00.000Z", + }, + { + "opportunityId": "opp-2", "name": "Initech Cloud Upgrade", + "accountId": "account-2", "contactId": "contact-2", + "amount": 35000, + "closeDate": "2026-08-15T00:00:00.000Z", + "stage": "Qualification", "probability": 40, "type": "Existing Business", + "leadSource": "Website", + "nextStep": "Schedule technical scoping call", + "description": "Cloud infrastructure upgrade for Initech.", + "ownerId": "user-3", + "createdDate": "2026-06-01T09:00:00.000Z", "modifiedDate": "2026-06-20T09:00:00.000Z", + }, +] + +sf_state = { + "user": sf_user, + "users": sf_users, + "leads": [], + "accounts": sf_accounts, + "contacts": sf_contacts, + "opportunities": sf_opportunities, + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + "dashboards": [], + "emailDrafts": [], + "reportSnapshots": [], +} + +# ===================================================================== +# Slack state +# ===================================================================== +slack_current_user = { + "userId": "user_1", "fullName": "John Smith", "displayName": "John", + "email": "john.smith@company.com", + "avatar": "https://picsum.photos/200/200?random=1", + "title": "Sales Manager", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York", +} +slack_users = [ + slack_current_user, + {"userId": "user_2", "fullName": "Sarah Johnson", "displayName": "Sarah", + "email": "sarah.johnson@company.com", "avatar": "https://picsum.photos/200/200?random=2", + "title": "Finance Manager", "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": "Controller", "status": "away", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/Los_Angeles"}, +] + +slack_channels = [ + {"channelId": "general", "name": "general", + "description": "Company-wide announcements and general discussion", + "topic": "Company-wide announcements", "isPrivate": False, "isStarred": True, + "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1", + "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "finance-approvals", "name": "finance-approvals", + "description": "Discount and pricing approval requests for finance sign-off", + "topic": "Pricing / discount approvals", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3"], "createdBy": "user_2", + "createdAt": "2025-11-03T08:00:00Z", "pinnedMessages": [], "unreadCount": 0}, +] + +slack_messages = { + "general": [ + {"messageId": "msg_g1", "senderId": "user_2", + "content": "Reminder: Q3 pricing review is this Friday.", + "timestamp": "2026-06-29T15:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + "finance-approvals": [], +} + +slack_state = { + "currentUser": slack_current_user, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", + "icon": "https://picsum.photos/64/64?random=workspace"}, + "users": slack_users, + "channels": slack_channels, + "messages": slack_messages, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", + "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], +} + +# ===================================================================== +# Inject state into both mocks (action: set -> writes initial + current) +# ===================================================================== +for name, url, state in [ + ("salesforce", SF_URL, sf_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} state injection failed: {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'State injected: {name} sid={sid}') + +# ===================================================================== +# Launch browser with both mocks (Salesforce first, then Slack tab) +# ===================================================================== +launch_gui( + f'google-chrome "{SF_URL}/?sid={sid}" "{SLACK_URL}/?sid={sid}"', + delay_sec=3.0, +) +print(f'GUI_READY: launched browser with salesforce + slack (sid={sid})') diff --git a/ar_approval_002/reward.py b/ar_approval_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..710ce96c67c4bc94df562973f338c47dc6972044 --- /dev/null +++ b/ar_approval_002/reward.py @@ -0,0 +1,213 @@ +""" +Reward Script: Post a structured discount-approval request in Slack #finance-approvals +Task ID: ar_approval_002 +Domain: mock_websites (Salesforce -> Slack chaining; observable state in Slack) + +Task outcome (from task_config.json): + A single structured message in Slack #finance-approvals containing ALL of: + - Customer = Hooli + - Original (list) Amount = $90,000 + - Adjusted (proposed) Amount = $72,000 + - Discount = 20% + - Requester = Jian Wu + - A note that it exceeds the 15% threshold and needs approval / sign-off + Salesforce must remain read-only / unchanged. + +Scoring (all components anchored to the NEW message in #finance-approvals, which is +absent in initial_env -> every component FAILS on initial_env -> reward(initial)=0.0): + C1 new message present in #finance-approvals .......... 0.15 + C2 Customer = Hooli ................................... 0.15 + C3 Original amount $90,000 ............................ 0.15 + C4 Adjusted amount $72,000 ........................... 0.15 + C5 Discount 20% ...................................... 0.15 + C6 Requester Jian Wu ................................. 0.15 + C7 Note: exceeds 15% threshold / needs approval ...... 0.10 + Total = 1.0 + +Salesforce-unchanged is a PRECONDITION (true in both initial and golden), so it is +used only as a non-scoring integrity gate: if the Hooli opportunity's figures were +mutated, the score is zeroed (anti-cheat). It never affects golden(1.0)/initial(0.0). + +All checks are deterministic. No LLM judge is used (OPENAI_API_KEY is EMPTY on the VM). +""" + +import os +import re +import sys + +# The VM can only reach the mocks via the corporate proxy. Set it explicitly so +# `requests` uses it regardless of how the script's environment was spawned. +PROXY = 'http://star-proxy.oa.com:3128' +os.environ['http_proxy'] = PROXY +os.environ['https_proxy'] = PROXY +os.environ['HTTP_PROXY'] = PROXY +os.environ['HTTPS_PROXY'] = PROXY +os.environ['no_proxy'] = 'localhost,127.0.0.1' + +import requests + +SLACK_URL = 'http://28.7.184.198:8178' +SALESFORCE_URL = 'http://28.7.184.198:8175' +APPROVAL_CHANNEL = 'finance-approvals' + + +def fail(msg): + print(f'CRITICAL: {msg}') + print('REWARD: 0.0') + sys.exit(0) + + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + fail(f'Cannot read sid from /tmp/task_web_sid: {e}') + +# --- Fetch Slack state --- +try: + slack = requests.get(f'{SLACK_URL}/go?sid={sid}', timeout=20).json() +except Exception as e: + fail(f'Cannot fetch Slack state: {e}') + +slack_initial = slack.get('initial_state') or {} +slack_current = slack.get('current_state') or {} +if not slack_current: + fail('Slack current_state is empty/None') + +init_msgs = (slack_initial.get('messages') or {}).get(APPROVAL_CHANNEL, []) or [] +cur_msgs = (slack_current.get('messages') or {}).get(APPROVAL_CHANNEL, []) or [] + +# Anchor scoring to messages that are NEW relative to the initial snapshot. +new_msgs = cur_msgs[len(init_msgs):] if len(cur_msgs) > len(init_msgs) else [] + +# Combined raw + normalized text of the new approval message(s). +raw_text = '\n'.join(str(m.get('content', '')) for m in new_msgs) +text_lower = raw_text.lower() +# Normalized: drop commas/spaces so "$90,000" and "$90000" both match "90000". +norm = re.sub(r'[,\s]', '', text_lower) + + +def verify_task(): + total_score = 0.0 + + # --- Integrity gate: Salesforce must be unchanged (read-only). --- + # Precondition (true in both initial and golden) -> awards NO points. + # Only used to zero-out the score if the agent mutated the Hooli opportunity. + try: + sf = requests.get(f'{SALESFORCE_URL}/go?sid={sid}', timeout=20).json() + sf_init = sf.get('initial_state') or {} + sf_cur = sf.get('current_state') or {} + + def hooli_opp(state): + for o in (state.get('opportunities') or []): + if str(o.get('name', '')).strip().lower() == 'hooli data migration': + return o + return None + + opp_i = hooli_opp(sf_init) + opp_c = hooli_opp(sf_cur) + if opp_i is not None and opp_c is not None: + # Compare the figures that the task says must stay read-only. + if (opp_i.get('amount') != opp_c.get('amount') + or opp_i.get('stage') != opp_c.get('stage')): + print('GATE FAIL: Salesforce Hooli opportunity was modified ' + f'(initial amount={opp_i.get("amount")}/stage={opp_i.get("stage")} ' + f'-> current amount={opp_c.get("amount")}/stage={opp_c.get("stage")}). ' + 'Salesforce must be read-only.') + print('\nScore: 0.0/1.0') + print('REWARD: 0.0') + return 0.0 + print('GATE PASS: Salesforce Hooli opportunity unchanged (read-only).') + else: + print('GATE INFO: Hooli opportunity not found in SF state; skipping integrity gate.') + except Exception as e: + # Do not crash scoring if SF is unreachable; just note it. + print(f'GATE WARN: could not verify Salesforce integrity: {e}') + + # --- Component 1: a NEW message exists in #finance-approvals (0.15) --- + try: + if new_msgs: + print(f'PASS: C1 — {len(new_msgs)} new message(s) in #{APPROVAL_CHANNEL} (0.15)') + total_score += 0.15 + else: + print(f'FAIL: C1 — no new message in #{APPROVAL_CHANNEL} ' + f'(initial={len(init_msgs)}, current={len(cur_msgs)})') + except Exception as e: + print(f'ERROR: C1 — {e}') + + # --- Component 2: Customer = Hooli (0.15) --- + try: + if 'hooli' in text_lower: + print('PASS: C2 — Customer "Hooli" present (0.15)') + total_score += 0.15 + else: + print('FAIL: C2 — Customer "Hooli" not found') + except Exception as e: + print(f'ERROR: C2 — {e}') + + # --- Component 3: Original/list amount $90,000 (0.15) --- + try: + if '90000' in norm: + print('PASS: C3 — Original amount $90,000 present (0.15)') + total_score += 0.15 + else: + print('FAIL: C3 — Original amount 90,000 not found') + except Exception as e: + print(f'ERROR: C3 — {e}') + + # --- Component 4: Adjusted/proposed amount $72,000 (0.15) --- + try: + if '72000' in norm: + print('PASS: C4 — Adjusted amount $72,000 present (0.15)') + total_score += 0.15 + else: + print('FAIL: C4 — Adjusted amount 72,000 not found') + except Exception as e: + print(f'ERROR: C4 — {e}') + + # --- Component 5: Discount 20% (0.15) --- + try: + # Require the 20% figure (allow "20 %" / "20percent" via normalization). + if '20%' in norm or '20percent' in norm: + print('PASS: C5 — Discount 20% present (0.15)') + total_score += 0.15 + else: + print('FAIL: C5 — Discount 20% not found') + except Exception as e: + print(f'ERROR: C5 — {e}') + + # --- Component 6: Requester Jian Wu (0.15) --- + try: + # Tolerate extra spacing; normalized form removes the space -> "jianwu". + if 'jianwu' in norm: + print('PASS: C6 — Requester "Jian Wu" present (0.15)') + total_score += 0.15 + else: + print('FAIL: C6 — Requester "Jian Wu" not found') + except Exception as e: + print(f'ERROR: C6 — {e}') + + # --- Component 7: note that it exceeds the 15% threshold / needs approval (0.10) --- + try: + mentions_15 = '15%' in norm or '15percent' in norm + mentions_approval = any(k in text_lower for k in + ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed')) + if mentions_15 and mentions_approval: + print('PASS: C7 — Note references 15% threshold and approval/sign-off (0.10)') + total_score += 0.10 + else: + print(f'FAIL: C7 — threshold note incomplete (mentions_15={mentions_15}, ' + f'mentions_approval={mentions_approval})') + except Exception as e: + print(f'ERROR: C7 — {e}') + + final_score = round(min(total_score, 1.0), 4) + print(f'\nScore: {final_score}/1.0') + print(f'REWARD: {final_score}') + return final_score + + +verify_task() diff --git a/ar_approval_002/reward_label.json b/ar_approval_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..67867cc2c3fe8ab32a5b3c55b9b0604bae4d8031 --- /dev/null +++ b/ar_approval_002/reward_label.json @@ -0,0 +1,82 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_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:22:12", + "label": { + "task_id": "ar_approval_002", + "domain": "mock_websites", + "summary": "验证代理是否在 Slack #finance-approvals 频道发布了包含特定客户、金额、折扣、请求人及审批说明的结构化折扣审批请求消息,并确保 Salesforce 只读未被修改。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "slack_mock (http://28.7.186.212:8198)", + "salesforce_mock (http://28.7.186.212:8195)" + ], + "scoring_components": [ + { + "name": "C1 new message present in #finance-approvals", + "weight": 0.15, + "description": "检查在 #finance-approvals 频道是否有相对于初始状态的新消息", + "check_logic": "比较 slack_current 与 slack_initial 中 finance-approvals 频道的消息列表,若 cur_msgs 长度大于 init_msgs,则取 new_msgs = cur_msgs[len(init_msgs):],判断 new_msgs 是否非空", + "pass_condition": "new_msgs 非空(即至少有一条新消息)" + }, + { + "name": "C2 Customer = Hooli", + "weight": 0.15, + "description": "检查新消息文本中是否包含客户名称 Hooli", + "check_logic": "将新消息的 raw_text 转为小写得到 text_lower,检查 'hooli' 是否在 text_lower 中", + "pass_condition": "text_lower 中包含子串 'hooli'" + }, + { + "name": "C3 Original amount $90,000", + "weight": 0.15, + "description": "检查新消息中是否包含原始金额 90,000", + "check_logic": "对 text_lower 使用 re.sub(r'[,\\s]', '', ...) 得到 norm(移除逗号和空格),检查 '90000' 是否在 norm 中", + "pass_condition": "norm 中包含子串 '90000'" + }, + { + "name": "C4 Adjusted amount $72,000", + "weight": 0.15, + "description": "检查新消息中是否包含调整后金额 72,000", + "check_logic": "检查 norm 中是否包含 '72000'", + "pass_condition": "norm 中包含子串 '72000'" + }, + { + "name": "C5 Discount 20%", + "weight": 0.15, + "description": "检查新消息中是否包含 20% 折扣信息", + "check_logic": "检查 norm 中是否包含 '20%' 或 '20percent'", + "pass_condition": "norm 中包含 '20%' 或 '20percent'" + }, + { + "name": "C6 Requester Jian Wu", + "weight": 0.15, + "description": "检查新消息中是否包含请求人 Jian Wu", + "check_logic": "检查 norm(已移除空格)中是否包含 'jianwu'", + "pass_condition": "norm 中包含子串 'jianwu'" + }, + { + "name": "C7 Note: exceeds 15% threshold / needs approval", + "weight": 0.1, + "description": "检查新消息中是否包含超过 15% 阈值并需要审批的说明", + "check_logic": "mentions_15 = '15%' in norm or '15percent' in norm;mentions_approval = any(k in text_lower for k in ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'));要求两者同时为真", + "pass_condition": "同时满足:norm 中包含 '15%' 或 '15percent',且 text_lower 中包含 'approval'、'sign-off'、'sign off'、'signoff'、'threshold' 或 'exceed' 之一" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最后通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:调用 fail() 打印 CRITICAL 并 sys.exit(0) 返回 0.0", + "无法获取 Slack 状态:调用 fail() 退出并返回 0.0", + "Slack current_state 为空/None:调用 fail() 退出并返回 0.0", + "Salesforce 中 Hooli Data Migration opportunity 的 amount 或 stage 被修改:直接打印 GATE FAIL 并返回 0.0(反作弊完整性门控)", + "无新消息(new_msgs 为空):C1 失败,不加分", + "各组件文本匹配失败:对应组件不加分,但脚本继续执行" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别拉取 Slack 和 Salesforce 的 mock 状态。对于 Slack,通过比较 initial_state 和 current_state 中 #finance-approvals 频道的消息列表,提取初始状态之后的新消息(new_msgs),并将所有新消息内容拼接为 raw_text,同时生成小写和规范化(移除逗号、空格)的文本。接着执行完整性门控:检查 Salesforce 中名为 'Hooli Data Migration' 的 opportunity 在初始状态和当前状态的 amount 与 stage 是否一致,若被修改则直接返回 0.0。随后逐项检查 7 个评分组件:C1 验证新消息存在性;C2-C6 通过在 text_lower 或 norm 中搜索特定关键词验证客户、原始金额、调整后金额、折扣、请求人;C7 要求同时包含 15% 相关字样和审批/阈值/超出相关字样。每个通过组件累加对应分数,最终分数经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ar_approval_001(从 docstring 中明确提取)\n - Domain: mock_websites(从 docstring 中明确提取)\n\n2. **任务概述**:\n - 在 Slack #finance-approvals 频道发布一个结构化的折扣审批请求消息,包含特定字段。Salesforce 必须保持只读/不变。\n\n3. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - Slack mock:`http://28.7.186.212:8198`(通过 `/go?sid={sid}` 获取状态)\n - Salesforce mock:`http://28.7.186.212:8195`(通过 `/go?sid={sid}` 获取状态)\n\n4. **评分组件**:\n - C1 (0.15):#finance-approvals 中有新消息\n - C2 (0.15):包含 \"Hooli\"\n - C3 (0.15):包含原始金额 $90,000(规范化后匹配 \"90000\")\n - C4 (0.15):包含调整后金额 $72,000(规范化后匹配 \"72000\")\n - C5 (0.15):包含折扣 20%(规范化后匹配 \"20%\" 或 \"20percent\")\n - C6 (0.15):包含请求人 Jian Wu(规范化后匹配 \"jianwu\")\n - C7 (0.10):包含超过 15% 阈值/需要审批的说明(需要同时满足:包含 \"15%\" 或 \"15percent\",以及包含 \"approval\"、\"sign-off\"、\"sign off\"、\"signoff\"、\"threshold\"、\"exceed\" 之一)\n\n5. **完整性门控(Integrity gate)**:\n - 检查 Salesforce 中 Hooli Data Migration opportunity 的 amount 和 stage 是否被修改\n - 如果被修改,直接返回 0.0\n - 不贡献分数,只是反作弊\n\n6. **分数聚合**:\n - 各组件分数相加\n - 最后 `round(min(total_score, 1.0), 4)`\n\n7. **失败模式**:\n - 读取 sid 失败:调用 fail(),输出 REWARD: 0.0 并 sys.exit(0)\n - 获取 Slack 状态失败:同上\n - Slack current_state 为空:同上\n - Salesforce Hooli opportunity 被修改:返回 0.0\n - 各组件检查失败:只是不加分,不会提前退出(除了 integrity gate)\n\n8. **is_placeholder**:\n - false,因为这是一个真正的评分脚本,有详细的检查逻辑\n\n9. **confidence**:\n - 1.0,因为代码非常清晰完整\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"ar_approval_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证代理是否在 Slack #finance-approvals 频道发布了包含特定客户、金额、折扣、请求人及审批说明的结构化折扣审批请求消息,并确保 Salesforce 只读未被修改。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"slack_mock (http://28.7.186.212:8198)\", \"salesforce_mock (http://28.7.186.212:8195)\"],\n \"scoring_components\": [\n {\n \"name\": \"C1 new message present in #finance-approvals\",\n \"weight\": 0.15,\n \"description\": \"检查在 #finance-approvals 频道是否有相对于初始状态的新消息\",\n \"check_logic\": \"比较 slack_current 与 slack_initial 中 finance-approvals 频道的消息列表,若 cur_msgs 长度大于 init_msgs,则取 new_msgs = cur_msgs[len(init_msgs):],判断 new_msgs 是否非空\",\n \"pass_condition\": \"new_msgs 非空(即至少有一条新消息)\"\n },\n {\n \"name\": \"C2 Customer = Hooli\",\n \"weight\": 0.15,\n \"description\": \"检查新消息文本中是否包含客户名称 Hooli\",\n \"check_logic\": \"将新消息的 raw_text 转为小写得到 text_lower,检查 'hooli' 是否在 text_lower 中\",\n \"pass_condition\": \"text_lower 中包含子串 'hooli'\"\n },\n {\n \"name\": \"C3 Original amount $90,000\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含原始金额 90,000\",\n \"check_logic\": \"对 text_lower 使用 re.sub(r'[,\\\\s]', '', ...) 得到 norm(移除逗号和空格),检查 '90000' 是否在 norm 中\",\n \"pass_condition\": \"norm 中包含子串 '90000'\"\n },\n {\n \"name\": \"C4 Adjusted amount $72,000\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含调整后金额 72,000\",\n \"check_logic\": \"检查 norm 中是否包含 '72000'\",\n \"pass_condition\": \"norm 中包含子串 '72000'\"\n },\n {\n \"name\": \"C5 Discount 20%\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含 20% 折扣信息\",\n \"check_logic\": \"检查 norm 中是否包含 '20%' 或 '20percent'\",\n \"pass_condition\": \"norm 中包含 '20%' 或 '20percent'\"\n },\n {\n \"name\": \"C6 Requester Jian Wu\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含请求人 Jian Wu\",\n \"check_logic\": \"检查 norm(已移除空格)中是否包含 'jianwu'\",\n \"pass_condition\": \"norm 中包含子串 'jianwu'\"\n },\n {\n \"name\": \"C7 Note: exceeds 15% threshold / needs approval\",\n \"weight\": 0.10,\n \"description\": \"检查新消息中是否包含超过 15% 阈值并需要审批的说明\",\n \"check_logic\": \"mentions_15 = '15%' in norm or '15percent' in norm;mentions_approval = any(k in text_lower for k in ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'));要求两者同时为真\",\n \"pass_condition\": \"同时满足:norm 中包含 '15%' 或 '15percent',且 text_lower 中包含 'approval'、'sign-off'、'sign off'、'signoff'、'threshold' 或 'exceed' 之一\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最后通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:调用 fail() 打印 CRITICAL 并 sys.exit(0) 返回 0.0\",\n \"无法获取 Slack 状态:调用 fail() 退出并返回 0.0\",\n \"Slack current_state 为空/None:调用 fail() 退出并返回 0.0\",\n \"Salesforce 中 Hooli Data Migration opportunity 的 amount 或 stage 被修改:直接打印 GATE FAIL 并返回 0.0(反作弊完整性门控)\",\n \"无新消息(new_msgs 为空):C1 失败,不加分\",\n \"各组件文本匹配失败:对应组件不加分,但脚本继续执行\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别拉取 Slack 和 Salesforce 的 mock 状态。对于 Slack,通过比较 initial_state 和 current_state 中 #finance-approvals 频道的消息列表,提取初始状态之后的新消息(new_msgs),并将所有新消息内容拼接为 raw_text,同时生成小写和规范化(移除逗号、空格)的文本。接着执行完整性门控:检查 Salesforce 中名为 'Hooli Data Migration' 的 opportunity 在初始状态和当前状态的 amount 与 stage 是否一致,若被修改则直接返回 0.0。随后逐项检查 7 个评分组件:C1 验证新消息存在性;C2-C6 通过在 text_lower 或 norm 中搜索特定关键词验证客户、原始金额、调整后金额、折扣、请求人;C7 要求同时包含 15% 相关字样和审批/阈值/超出相关字样。每个通过组件累加对应分数,最终分数经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名、代码标识符保留原样\n- is_placeholder: false\n- weight 填写代码中显式给出的分值\n\n确认所有字段都已包含且格式正确。 {\"task_id\":\"ar_approval_001\",\"domain\":\"mock_websites\",\"summary\":\"验证代理是否在 Slack #finance-approvals 频道发布了包含特定客户、金额、折扣、请求人及审批说明的结构化折扣审批请求消息,并确保 Salesforce 只读未被修改。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"slack_mock (http://28.7.186.212:8198)\",\"salesforce_mock (http://28.7.186.212:8195)\"],\"scoring_components\":[{\"name\":\"C1 new message present in #finance-approvals\",\"weight\":0.15,\"description\":\"检查在 #finance-approvals 频道是否有相对于初始状态的新消息\",\"check_logic\":\"比较 slack_current 与 slack_initial 中 finance-approvals 频道的消息列表,若 cur_msgs 长度大于 init_msgs,则取 new_msgs = cur_msgs[len(init_msgs):],判断 new_msgs 是否非空\",\"pass_condition\":\"new_msgs 非空(即至少有一条新消息)\"},{\"name\":\"C2 Customer = Hooli\",\"weight\":0.15,\"description\":\"检查新消息文本中是否包含客户名称 Hooli\",\"check_logic\":\"将新消息的 raw_text 转为小写得到 text_lower,检查 'hooli' 是否在 text_lower 中\",\"pass_condition\":\"text_lower 中包含子串 'hooli'\"},{\"name\":\"C3 Original amount $90,000\",\"weight\":0.15,\"description\":\"检查新消息中是否包含原始金额 90,000\",\"check_logic\":\"对 text_lower 使用 re.sub(r'[,\\\\s]', '', ...) 得到 norm(移除逗号和空格),检查 '90000' 是否在 norm 中\",\"pass_condition\":\"norm 中包含子串 '90000'\"},{\"name\":\"C4 Adjusted amount $72,000\",\"weight\":0.15,\"description\":\"检查新消息中是否包含调整后金额 72,000\",\"check_logic\":\"检查 norm 中是否包含 '72000'\",\"pass_condition\":\"norm 中包含子串 '72000'\"},{\"name\":\"C5 Discount 20%\",\"weight\":0.15,\"description\":\"检查新消息中是否包含 20% 折扣信息\",\"check_logic\":\"检查 norm 中是否包含 '20%' 或 '20percent'\",\"pass_condition\":\"norm 中包含 '20%' 或 '20percent'\"},{\"name\":\"C6 Requester Jian Wu\",\"weight\":0.15,\"description\":\"检查新消息中是否包含请求人 Jian Wu\",\"check_logic\":\"检查 norm(已移除空格)中是否包含 'jianwu'\",\"pass_condition\":\"norm 中包含子串 'jianwu'\"},{\"name\":\"C7 Note: exceeds 15% threshold / needs approval\",\"weight\":0.10,\"description\":\"检查新消息中是否包含超过 15% 阈值并需要审批的说明\",\"check_logic\":\"mentions_15 = '15%' in norm or '15percent' in norm;mentions_approval = any(k in text_lower for k in ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'));要求两者同时为真\",\"pass_condition\":\"同时满足:norm 中包含 '15%' 或 '15percent',且 text_lower 中包含 'approval'、'sign-off'、'sign off'、'signoff'、'threshold' 或 'exceed' 之一\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:调用 fail() 打印 CRITICAL 并 sys.exit(0) 返回 0.0\",\"无法获取 Slack 状态:调用 fail() 退出并返回 0.0\",\"Slack current_state 为空/None:调用 fail() 退出并返回 0.0\",\"Salesforce 中 Hooli Data Migration opportunity 的 amount 或 stage 被修改:直接打印 GATE FAIL 并返回 0.0(反作弊完整性门控)\",\"无新消息(new_msgs 为空):C1 失败,不加分\",\"各组件文本匹配失败:对应组件不加分,但脚本继续执行\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别拉取 Slack 和 Salesforce 的 mock 状态。对于 Slack,通过比较 initial_state 和 current_state 中 #finance-approvals 频道的消息列表,提取初始状态之后的新消息(new_msgs),并将所有新消息内容拼接为 raw_text,同时生成小写和规范化(移除逗号、空格)的文本。接着执行完整性门控:检查 Salesforce 中名为 'Hooli Data Migration' 的 opportunity 在初始状态和当前状态的 amount 与 stage 是否一致,若被修改则直接返回 0.0。随后逐项检查 7 个评分组件:C1 验证新消息存在性;C2-C6 通过在 text_lower 或 norm 中搜索特定关键词验证客户、原始金额、调整后金额、折扣、请求人;C7 要求同时包含 15% 相关字样和审批/阈值/超出相关字样。每个通过组件累加对应分数,最终分数经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/ar_billing_exception_012__long/_cua_gym_vm_bridge.sh b/ar_billing_exception_012__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_billing_exception_012__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ar_billing_exception_012__long/initial_setup.py b/ar_billing_exception_012__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d67d7dd296e7f35666624b37370a8b2f5fce3a7a --- /dev/null +++ b/ar_billing_exception_012__long/initial_setup.py @@ -0,0 +1,934 @@ +""" +Initial Setup: Weekly billing-exceptions reconciliation +Task ID: ar_billing_exception_012__long +Mocks: stripe_dashboard_mock (8179), quickbooks_mock (8172), + google_sheets_mock (8145), slack_mock (8178) + +Scenario (multi-branch finance-ops reconciliation, "today" = 2026-06-29) +------------------------------------------------------------------------ +A finance-ops analyst clears the week's billing exceptions. The Google Sheet +"Billing Exceptions" (tab `Exceptions`, cols: Customer | Exception Type | Amount +| Invoice #) lists customers the billing system flagged, one row each. For every +row the analyst derives the corrective action from the `Exception Type`, carries +the identifier into Stripe or QuickBooks, performs the (hidden) control there, +then adds a "Reconciliation Summary" tab to the sheet and posts + pins a one-line +summary to Slack #finance. + +Branch rule (stated in the instruction; VERIFIED against current app state): + * Duplicate charge -> REFUND the matching Stripe payment + (skip if that payment is already refunded). + * Churn - downgrade -> CANCEL the matching Stripe subscription at PERIOD END + (skip if already cancel_at_period_end / canceled). + * Payment received -> RECEIVE PAYMENT on the matching QuickBooks invoice + (skip if the invoice is already Paid). + * On hold / Under review -> LEAVE (must NOT act — tempting distractor). + * Customer with no matching Stripe/QB record -> SKIP (unresolvable). + +Row plan (10 rows) => 6 require action, 4 must be skipped: + 2 REFUND, 2 CANCEL_EOP, 2 RECEIVE_PAYMENT, 2 LEAVE (On hold / Under review), + 1 already-refunded 'Duplicate charge' (arms the refund leak guard), + 1 no-match 'Payment received' (unresolvable distractor). + +Cross-app data flow (H3): + Customer + Amount read in the Sheets worklist -> locate the matching Stripe + payment (customer_name + amount in cents) to refund, and the matching Stripe + subscription (customer) to cancel-at-period-end; Invoice # -> matching + QuickBooks invoice number to receive payment on. + +Ground-truth embedding (Rule 2), PRECOMPUTED in Python from the visible sheet +rows + the injected Stripe/QB records so visible <=> key can never disagree: + * google_sheets.initial_state._task_adapter.expected -> per-row worklist + * google_sheets.initial_state._task_adapter.summary_tab_name = 'Reconciliation Summary' + * slack.initial_state._task_adapter.summary_channel = 'finance' + +Observable result kept ABSENT at injection (Rule 3): + * the 2 REFUND-target payments: amount_refunded=0, refunded=False; refunds[] + holds only a decoy that does NOT reference any target. + * the 2 CANCEL_EOP-target subscriptions: cancel_at_period_end=False, status='active'. + * the 2 RECEIVE_PAYMENT-target QB invoices: status Sent/Overdue, paidAmount=0, + paidDate=None. + * the Sheets workbook has NO 'Reconciliation Summary' tab (only 'Exceptions'). + * Slack #finance starts EMPTY (no messages, no pinned). + * the 'already-done' distractor payment IS already refunded (must be left alone). + +NOTE: Stripe amounts are in CENTS, QuickBooks amounts are in DOLLARS. +""" +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 = 'cc91abcd-23c1-4845-afde-3bfed691bbe4' +TODAY = _dt.date(2026, 6, 29) +SUMMARY_TAB_NAME = 'Reconciliation Summary' +SUMMARY_CHANNEL = 'finance' + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- +def _ts(date_str): + """Unix seconds for date_str at 12:00 UTC (stable displayed date across TZs).""" + d = _dt.datetime.strptime(date_str, '%Y-%m-%d').replace( + hour=12, minute=0, second=0, microsecond=0, tzinfo=_dt.timezone.utc + ) + return int(d.timestamp()) + + +_CREATED = _ts('2026-01-08') +_NOW_TS = _ts('2026-06-29') + + +# =========================================================================== +# 1) STRIPE — payments + subscriptions (+ customers, payment methods) +# =========================================================================== +# Shared customer registry: name -> (stripe_customer_id, email, card) +_STRIPE_CUSTS = { + 'Acme Corporation': ('cus_acme00000001', 'billing@acmecorp.com', {'brand': 'visa', 'last4': '4242', 'exp_month': 12, 'exp_year': 2027}), + 'Globex Industries': ('cus_globex0000012', 'ap@globexind.com', {'brand': 'mastercard', 'last4': '5555', 'exp_month': 8, 'exp_year': 2028}), + 'TechStart Inc.': ('cus_techstart0001', 'finance@techstart.io', {'brand': 'visa', 'last4': '1234', 'exp_month': 3, 'exp_year': 2027}), + 'Riverside Medical Group': ('cus_riverside0001', 'it@riversidemedical.org', {'brand': 'visa', 'last4': '8888', 'exp_month': 1, 'exp_year': 2028}), + 'CloudSync Pro': ('cus_cloudsync0001', 'billing@cloudsyncpro.com', {'brand': 'visa', 'last4': '6543', 'exp_month': 10, 'exp_year': 2028}), + 'DataVault Systems': ('cus_datavault0001', 'procurement@datavault.io', {'brand': 'amex', 'last4': '0001', 'exp_month': 6, 'exp_year': 2028}), + 'Pioneer Labs': ('cus_pioneer000001', 'admin@pioneerlabs.io', {'brand': 'visa', 'last4': '7777', 'exp_month': 12, 'exp_year': 2027}), + 'Northwind Traders': ('cus_northwind0001', 'ap@northwindtraders.com', {'brand': 'mastercard', 'last4': '2323', 'exp_month': 5, 'exp_year': 2027}), + 'Summit Retail': ('cus_summit0000001', 'billing@summitretail.com', {'brand': 'visa', 'last4': '9090', 'exp_month': 9, 'exp_year': 2028}), +} + + +def _stripe_customer(name): + cid, email, _card = _STRIPE_CUSTS[name] + return { + 'id': cid, 'name': name, 'email': email, 'phone': None, 'description': None, + 'address': {'line1': '200 Market St', 'line2': None, 'city': 'San Francisco', + 'state': 'CA', 'postal_code': '94105', 'country': 'US'}, + 'balance': 0, 'currency': 'usd', 'default_payment_method': None, + 'metadata': {}, 'created': _CREATED, 'livemode': True, 'delinquent': False, + 'total_spent': 0, 'payments_count': 1, + } + + +def _payment(pid, cust_name, amount_cents, date_str, description, + refunded=False, status='succeeded'): + cid, email, card = _STRIPE_CUSTS[cust_name] + captured = (status == 'succeeded') + return { + 'id': pid, + 'amount': amount_cents, + 'currency': 'usd', + 'status': status, + 'description': description, + 'customer': cid, + 'customer_email': email, + 'customer_name': cust_name, + 'payment_method': {'type': 'card', 'card': dict(card, funding='credit')}, + 'amount_received': amount_cents if captured else 0, + 'amount_refunded': amount_cents if refunded else 0, + 'refunded': bool(refunded), + 'disputed': False, + 'captured': captured, + 'receipt_email': email, + 'receipt_url': None, + 'metadata': {}, + 'created': _ts(date_str), + 'livemode': True, + 'risk_score': 12, + 'risk_level': 'normal', + 'outcome': {'type': 'authorized' if captured else 'pending', + 'risk_level': 'normal', 'risk_score': 12, 'reason': None}, + 'invoice': None, + } + + +# Payments: 2 refund targets + 1 already-refunded distractor + 1 LEAVE bait +# (DataVault, refunding it = FALSE POSITIVE) + 2 watermark decoys not in the sheet. +_STRIPE_PAYMENTS = [ + # --- REFUND targets (Duplicate charge) — ABSENT result: refunded=False --- + _payment('pi_refund_acme_0001', 'Acme Corporation', 25000, '2026-06-16', + 'Pro Plan - Monthly (duplicate charge)', refunded=False), # $250.00 + _payment('pi_refund_globex_0002', 'Globex Industries', 9999, '2026-06-18', + 'Starter Plan - Monthly (duplicate charge)', refunded=False), # $99.99 + + # --- already-refunded distractor (Pioneer): must be LEFT alone --- + _payment('pi_already_pioneer_09', 'Pioneer Labs', 4999, '2026-06-10', + 'API Access Add-on (already refunded)', refunded=True), # $49.99 + + # --- LEAVE-row bait (DataVault 'Under review'): refunding this = leak/FP --- + _payment('pi_leave_datavault_08', 'DataVault Systems', 18000, '2026-06-20', + 'Team Plan - Monthly', refunded=False), # $180.00 + + # --- watermark decoys (customers NOT in the exceptions sheet) --- + _payment('pi_decoy_north_0011', 'Northwind Traders', 12000, '2026-06-12', + 'Pro Plan Upgrade - Monthly', refunded=False), + _payment('pi_decoy_summit_0012', 'Summit Retail', 30000, '2026-06-14', + 'Enterprise Annual - Prepaid', refunded=False), +] + + +def _subscription(sub_id, cust_name, status, interval, price_id, product_name, + unit_amount_cents, quantity, cancel_at_period_end=False): + cid, email, _card = _STRIPE_CUSTS[cust_name] + if interval == 'year': + cps, cpe = _ts('2026-01-01'), _ts('2027-01-01') + else: + cps, cpe = _ts('2026-06-01'), _ts('2026-07-01') + sub = { + 'id': sub_id, + 'customer': cid, + 'customer_name': cust_name, + 'customer_email': email, + 'status': status, + 'items': [{ + 'id': f'si_{sub_id[4:]}_1', 'price': price_id, 'product': f'prod_{price_id}', + 'product_name': product_name, 'quantity': quantity, + 'unit_amount': unit_amount_cents, 'currency': 'usd', 'interval': interval, + }], + 'current_period_start': cps, + 'current_period_end': cpe, + 'cancel_at_period_end': bool(cancel_at_period_end), + 'canceled_at': _ts('2026-05-20') if status == 'canceled' else None, + 'ended_at': _ts('2026-05-20') if status == 'canceled' else None, + 'trial_start': None, + 'trial_end': None, + 'collection_method': 'charge_automatically', + 'default_payment_method': None, + 'latest_invoice': None, + 'pause_collection': None, + 'metadata': {}, + 'created': _CREATED, + } + return sub + + +# Subscriptions: 2 cancel-eop targets + 1 LEAVE bait (CloudSync active sub; +# cancelling it = FALSE POSITIVE) + 2 watermark decoys (1 already-canceled). +_STRIPE_SUBS = [ + # --- CANCEL_EOP targets (Churn - downgrade) — ABSENT: cap=False, active --- + _subscription('sub_techstart00001', 'TechStart Inc.', 'active', 'month', + 'price_team_month', 'Team Plan', 4999, 3, cancel_at_period_end=False), + _subscription('sub_riverside00001', 'Riverside Medical Group', 'active', 'year', + 'price_clinic_annual', 'Clinic Suite', 359988, 1, cancel_at_period_end=False), + + # --- LEAVE-row bait (CloudSync 'On hold'): cancelling this = leak/FP --- + _subscription('sub_cloudsync00001', 'CloudSync Pro', 'active', 'month', + 'price_platform_month', 'CloudSync Platform', 48000, 1, cancel_at_period_end=False), + + # --- watermark decoys --- + _subscription('sub_decoy_north0001', 'Northwind Traders', 'active', 'month', + 'price_pro_month', 'Pro Plan', 9900, 2, cancel_at_period_end=False), + _subscription('sub_decoy_summit001', 'Summit Retail', 'canceled', 'month', + 'price_starter_month', 'Starter Plan', 2999, 1, cancel_at_period_end=False), +] + +_STRIPE_CUSTOMERS = [_stripe_customer(nm) for nm in _STRIPE_CUSTS] + +# Decoy refund that references a NON-target payment (watermark; not the targets). +_STRIPE_REFUNDS = [ + {'id': 're_decoy_pioneer_01', 'amount': 4999, 'currency': 'usd', + 'charge': 'pi_already_pioneer_09', 'reason': 'duplicate', 'status': 'succeeded', + 'created': _ts('2026-06-11'), 'metadata': {}}, +] + +_STRIPE_STATE = { + 'business': { + 'name': 'Northwind SaaS', 'email': 'admin@northwind-saas.com', + 'url': 'https://northwind-saas.com', 'support_email': 'support@northwind-saas.com', + 'country': 'US', 'currency': 'usd', 'timezone': 'America/Los_Angeles', + }, + 'currentUser': {'id': 'user_admin', 'name': 'Finance Admin', + 'email': 'admin@northwind-saas.com', 'role': 'administrator', 'avatar': None}, + 'balance': {'available': 8421500, 'pending': 1530000, 'reserved': 0, 'currency': 'usd'}, + 'customers': _STRIPE_CUSTOMERS, + 'payments': _STRIPE_PAYMENTS, + 'products': [], + 'prices': [], + 'invoices': [], + 'subscriptions': _STRIPE_SUBS, + 'payouts': [], + 'disputes': [], + 'refunds': _STRIPE_REFUNDS, # decoy only; NONE references a refund target (Rule 3) + 'balanceTransactions': [], + 'events': [], + 'paymentMethods': [], + 'testMode': False, + 'searchQuery': '', + 'selectedDateRange': '30d', + 'metrics': { + 'today': {'grossVolume': 0, 'grossVolumeChart': []}, + 'summary': { + 'grossVolume': {'amount': 100097, 'change': 0, 'previousAmount': 0}, + 'netVolume': {'amount': 97000, 'change': 0, 'previousAmount': 0}, + 'disputeActivity': {'rate': 0, 'change': 0, 'previousRate': 0}, + }, + 'chartData': {'grossVolume': [], 'netVolume': [], 'disputeRate': []}, + }, +} + + +# =========================================================================== +# 2) QUICKBOOKS — invoices (+ customers). Amounts in DOLLARS. +# =========================================================================== +_QB_CUSTOMERS = [ + {'id': 'c1', 'name': 'Dev Solutions LLC', 'company': 'Dev Solutions LLC', 'email': 'accounts@devsolutions.co', 'phone': '(555) 100-2001'}, + {'id': 'c2', 'name': 'BrightPath Education', 'company': 'BrightPath Education', 'email': 'admin@brightpath.edu', 'phone': '(555) 100-2002'}, + {'id': 'c3', 'name': 'Summit Retail', 'company': 'Summit Retail', 'email': 'billing@summitretail.com', 'phone': '(555) 100-2003'}, + {'id': 'c4', 'name': 'Harbor Logistics', 'company': 'Harbor Logistics', 'email': 'ap@harborlogistics.com', 'phone': '(555) 100-2004'}, +] +for _c in _QB_CUSTOMERS: + _c.setdefault('address', '100 Market St, San Francisco, CA 94105') + _c.setdefault('balance', 0) + _c.setdefault('notes', '') + _c.setdefault('isActive', True) + _c.setdefault('createdAt', '2026-01-08') + + +def _qb_invoice(inv_id, number, customer_id, due_date, total, status): + inv_date = (_dt.date.fromisoformat(due_date) - _dt.timedelta(days=30)).isoformat() + paid = (status == 'Paid') + return { + 'id': inv_id, + 'number': number, + 'customerId': customer_id, + 'date': inv_date, + 'dueDate': due_date, + 'items': [{'id': f'{inv_id}_li1', 'productId': 'p1', + 'description': 'Professional services', 'qty': 1, + 'rate': total, 'amount': total}], + 'subtotal': total, + 'tax': 0, + 'total': total, + 'status': status, + 'paidAmount': total if paid else 0, + 'paidDate': inv_date if paid else None, + 'terms': 'Net 30', + 'message': '', + 'createdAt': f'{inv_date}T09:00:00Z', + } + + +# Invoices: 2 receive-payment targets (Sent/Overdue) + 1 unpaid decoy (receiving +# payment on it = FALSE POSITIVE) + 2 already-Paid decoys + 1 Draft decoy. +_QB_INVOICES = [ + # --- RECEIVE_PAYMENT targets — ABSENT: not Paid, paidAmount=0 --- + _qb_invoice('inv_dev_1042', '1042', 'c1', '2026-06-10', 1800.00, 'Sent'), # target + _qb_invoice('inv_bright_1057', '1057', 'c2', '2026-05-20', 3200.00, 'Overdue'), # target + + # --- LEAVE / leak bait: an unpaid invoice NOT referenced by any sheet row --- + _qb_invoice('inv_summit_1099', '1099', 'c3', '2026-06-15', 500.00, 'Sent'), # receiving = FP + + # --- watermark decoys (already Paid / Draft) --- + _qb_invoice('inv_paid_1001', '1001', 'c4', '2026-05-01', 2200.00, 'Paid'), + _qb_invoice('inv_paid_1002', '1002', 'c1', '2026-04-25', 9900.00, 'Paid'), + _qb_invoice('inv_draft_1100', '1100', 'c4', '2026-06-25', 1750.00, 'Draft'), +] + +_QB_STATE = { + 'company': { + 'name': 'Northwind SaaS', 'address': '123 Business Rd, San Francisco, CA 94105', + 'email': 'admin@northwind-saas.com', 'industry': 'Technology Services', + 'accountingMethod': 'Accrual', + }, + 'customers': _QB_CUSTOMERS, + 'invoices': _QB_INVOICES, +} + + +# =========================================================================== +# 3) THE WORKLIST + PRECOMPUTED ANSWER KEY (single source of truth) +# =========================================================================== +# Index injected records so the key can point at real ids + verify pre-state. +_PAY_BY_ID = {p['id']: p for p in _STRIPE_PAYMENTS} +_SUB_BY_ID = {s['id']: s for s in _STRIPE_SUBS} +_INV_BY_ID = {i['id']: i for i in _QB_INVOICES} + +HEADERS = ['Customer', 'Exception Type', 'Amount', 'Invoice #'] + +# Each row references the target record id (or None for the no-match row). +# (customer, exception_type, amount_dollars, invoice_num, +# stripe_payment_id, stripe_subscription_id, qb_invoice_id) +_ROW_SPECS = [ + # --- REFUND (Duplicate charge) --- + dict(customer='Acme Corporation', exception_type='Duplicate charge', amount=250.00, invoice_num='', + stripe_payment_id='pi_refund_acme_0001', stripe_subscription_id=None, qb_invoice_id=None), + dict(customer='Globex Industries', exception_type='Duplicate charge', amount=99.99, invoice_num='', + stripe_payment_id='pi_refund_globex_0002', stripe_subscription_id=None, qb_invoice_id=None), + # --- CANCEL_EOP (Churn - downgrade) --- + dict(customer='TechStart Inc.', exception_type='Churn - downgrade', amount=149.97, invoice_num='', + stripe_payment_id=None, stripe_subscription_id='sub_techstart00001', qb_invoice_id=None), + dict(customer='Riverside Medical Group', exception_type='Churn - downgrade', amount=299.99, invoice_num='', + stripe_payment_id=None, stripe_subscription_id='sub_riverside00001', qb_invoice_id=None), + # --- RECEIVE_PAYMENT (Payment received) --- + dict(customer='Dev Solutions LLC', exception_type='Payment received', amount=1800.00, invoice_num='1042', + stripe_payment_id=None, stripe_subscription_id=None, qb_invoice_id='inv_dev_1042'), + dict(customer='BrightPath Education', exception_type='Payment received', amount=3200.00, invoice_num='1057', + stripe_payment_id=None, stripe_subscription_id=None, qb_invoice_id='inv_bright_1057'), + # --- LEAVE (On hold / Under review) — tempting distractors --- + dict(customer='CloudSync Pro', exception_type='On hold', amount=480.00, invoice_num='', + stripe_payment_id=None, stripe_subscription_id='sub_cloudsync00001', qb_invoice_id=None), + dict(customer='DataVault Systems', exception_type='Under review', amount=180.00, invoice_num='', + stripe_payment_id='pi_leave_datavault_08', stripe_subscription_id=None, qb_invoice_id=None), + # --- already-refunded 'Duplicate charge' -> must be SKIPPED --- + dict(customer='Pioneer Labs', exception_type='Duplicate charge', amount=49.99, invoice_num='', + stripe_payment_id='pi_already_pioneer_09', stripe_subscription_id=None, qb_invoice_id=None), + # --- no matching Stripe/QB record -> SKIP --- + dict(customer='Zenith Partners', exception_type='Payment received', amount=750.00, invoice_num='9999', + stripe_payment_id=None, stripe_subscription_id=None, qb_invoice_id=None), +] + + +def _decide(spec): + """Derive (action, requires_action) from Exception Type VERIFIED against the + current injected state. Precomputed so the visible row <=> key can't drift.""" + et = spec['exception_type'].strip().lower() + + if et == 'duplicate charge': + pid = spec['stripe_payment_id'] + pay = _PAY_BY_ID.get(pid) if pid else None + if pay is None: + return 'skip', False + already = bool(pay.get('refunded')) or ( + pay.get('amount', 0) > 0 and pay.get('amount_refunded', 0) >= pay.get('amount', 0)) + return 'refund', (not already) + + if et == 'churn - downgrade': + sid_ = spec['stripe_subscription_id'] + sub = _SUB_BY_ID.get(sid_) if sid_ else None + if sub is None: + return 'skip', False + already = bool(sub.get('cancel_at_period_end')) or ( + str(sub.get('status', '')).lower() == 'canceled') + return 'cancel_eop', (not already) + + if et == 'payment received': + iid = spec['qb_invoice_id'] + inv = _INV_BY_ID.get(iid) if iid else None + if inv is None: + return 'skip', False + already = (str(inv.get('status', '')).lower() == 'paid') + return 'receive_payment', (not already) + + # 'On hold' / 'Under review' (and anything else) -> LEAVE + return 'leave', False + + +expected = [] +sheet_rows_dict = [] +for idx, spec in enumerate(_ROW_SPECS): + action, requires_action = _decide(spec) + row_index = idx + 2 # sheet row (row 1 = header) + + pid = spec['stripe_payment_id'] + refund_amount_cents = None + if action == 'refund' and pid: + refund_amount_cents = _PAY_BY_ID[pid].get('amount') + + inv_id = spec['qb_invoice_id'] + qb_invoice_number = None + if inv_id and inv_id in _INV_BY_ID: + qb_invoice_number = _INV_BY_ID[inv_id].get('number') + + expected.append({ + 'row_index': row_index, + 'customer': spec['customer'], + 'exception_type': spec['exception_type'], + 'action': action, + 'requires_action': bool(requires_action), + 'stripe_payment_id': pid if action == 'refund' else None, + 'refund_amount_cents': refund_amount_cents, + 'stripe_subscription_id': spec['stripe_subscription_id'] if action == 'cancel_eop' else None, + 'qb_invoice_id': inv_id if action == 'receive_payment' else None, + 'qb_invoice_number': qb_invoice_number if action == 'receive_payment' else None, + }) + + sheet_rows_dict.append({ + 'Customer': spec['customer'], + 'Exception Type': spec['exception_type'], + 'Amount': f"{spec['amount']:.2f}", + 'Invoice #': spec['invoice_num'], + }) + + +# ---- resolved counts (for the DEBUG line / believable data) ---- +refund_rows = [e for e in expected if e['action'] == 'refund' and e['requires_action']] +cancel_rows = [e for e in expected if e['action'] == 'cancel_eop' and e['requires_action']] +receive_rows = [e for e in expected if e['action'] == 'receive_payment' and e['requires_action']] +leave_rows = [e for e in expected if e['action'] == 'leave'] +refund_done = [e for e in expected if e['action'] == 'refund' and not e['requires_action']] +skip_rows = [e for e in expected if e['action'] == 'skip'] +requires_rows = [e for e in expected if e['requires_action']] +resolved_count = len(requires_rows) + +# --------------------------------------------------------------------------- +# Build-time asserts — pin the partition sizes + Rule-3 absences. +# --------------------------------------------------------------------------- +assert len(_ROW_SPECS) == 10, len(_ROW_SPECS) +assert len(refund_rows) == 2, refund_rows # 2 REFUND require action +assert len(cancel_rows) == 2, cancel_rows # 2 CANCEL_EOP require action +assert len(receive_rows) == 2, receive_rows # 2 RECEIVE_PAYMENT require action +assert len(leave_rows) == 2, leave_rows # 2 LEAVE (On hold / Under review) +assert len(refund_done) == 1, refund_done # 1 already-refunded distractor +assert len(skip_rows) == 1, skip_rows # 1 no-match +assert resolved_count == 6, resolved_count # 6 require action +assert (len(leave_rows) + len(refund_done) + len(skip_rows)) == 4 # 4 must be skipped + +# Rule 3: refund targets NOT yet refunded. +for e in refund_rows: + p = _PAY_BY_ID[e['stripe_payment_id']] + assert p['refunded'] is False and p['amount_refunded'] == 0, p['id'] +# Rule 3: the already-done distractor IS refunded (must be left alone). +_pioneer = _PAY_BY_ID['pi_already_pioneer_09'] +assert _pioneer['refunded'] is True and _pioneer['amount_refunded'] == _pioneer['amount'] +# Rule 3: cancel targets NOT yet cancel_at_period_end and still active. +for e in cancel_rows: + s = _SUB_BY_ID[e['stripe_subscription_id']] + assert s['cancel_at_period_end'] is False and s['status'] == 'active', s['id'] +# Rule 3: receive targets NOT yet Paid. +for e in receive_rows: + inv = _INV_BY_ID[e['qb_invoice_id']] + assert str(inv['status']).lower() in ('sent', 'overdue'), inv['status'] + assert inv['paidAmount'] == 0 and inv['paidDate'] is None, inv['id'] +# Rule 3: NO refund references any refund target. +_target_pay_ids = {e['stripe_payment_id'] for e in refund_rows} +assert all(r['charge'] not in _target_pay_ids for r in _STRIPE_REFUNDS) + +print(f'Precomputed worklist: refund={len(refund_rows)} cancel_eop={len(cancel_rows)} ' + f'receive_payment={len(receive_rows)} leave={len(leave_rows)} ' + f'already_refunded={len(refund_done)} no_match={len(skip_rows)} ' + f'-> requires_action={resolved_count}, skipped={10 - resolved_count}') + + +# =========================================================================== +# 4) GOOGLE SHEETS — 'Billing Exceptions' workbook, tab 'Exceptions' +# (NO 'Reconciliation Summary' tab at injection — Rule 3) +# =========================================================================== +COL_LETTERS = ['A', 'B', 'C', 'D'] + + +def _header_cell(text): + return {'value': text, 'formula': text, 'computed': text, + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}} + + +def _text_cell(text): + return {'value': text, 'formula': text, 'computed': text} + + +def _money_cell(text): + return {'value': text, 'formula': text, 'computed': text, 'format': 'currency'} + + +_sheet_data = {} +for col, head in zip(COL_LETTERS, HEADERS): + _sheet_data[f'{col}1'] = _header_cell(head) +for i, row in enumerate(sheet_rows_dict): + r = i + 2 + _sheet_data[f'A{r}'] = _text_cell(row['Customer']) + _sheet_data[f'B{r}'] = _text_cell(row['Exception Type']) + _sheet_data[f'C{r}'] = _money_cell(row['Amount']) + _sheet_data[f'D{r}'] = _text_cell(row['Invoice #']) + +_SHEETS_STATE = { + 'id': 'workbook_cc91abcd_billing_exceptions', + 'title': 'Billing Exceptions', + 'activeSheetId': 'sheet_exceptions', + 'selectedCell': 'A1', + 'selectionRange': None, + 'clipboard': None, + 'isDragging': False, + 'undoStack': [], + 'redoStack': [], + 'namedRanges': [], + 'conditionalFormats': [], + 'charts': [], + 'showGridlines': True, + 'showFormulas': False, + 'zoom': 100, + 'sheets': [{ + 'id': 'sheet_exceptions', + 'name': 'Exceptions', + 'data': _sheet_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': 'rows_dict', + 'task_id': TASK_ID, + 'variant': 'eval', + 'sheet_names': ['Exceptions'], + 'headers_by_sheet': {'Exceptions': HEADERS}, + 'task_sheets': {'Exceptions': {'headers': HEADERS, 'rows': sheet_rows_dict}}, + # ---- ANSWER KEY ---- + 'expected': expected, + 'summary_tab_name': SUMMARY_TAB_NAME, + 'resolved_count': resolved_count, + 'n_refund': len(refund_rows), + 'n_cancel_eop': len(cancel_rows), + 'n_receive_payment': len(receive_rows), + }, +} + +# Rule 3 guard: the 'Reconciliation Summary' tab must be ABSENT at injection. +assert all(str(sh.get('name', '')).strip().lower() != SUMMARY_TAB_NAME.lower() + for sh in _SHEETS_STATE['sheets']), 'Reconciliation Summary tab must be absent' + + +# =========================================================================== +# 5) SLACK — #finance starts EMPTY (Rule 3); decoy chatter elsewhere. +# =========================================================================== +_SLACK_STATE = { + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', + 'topic': 'Welcome to Northwind SaaS!', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'finance', 'name': 'finance', 'description': 'Finance ops — billing exceptions and reconciliation', + 'topic': 'Post a summary when you finish the weekly reconciliation', 'isPrivate': False, + 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1', + 'createdAt': '2026-06-01T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana', + 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + 'users': [ + {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana', + 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya', + 'email': 'maya.lindqvist@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Controller', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'Europe/Stockholm'}, + ], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind SaaS', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', + 'content': 'Morning all — reminder that Q2 books close on Friday.', + 'timestamp': '2026-06-29T13:02:00Z', 'reactions': [], 'isEdited': False, + 'threadId': None, 'attachments': []}, + ], + # #finance starts EMPTY — the gradable post + pin are the agent's work. + 'finance': [], + }, + '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, # agent posts + pins here (empty at injection) + 'resolved_count': resolved_count, + }, +} + +# Rule 3 guard: #finance has no messages and nothing pinned at injection. +_fin = next(c for c in _SLACK_STATE['channels'] if c['name'] == SUMMARY_CHANNEL) +assert _fin['pinnedMessages'] == [], 'finance must have no pinned messages at injection' +assert _SLACK_STATE['messages'].get(SUMMARY_CHANNEL) == [], 'finance must be empty at injection' + + +# =========================================================================== +# 6) INJECT + VERIFY + LAUNCH (domain order: stripe, quickbooks, sheets, slack) +# =========================================================================== +APP_STATES = [ + ('http://28.7.184.198:8179', _STRIPE_STATE), # stripe_dashboard_mock + ('http://28.7.184.198:8172', _QB_STATE), # quickbooks_mock + ('http://28.7.184.198:8145', _SHEETS_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/ar_billing_exception_012__long/reward.py b/ar_billing_exception_012__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..da5f4eef344e95db553061fc0df354f1b8476c69 --- /dev/null +++ b/ar_billing_exception_012__long/reward.py @@ -0,0 +1,649 @@ +""" +Reward Script: Weekly billing-exceptions reconciliation +Task ID: ar_billing_exception_012__long +Mocks: stripe_dashboard_mock,quickbooks_mock,google_sheets_mock,slack_mock + +Scoring (all components in [0,1]; weights sum to 1.0; NO subtracted penalties — +leak is punished ONLY by precision inside the three F1 set-membership components): + 0.30 refund set correctness — F1(true, pred): + true = {stripe_payment_id of REFUND rows that require action} + pred = {payment ids REFUNDED now AND NOT refunded at injection} (a diff). + Refunding the already-refunded distractor cannot enter pred (no diff); + refunding a LEAVE-row / non-target payment IS a false positive -> precision down. + 0.25 cancel-at-period-end set correctness — F1(true, pred): + true = {subscription_id of CANCEL_EOP rows} + pred = {sub ids with cancel_at_period_end==True now AND False at injection}. + Cancelling IMMEDIATELY (status->'canceled') does NOT set cancel_at_period_end, + so it is NOT a true positive (wrong control). Cancelling a LEAVE sub = FP. + 0.25 receive-payment set correctness — F1(true, pred): + true = {qb_invoice_id of RECEIVE_PAYMENT rows} + pred = {invoice ids 'Paid' now AND not 'Paid' at injection}. + 0.10 Reconciliation Summary tab: 1.0 iff a sheet named 'Reconciliation Summary' + exists now, did NOT at injection (diff name-set), AND has >=1 numeric cell. + 0.05 Slack #finance post: a non-empty message exists in #finance. + 0.05 Slack #finance pin: a pinned #finance message referencing a real posted + message (gated on a post existing). + +Answer key: read from google_sheets.initial_state._task_adapter + .expected -> per-row worklist (action / requires_action / target ids) + .summary_tab_name -> 'Reconciliation Summary' +and slack.initial_state._task_adapter.summary_channel -> 'finance'. + +Stripe amounts are CENTS, QuickBooks amounts are DOLLARS. +""" +import copy +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 = {'stripe_dashboard': 'http://28.7.184.198:8179', 'quickbooks': 'http://28.7.184.198:8172', + '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 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): + if not isinstance(msg, dict): + return '' + return msg.get('content') or msg.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) if isinstance(slack_state, dict) else [] + target = None + for ch in channels: + if isinstance(ch, dict) and 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 target.get('id'), []) or [] + return [] + + +def _to_float(v): + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _sheet_rows(sheet): + if not isinstance(sheet, dict): + return [] + rows = sheet.get('rows', []) + return rows if isinstance(rows, list) else [] + + +def _sheet_tabs(sheets): + if isinstance(sheets, dict): + return sheets + if isinstance(sheets, list): + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') + if name: + out[name] = sh + return out + return {} + + +def _jaccard(a, b): + if not a and not b: + return 1.0 + u = a | b + return (len(a & b) / len(u)) if u else 1.0 + + +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 [], + 'attachments': m.get('attachments') if isinstance(m.get('attachments'), 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 +# +# Answer key lives in google_sheets.initial_state._task_adapter.expected — a list +# of per-row dicts with: +# action ∈ {refund, cancel_eop, receive_payment, leave, skip} +# requires_action: bool +# stripe_payment_id | refund_amount_cents (refund target) +# stripe_subscription_id (cancel_eop target) +# qb_invoice_id | qb_invoice_number (receive_payment target) +# summary_tab_name (sheets adapter) and summary_channel (slack adapter) name the +# aux artefacts. We score CURRENT state against this key using precision-aware F1 +# set-membership for the three action sets — leak (acting on a distractor / LEAVE +# item / wrong control) lowers precision but never drives the score below 0. +# ============================================================================= +def _refunded_id_set(stripe_state): + """Payment ids that are (fully) refunded in this Stripe state — union of the + payments[].refunded/amount_refunded flags and any refunds[].charge id.""" + ids = set() + for p in (stripe_state.get('payments') or []): + if not isinstance(p, dict): + continue + pid = norm(p.get('id')) + if not pid: + continue + amt = p.get('amount') or 0 + ar = p.get('amount_refunded') or 0 + try: + fully = (float(amt) > 0 and float(ar) >= float(amt)) + except (TypeError, ValueError): + fully = False + if p.get('refunded') is True or fully: + ids.add(pid) + for r in (stripe_state.get('refunds') or []): + if isinstance(r, dict) and r.get('charge'): + ids.add(norm(r.get('charge'))) + return ids + + +def _cap_id_set(stripe_state): + """Subscription ids flagged cancel_at_period_end (an EOP cancel specifically; + an immediate cancel sets status='canceled' and leaves this flag False).""" + ids = set() + for s in (stripe_state.get('subscriptions') or []): + if not isinstance(s, dict): + continue + if s.get('cancel_at_period_end') is True and norm(s.get('status')) != 'canceled': + ids.add(norm(s.get('id'))) + return ids + + +def _paid_invoice_id_set(qb_state): + ids = set() + for inv in (qb_state.get('invoices') or []): + if isinstance(inv, dict) and norm(inv.get('status')) == 'paid': + ids.add(norm(inv.get('id'))) + return ids + + +def _raw_sheets(state): + """Raw sheet dicts (list) — prefer the pre-materialization _ui_workbook copy.""" + if not isinstance(state, dict): + return [] + ui = state.get('_ui_workbook') + if isinstance(ui, dict) and isinstance(ui.get('sheets'), list): + return ui['sheets'] + sheets = state.get('sheets') + if isinstance(sheets, list): + return sheets + return [] + + +def _sheet_name_set(state): + out = set() + for sh in _raw_sheets(state): + if isinstance(sh, dict) and sh.get('name'): + out.add(norm(sh.get('name'))) + # also fold in materialized-dict keys (belt & suspenders) + sheets = state.get('sheets') if isinstance(state, dict) else None + if isinstance(sheets, dict): + for k in sheets: + out.add(norm(k)) + return out + + +def _sheet_has_numeric_cell(state, tab_name): + for sh in _raw_sheets(state): + if not isinstance(sh, dict) or norm(sh.get('name')) != norm(tab_name): + continue + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + for cell in data.values(): + if isinstance(cell, dict): + for k in ('computed', 'value', 'formula'): + v = cell.get(k) + if isinstance(v, bool): + continue + if isinstance(v, (int, float)): + return True + if isinstance(v, str): + s = v.replace('$', '').replace(',', '').strip() + if s and re.fullmatch(r'-?\d+(\.\d+)?', s): + return True + elif isinstance(cell, (int, float)) and not isinstance(cell, bool): + return True + return False + + +def reward(go): + W_REFUND = 0.30 + W_CANCEL = 0.25 + W_RECEIVE = 0.25 + W_TAB = 0.10 + W_POST = 0.05 + W_PIN = 0.05 + + # ---- 1) Answer key from google_sheets initial_state._task_adapter ---- + gs = go('google_sheets') + gs_init = gs.get('initial_state', {}) if isinstance(gs.get('initial_state'), dict) else {} + gs_cur = gs.get('current_state', {}) if isinstance(gs.get('current_state'), dict) else {} + adapter = gs_init.get('_task_adapter', {}) if isinstance(gs_init.get('_task_adapter'), dict) else {} + + expected = adapter.get('expected') if isinstance(adapter.get('expected'), list) else [] + summary_tab_name = adapter.get('summary_tab_name') or 'Reconciliation Summary' + + if not expected: + print('DEBUG_cc91abcd fatal=no_expected_worklist total=0.0') + return 0.0 + + refund_true = {norm(e.get('stripe_payment_id')) for e in expected + if isinstance(e, dict) and e.get('action') == 'refund' + and e.get('requires_action') and e.get('stripe_payment_id')} + cancel_true = {norm(e.get('stripe_subscription_id')) for e in expected + if isinstance(e, dict) and e.get('action') == 'cancel_eop' + and e.get('requires_action') and e.get('stripe_subscription_id')} + receive_true = {norm(e.get('qb_invoice_id')) for e in expected + if isinstance(e, dict) and e.get('action') == 'receive_payment' + and e.get('requires_action') and e.get('qb_invoice_id')} + + # ---- 2) Stripe: refund set + cancel-at-period-end set (diff vs injection) ---- + stripe = go('stripe_dashboard') + st_init = stripe.get('initial_state', {}) if isinstance(stripe.get('initial_state'), dict) else {} + st_cur = stripe.get('current_state', {}) if isinstance(stripe.get('current_state'), dict) else {} + + refunded_init = _refunded_id_set(st_init) + refunded_now = _refunded_id_set(st_cur) + refund_pred = refunded_now - refunded_init # newly-refunded (diff) + + cap_init = _cap_id_set(st_init) + cap_now = _cap_id_set(st_cur) + cancel_pred = cap_now - cap_init # newly flagged EOP-cancel + + # ---- 3) QuickBooks: receive-payment set (diff vs injection) ---- + qb = go('quickbooks') + qb_init = qb.get('initial_state', {}) if isinstance(qb.get('initial_state'), dict) else {} + qb_cur = qb.get('current_state', {}) if isinstance(qb.get('current_state'), dict) else {} + paid_init = _paid_invoice_id_set(qb_init) + paid_now = _paid_invoice_id_set(qb_cur) + receive_pred = paid_now - paid_init # newly-paid invoices + + # F1 components (precision punishes leak; gate on a non-empty true set so a + # malformed/empty key can never hand out free credit at do-nothing). + s_refund = W_REFUND * (f1(refund_true, refund_pred) if refund_true else 0.0) + s_cancel = W_CANCEL * (f1(cancel_true, cancel_pred) if cancel_true else 0.0) + s_receive = W_RECEIVE * (f1(receive_true, receive_pred) if receive_true else 0.0) + + # ---- 4) Reconciliation Summary tab: NEW named tab with >=1 numeric cell ---- + names_init = _sheet_name_set(gs_init) + names_now = _sheet_name_set(gs_cur) + tab_is_new = norm(summary_tab_name) in names_now and norm(summary_tab_name) not in names_init + tab_has_numeric = _sheet_has_numeric_cell(gs_cur, summary_tab_name) + tab_ok = bool(tab_is_new and tab_has_numeric) + s_tab = W_TAB * (1.0 if tab_ok else 0.0) + + # ---- 5) Slack #finance: post (non-empty) + pin (references a real message) ---- + slack = go('slack') + sl_init = slack.get('initial_state', {}) if isinstance(slack.get('initial_state'), dict) else {} + sl_cur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + s_adapter = sl_init.get('_task_adapter', {}) if isinstance(sl_init.get('_task_adapter'), dict) else {} + summary_channel = s_adapter.get('summary_channel') or 'finance' + + fin_msgs = _slack_channel_messages(sl_cur, summary_channel) + _fin_kw = ('reconcil', 'resolved', 'payment', 'invoice', 'exception', 'refund') + def _is_fin_summary(m): + t = (_msg_text(m) or '').lower() + return bool(t.strip()) and any(k in t for k in _fin_kw) and any(c.isdigit() for c in t) + post_ok = any(_is_fin_summary(m) for m in fin_msgs if isinstance(m, dict)) + s_post = W_POST * (1.0 if post_ok else 0.0) + + # Pin: at least one pinned id in #finance that matches a real posted message. + msg_ids = set() + for m in fin_msgs: + if isinstance(m, dict): + mid = m.get('messageId') or m.get('id') + if mid is not None: + msg_ids.add(norm(mid)) + pinned = [] + for ch in (sl_cur.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel): + pinned = ch.get('pinnedMessages') or [] + break + pinned_ids = set() + for pm in pinned: + if isinstance(pm, dict): + pid = pm.get('messageId') or pm.get('id') + else: + pid = pm + if pid is not None: + pinned_ids.add(norm(pid)) + pin_ok = bool(post_ok and (pinned_ids & msg_ids)) + s_pin = W_PIN * (1.0 if pin_ok else 0.0) + + score = s_refund + s_cancel + s_receive + s_tab + s_post + s_pin + + print( + 'DEBUG_cc91abcd ' + f'refund_true={len(refund_true)} refund_pred={len(refund_pred)} ' + f'refund_f1={round(f1(refund_true, refund_pred) if refund_true else 0.0, 4)} ' + f'cancel_true={len(cancel_true)} cancel_pred={len(cancel_pred)} ' + f'cancel_f1={round(f1(cancel_true, cancel_pred) if cancel_true else 0.0, 4)} ' + f'receive_true={len(receive_true)} receive_pred={len(receive_pred)} ' + f'receive_f1={round(f1(receive_true, receive_pred) if receive_true else 0.0, 4)} ' + f'tab_new={int(tab_is_new)} tab_numeric={int(tab_has_numeric)} ' + f'post_ok={int(post_ok)} pin_ok={int(pin_ok)} ' + f'w_refund={round(s_refund, 4)} w_cancel={round(s_cancel, 4)} w_receive={round(s_receive, 4)} ' + f'w_tab={round(s_tab, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} ' + f'total={round(score, 4)}' + ) + + return clamp01(score) + + +try: + score = float(reward(go)) +except Exception as exc: + print(f'ERROR: reward() raised {exc!r}') + score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') diff --git a/ar_deal_to_invoice_007__long/_cua_gym_vm_bridge.sh b/ar_deal_to_invoice_007__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_deal_to_invoice_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/ar_deal_to_invoice_007__long/initial_setup.py b/ar_deal_to_invoice_007__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb17fa86503f6f5f748461e4d65728fba7fc95b --- /dev/null +++ b/ar_deal_to_invoice_007__long/initial_setup.py @@ -0,0 +1,431 @@ +""" +Initial Setup: X2 — Won deal to invoice to notification +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py +Variant: eval +Mocks: hubspot_mock,quickbooks_mock,gmail_mock +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +APP_STATES = [('http://28.7.184.198:8150', + {'companies': [{'id': 'comp1', 'name': 'Acme', 'domain': 'acme.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0001', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'numberOfEmployees': 250, 'annualRevenue': 15000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Enterprise SaaS platform', 'createDate': '2024-01-10T09:00:00Z'}, + {'id': 'comp2', 'name': 'Globex', 'domain': 'globex.com', 'industry': 'Manufacturing', 'phone': '+1 (555) 100-0002', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'numberOfEmployees': 500, 'annualRevenue': 32000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Industrial parts supplier', 'createDate': '2024-01-12T09:00:00Z'}, + {'id': 'comp3', 'name': 'Initech', 'domain': 'initech.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0003', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'numberOfEmployees': 120, 'annualRevenue': 8000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Office software vendor', 'createDate': '2024-01-14T09:00:00Z'}, + {'id': 'comp4', 'name': 'Umbrella', 'domain': 'umbrella.com', 'industry': 'Healthcare', 'phone': '+1 (555) 100-0004', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'numberOfEmployees': 800, 'annualRevenue': 55000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Healthcare research', 'createDate': '2024-01-16T09:00:00Z'}, + {'id': 'comp5', 'name': 'Wayne', 'domain': 'wayne.com', 'industry': 'Finance', 'phone': '+1 (555) 100-0005', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'numberOfEmployees': 1200, 'annualRevenue': 90000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Financial holding group', 'createDate': '2024-01-18T09:00:00Z'}, + {'id': 'comp6', 'name': 'Stale Co', 'domain': 'stale.com', 'industry': 'Other', 'phone': '+1 (555) 100-0006', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'numberOfEmployees': 90, 'annualRevenue': 5000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Legacy customer (last quarter)', 'createDate': '2024-01-22T09:00:00Z'}, + {'id': 'comp7', 'name': 'Future Inc', 'domain': 'future.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0007', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'numberOfEmployees': 60, 'annualRevenue': 3000000, 'lifecycleStage': 'opportunity', 'owner': 'Admin User', 'description': 'Q2 prospect', 'createDate': '2024-01-24T09:00:00Z'}, + {'id': 'comp8', 'name': 'LostCorp', 'domain': 'lostcorp.com', 'industry': 'Other', 'phone': '+1 (555) 100-0008', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'numberOfEmployees': 40, 'annualRevenue': 2000000, 'lifecycleStage': 'lead', 'owner': 'Admin User', 'description': 'Lost competitive bid', 'createDate': '2024-01-26T09:00:00Z'}], + 'contacts': [{'id': 'c1', 'firstName': '', 'lastName': 'Acme', 'email': 'ap@acme.com', 'phone': '+1 (555) 100-0001', 'jobTitle': 'AP Manager', 'companyId': 'comp1', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-05T10:00:00Z', 'timeline': []}, + {'id': 'c2', 'firstName': '', 'lastName': 'Globex', 'email': 'ap@globex.com', 'phone': '+1 (555) 100-0002', 'jobTitle': 'AP Manager', 'companyId': 'comp2', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-08T10:00:00Z', 'timeline': []}, + {'id': 'c3', 'firstName': '', 'lastName': 'Initech', 'email': 'ap@initech.com', 'phone': '+1 (555) 100-0003', 'jobTitle': 'AP Manager', 'companyId': 'comp3', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-12T10:00:00Z', 'timeline': []}, + {'id': 'c4', 'firstName': '', 'lastName': 'Umbrella', 'email': 'ap@umbrella.com', 'phone': '+1 (555) 100-0004', 'jobTitle': 'AP Manager', 'companyId': 'comp4', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-18T10:00:00Z', 'timeline': []}, + {'id': 'c5', 'firstName': '', 'lastName': 'Wayne', 'email': 'ap@wayne.com', 'phone': '+1 (555) 100-0005', 'jobTitle': 'AP Manager', 'companyId': 'comp5', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-22T10:00:00Z', 'timeline': []}, + {'id': 'c6', 'firstName': '', 'lastName': 'Stale Co', 'email': 'ap@stale.com', 'phone': '+1 (555) 100-0006', 'jobTitle': 'AP Manager', 'companyId': 'comp6', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-03-25T10:00:00Z', 'timeline': []}, + {'id': 'c7', 'firstName': '', 'lastName': 'Future Inc', 'email': 'ap@future.com', 'phone': '+1 (555) 100-0007', 'jobTitle': 'AP Manager', 'companyId': 'comp7', 'lifecycleStage': 'opportunity', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-05-03T10:00:00Z', 'timeline': []}, + {'id': 'c8', 'firstName': '', 'lastName': 'LostCorp', 'email': 'ap@lostcorp.com', 'phone': '+1 (555) 100-0008', 'jobTitle': 'AP Manager', 'companyId': 'comp8', 'lifecycleStage': 'lead', 'leadStatus': 'unqualified', 'owner': 'Admin User', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-15T10:00:00Z', 'timeline': []}], + # Each deal carries the schema fields the hubspot_mock front-end reads + # (name/stage/amount/closeDate/dealType/priority/owner/companyId/ + # contactIds/probability/description). The rewritten reward.py reads the + # same schema (companies[id==deal.companyId].name, contacts[id== + # contactIds[0]].email, deal.description) -- there are NO legacy + # tag-along fields any more. + # + # Single-line-only design: every April Closed Won deal is invoiced with + # exactly one line item. The deal name follows the pattern + # " - " so the agent can derive the QuickBooks + # Product/Service name (the part after " - ") and the QB product catalog + # below seeds a matching product whose price equals deals[].amount. + # + # IMPORTANT: stage value is 'closedwon' (no underscore) because reward.py + # filters won deals via norm(d['stage']) == 'closedwon'. We add a matching + # 'closedwon' entry to dealStages below so the front-end pipeline shows + # those deals in their own labelled column. + 'deals': [{'id': 'd1', 'name': 'Acme - Enterprise License', 'stage': 'closedwon', 'amount': 12000, 'closeDate': '2026-04-05', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp1', 'contactIds': ['c1'], 'probability': 100, 'description': 'Annual enterprise license, 250 seats', 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-04-05T14:00:00Z'}, + {'id': 'd2', 'name': 'Globex - Onboarding Package', 'stage': 'closedwon', 'amount': 7000, 'closeDate': '2026-04-08', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp2', 'contactIds': ['c2'], 'probability': 100, 'description': 'Onboarding bundle (setup + license)', 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-04-08T14:00:00Z'}, + {'id': 'd3', 'name': 'Initech - Annual Subscription', 'stage': 'closedwon', 'amount': 8000, 'closeDate': '2026-04-12', 'dealType': 'existing_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp3', 'contactIds': ['c3'], 'probability': 100, 'description': 'Standard annual plan', 'createDate': '2026-03-05T10:00:00Z', 'lastActivityDate': '2026-04-12T14:00:00Z'}, + {'id': 'd4', 'name': 'Umbrella - Hybrid Plan', 'stage': 'closedwon', 'amount': 8000, 'closeDate': '2026-04-18', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp4', 'contactIds': ['c4'], 'probability': 100, 'description': 'Hybrid plan (seats + support bundled)', 'createDate': '2026-03-08T10:00:00Z', 'lastActivityDate': '2026-04-18T14:00:00Z'}, + {'id': 'd5', 'name': 'Wayne - Renewal', 'stage': 'closedwon', 'amount': 15000, 'closeDate': '2026-04-22', 'dealType': 'existing_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp5', 'contactIds': ['c5'], 'probability': 100, 'description': 'Renewal of existing master contract', 'createDate': '2026-03-12T10:00:00Z', 'lastActivityDate': '2026-04-22T14:00:00Z'}, + {'id': 'd6', 'name': 'Stale Co - Last Quarter', 'stage': 'closedwon', 'amount': 9000, 'closeDate': '2026-03-25', 'dealType': 'existing_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp6', 'contactIds': ['c6'], 'probability': 100, 'description': 'Q1 deal, closed in March 2026', 'createDate': '2026-02-20T10:00:00Z', 'lastActivityDate': '2026-03-25T14:00:00Z'}, + {'id': 'd7', 'name': 'Future Inc - Q2 Pipeline', 'stage': 'contract_sent', 'amount': 11000, 'closeDate': '2026-05-03', 'dealType': 'new_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp7', 'contactIds': ['c7'], 'probability': 90, 'description': 'Q2 deal, awaiting signature', 'createDate': '2026-04-10T10:00:00Z', 'lastActivityDate': '2026-05-03T14:00:00Z'}, + {'id': 'd8', 'name': 'LostCorp - Lost Bid', 'stage': 'closed_lost', 'amount': 7000, 'closeDate': '2026-04-15', 'dealType': 'new_business', 'priority': 'low', 'owner': 'Admin User', 'companyId': 'comp8', 'contactIds': ['c8'], 'probability': 0, 'description': 'Lost to competitor', 'createDate': '2026-02-25T10:00:00Z', 'lastActivityDate': '2026-04-15T14:00:00Z', 'closedLostReason': 'Lost to competitor pricing'}], + 'tickets': [], + 'tasks': [], + # Single-line-only design: no per-deal line-item notes are needed. + 'notes': [], + 'templates': [], + 'meetings': [], + 'forms': [], + # NOTE: 'closedwon' (no underscore) is intentional and matches the literal + # value used in reward.py (norm(d['stage']) == 'closedwon'). The default + # mockData.js dealStages uses 'closed_won' (with underscore); we override + # with this dict so the pipeline view actually has a column whose id === + # 'closedwon' to render our deals into. + 'dealStages': {'appointment_scheduled': {'id': 'appointment_scheduled', 'label': 'Appointment Scheduled', 'probability': 20, 'color': '#E5F4FF', 'order': 1}, + 'qualified_to_buy': {'id': 'qualified_to_buy', 'label': 'Qualified to Buy', 'probability': 40, 'color': '#FFF0E6', 'order': 2}, + 'presentation_scheduled': {'id': 'presentation_scheduled', 'label': 'Presentation Scheduled', 'probability': 60, 'color': '#FFF8E6', 'order': 3}, + 'decision_maker_bought_in': {'id': 'decision_maker_bought_in', 'label': 'Decision Maker Bought-In', 'probability': 80, 'color': '#E8F5E9', 'order': 4}, + 'contract_sent': {'id': 'contract_sent', 'label': 'Contract Sent', 'probability': 90, 'color': '#E6FFFA', 'order': 5}, + 'closedwon': {'id': 'closedwon', 'label': 'Closed Won', 'probability': 100, 'color': '#E6FFEC', 'order': 6}, + 'closed_lost': {'id': 'closed_lost', 'label': 'Closed Lost', 'probability': 0, 'color': '#FFE6E6', 'order': 7}}, + 'ticketStatuses': {'new': {'id': 'new', 'label': 'New', 'color': '#E5F4FF', 'order': 1}, + 'waiting_on_contact': {'id': 'waiting_on_contact', 'label': 'Waiting on Contact', 'color': '#FFF8E6', 'order': 2}, + 'waiting_on_us': {'id': 'waiting_on_us', 'label': 'Waiting on Us', 'color': '#FFF0E6', 'order': 3}, + 'in_progress': {'id': 'in_progress', 'label': 'In Progress', 'color': '#E6FFFA', 'order': 4}, + 'closed': {'id': 'closed', 'label': 'Closed', 'color': '#E6FFEC', 'order': 5}}, + 'appState': {'sidebarOpen': True, 'currentUser': {'name': 'Admin User', 'email': 'admin@example.com', 'avatar': None}}}), + # ---- QuickBooks ---- + # Customer naming convention: B2B mapping. Each pre-seeded customer's `name` + # equals the corresponding HubSpot company's `name`, and `company` is set to + # the same value so the agent can satisfy the instruction's "use that name + # as both Name and Company" rule by selecting an existing record. + # + # Coverage of April 2026 Closed Won deals (d1..d5): + # d1 Acme -> qb_c1 (pre-seeded) + # d2 Globex -> qb_c2 (pre-seeded) + # d3 Initech -> qb_c3 (pre-seeded) + # d4 Umbrella -> qb_c4 (pre-seeded) + # d5 Wayne -> NOT pre-seeded -> agent MUST create it first. + # + # Plus distractors (qb_c5 Hooli, qb_c6 Pied Piper) that are unrelated to any + # HubSpot deal -- they verify the agent picks customers by deal mapping + # rather than blindly choosing the first row. qb_c7 (Stale Co) is the + # historical customer for d6 (March 25 won deal, NOT to be invoiced this run); + # keeping it makes the seed look like a realistic ongoing books. + # + # `products` is pre-seeded with one Service per April Closed Won deal: each + # product's `name` equals the part of the corresponding deal's name after + # " - " (e.g. d1 "Acme - Enterprise License" -> product "Enterprise + # License"), and its `price` equals deals[].amount. This way, when the + # agent picks the product on the invoice line the form auto-fills the Rate + # to the correct amount with no manual override needed. Every product is + # `isTaxable: false` so the form's auto-tax stays at $0. + ('http://28.7.184.198:8172', + {'customers': [{'id': 'qb_c1', 'name': 'Acme', 'company': 'Acme', + 'email': 'ap@acme.com', 'phone': '+1 (555) 100-0001', + 'address': 'San Francisco, CA, United States', + 'balance': 0, 'isActive': True, 'createdAt': '2024-02-01', + 'notes': ''}, + # NOTE: qb_c2 (Globex) / qb_c3 (Initech) / qb_c4 (Umbrella) + # are intentionally NOT pre-seeded. The agent must create + # these customers via Sales -> Customers -> "New customer" + # before invoicing d2/d3/d4 (same as d5 Wayne). Only d1 + # (Acme) starts with a pre-seeded customer in QB. + # Distractors: legitimate-looking customers unrelated to any + # HubSpot deal in this task. These should NOT receive any + # invoice in this run. + {'id': 'qb_c5', 'name': 'Hooli', 'company': 'Hooli', + 'email': 'billing@hooli.com', 'phone': '+1 (555) 200-0001', + 'address': 'Palo Alto, CA, United States', + 'balance': 1500, 'isActive': True, 'createdAt': '2023-09-15', + 'notes': 'Legacy account'}, + {'id': 'qb_c6', 'name': 'Pied Piper', 'company': 'Pied Piper', + 'email': 'ap@piedpiper.com', 'phone': '+1 (555) 200-0002', + 'address': 'San Francisco, CA, United States', + 'balance': 0, 'isActive': True, 'createdAt': '2023-11-02', + 'notes': ''}, + # Historical customer for d6 (March 25 won, OUT of April scope). + {'id': 'qb_c7', 'name': 'Stale Co', 'company': 'Stale Co', + 'email': 'ap@stale.com', 'phone': '+1 (555) 100-0006', + 'address': 'Seattle, WA, United States', + 'balance': 0, 'isActive': True, 'createdAt': '2024-02-01', + 'notes': 'Q1 customer; already invoiced in March.'}], + # One Service per April Closed Won deal. price == deals[].amount so that + # selecting the product on the invoice line auto-fills the Rate correctly. + 'products': [{'id': 'qb_p1', 'name': 'Enterprise License', 'description': 'Annual enterprise license', 'type': 'Service', + 'price': 12000, 'cost': 0, 'category': 'Services', 'sku': '', + 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, + {'id': 'qb_p2', 'name': 'Onboarding Package', 'description': 'Onboarding bundle (setup + license)', 'type': 'Service', + 'price': 7000, 'cost': 0, 'category': 'Services', 'sku': '', + 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, + {'id': 'qb_p3', 'name': 'Annual Subscription', 'description': 'Standard annual plan', 'type': 'Service', + 'price': 8000, 'cost': 0, 'category': 'Services', 'sku': '', + 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, + {'id': 'qb_p4', 'name': 'Hybrid Plan', 'description': 'Hybrid plan (seats + support bundled)', 'type': 'Service', + 'price': 8000, 'cost': 0, 'category': 'Services', 'sku': '', + 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}, + {'id': 'qb_p5', 'name': 'Renewal', 'description': 'Renewal of existing master contract', 'type': 'Service', + 'price': 15000, 'cost': 0, 'category': 'Services', 'sku': '', + 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}], + 'invoices': []}), + ('http://28.7.184.198:8138', {'emails': []})] + + +for app_url, state in APP_STATES: + resp = requests.post( + f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {app_url}: {resp.text}' + ) + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}' + ) + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/ar_deal_to_invoice_007__long/reward.py b/ar_deal_to_invoice_007__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..90ad3f1d0b929ee23f837e884cdaec0be838e089 --- /dev/null +++ b/ar_deal_to_invoice_007__long/reward.py @@ -0,0 +1,826 @@ +""" +Reward Script: X2 — Won deal to invoice to notification +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py +Variant: eval +Mocks: hubspot_mock,quickbooks_mock,gmail_mock +""" +import copy +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 = {'hubspot': 'http://28.7.184.198:8150', 'quickbooks': 'http://28.7.184.198:8172', 'gmail': 'http://28.7.184.198:8138'} +_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 _deal_amount(deal): + if not isinstance(deal, dict): + return 0.0 + line_items = deal.get('lineItems') or [] + if isinstance(line_items, list) and line_items: + total = 0.0 + for item in line_items: + if isinstance(item, dict): + try: + total += float(item.get('amount', 0) or 0) + except (TypeError, ValueError): + continue + return total + try: + return float(deal.get('amount', 0) or 0) + except (TypeError, ValueError): + return 0.0 + +def _invoice_customer_name(iv): + if not isinstance(iv, dict): + return '' + + customer = iv.get('customer') + if isinstance(customer, dict): + return customer.get('name') or customer.get('displayName') or customer.get('customerName') or customer.get('fullName') or '' + + if isinstance(customer, list): + for c in customer: + if isinstance(c, dict): + name = c.get('name') or c.get('displayName') or c.get('customerName') or c.get('fullName') + if name: + return name + elif c: + return str(c) + + return customer or iv.get('customerName') or iv.get('name') or iv.get('displayName') or iv.get('customerDisplayName') or '' + + +def _invoice_total(iv): + if not isinstance(iv, dict): + return 0.0 + + for key in ('total', 'amount', 'invoiceTotal', 'balance', 'totalAmount', 'amountDue', 'amount_total'): + value = iv.get(key) + if isinstance(value, dict): + value = value.get('amount') or value.get('value') + try: + return float(value or 0) + except (TypeError, ValueError): + continue + + line_items = iv.get('lineItems') or iv.get('items') or iv.get('lines') + if isinstance(line_items, list) and line_items: + total = 0.0 + for item in line_items: + if not isinstance(item, dict): + continue + raw = item.get('amount') + if raw is None: + qty = item.get('quantity', 1) + unit = item.get('unitPrice') or item.get('rate') or item.get('price') + try: + raw = float(qty or 0) * float(unit or 0) + except (TypeError, ValueError): + raw = 0 + try: + total += float(raw or 0) + except (TypeError, ValueError): + continue + return total + + return 0.0 + + +def _notes_text(deal): + if not isinstance(deal, dict): + return '' + + chunks = [] + notes = deal.get('notes', []) + if isinstance(notes, list): + for x in notes: + if isinstance(x, dict): + chunks.append(str(x.get('body') or x.get('content') or x.get('text') or x.get('note') or x)) + else: + chunks.append(str(x)) + elif notes: + chunks.append(str(notes)) + + for key in ('activity', 'activities', 'timeline', 'comments'): + value = deal.get(key) + if isinstance(value, list): + for v in value: + if isinstance(v, dict): + chunks.append(str(v.get('body') or v.get('content') or v.get('text') or v.get('note') or v)) + else: + chunks.append(str(v)) + elif value: + chunks.append(str(value)) + + return ' '.join(chunks) + + +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 _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 _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 (rewritten for new schema, per-deal weighted) === +# +# Scoring model (B-mixed, decided 2026-06-15): +# - Each April-Closed-Won deal contributes up to 1.0 to its own score. +# - 6 sub-checks per deal, weights sum to 1.0: +# A1 customer 0.15 invoice exists for this deal's company +# A2 line item 0.20 exactly 1 item with the right product/qty/rate/amount +# (must also match customer name; A2 is self-contained +# and re-checks customer to prevent cross-deal mix-up) +# A3 header 0.15 same invoice has terms/date/dueDate/tax/status correct +# (must also match customer name; self-contained) +# B1 recipient 0.10 a sent gmail email addressed to the right contact +# B2 email body 0.15 email's subject + body match the template anchors, +# with subject/body invoice number self-consistent. +# Independent of A* (does NOT require a real invoice). +# C description 0.25 deal.description contains "Invoiced INV-.". +# Independent of A* (does NOT require a real invoice). +# - total_score = sum(deal_score(d) for d in won) / n +# - n is the count of April-Closed-Won deals in the initial state. +# +# Dependency chain (B-mixed): +# A1 -> A2 (re-checks customer) and A3 (re-checks customer): A group is integrated. +# B1 -> B2 (re-checks recipient): B group is internally chained. +# C is fully standalone (matches the literal pattern in description). +# A and B and C are independent of each other. + +import datetime as _dt +import re as _re + +_INV_NUMBER_RE = _re.compile(r'Invoiced\s+INV-(\d+)\.', _re.IGNORECASE) + + +def _april_won_deals(deals_initial): + out = [] + for d in deals_initial or []: + if not isinstance(d, dict): + continue + if norm(d.get('stage')) != 'closedwon': + continue + close_date = (d.get('closeDate') or '').strip() + if close_date.startswith('2026-04-'): + out.append(d) + return out + + +def _company_name_for_deal(deal, hubspot_initial): + company_id = deal.get('companyId') + for c in hubspot_initial.get('companies', []) or []: + if isinstance(c, dict) and c.get('id') == company_id: + return (c.get('name') or '').strip() + return (deal.get('customer') or '').strip() + + +def _primary_contact_for_deal(deal, hubspot_initial): + contact_ids = deal.get('contactIds') or [] + if not contact_ids: + return None + cid0 = contact_ids[0] + for c in hubspot_initial.get('contacts', []) or []: + if isinstance(c, dict) and c.get('id') == cid0: + return c + return None + + +def _qb_customer_name_by_id(qb_state): + return { + c.get('id'): (c.get('name') or '').strip() + for c in (qb_state.get('customers') or []) + if isinstance(c, dict) and c.get('id') + } + + +def _qb_product_by_id(qb_state): + return { + p.get('id'): p + for p in (qb_state.get('products') or []) + if isinstance(p, dict) and p.get('id') + } + + +def _add_days(date_str, days): + try: + d = _dt.datetime.strptime(date_str, '%Y-%m-%d').date() + except (TypeError, ValueError): + return '' + return (d + _dt.timedelta(days=days)).isoformat() + + +def _invoice_items(iv): + items = iv.get('items') + if isinstance(items, list): + return items + items = iv.get('lineItems') + if isinstance(items, list): + return items + return [] + + +def _check_a1_customer(deal, hubspot_initial, invoices, qb_cust_by_id): + target_name = norm(_company_name_for_deal(deal, hubspot_initial)) + if not target_name: + return None + for iv in invoices or []: + if not isinstance(iv, dict): + continue + cust_name = norm(qb_cust_by_id.get(iv.get('customerId'), '')) + if not cust_name: + cust_name = norm(_invoice_customer_name(iv)) + if cust_name and cust_name == target_name: + return iv + return None + + +def _check_a2_line_item(deal, hubspot_initial, invoices, qb_cust_by_id, qb_prod_by_id): + """Self-contained: find ANY invoice for the deal's company that has the right + single line item. Independent of A1's pick (but typically returns same one).""" + target_name = norm(_company_name_for_deal(deal, hubspot_initial)) + if not target_name: + return False + deal_name = deal.get('name') or '' + if ' - ' not in deal_name: + return False + expected_product = deal_name.split(' - ', 1)[1].strip() + deal_amt = _deal_amount(deal) + + for invoice in invoices or []: + if not isinstance(invoice, dict): + continue + cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), '')) + if not cust_name: + cust_name = norm(_invoice_customer_name(invoice)) + if cust_name != target_name: + continue + items = _invoice_items(invoice) + if len(items) != 1: + continue + item = items[0] + if not isinstance(item, dict): + continue + product = qb_prod_by_id.get(item.get('productId')) or {} + if norm(product.get('name', '')) != norm(expected_product): + continue + try: + qty = float(item.get('qty', 0) or 0) + except (TypeError, ValueError): + qty = 0 + if abs(qty - 1.0) > 1e-6: + continue + try: + rate = float(item.get('rate', 0) or 0) + amt = float(item.get('amount', 0) or 0) + except (TypeError, ValueError): + continue + if abs(rate - deal_amt) > 0.5 or abs(amt - deal_amt) > 0.5: + continue + return True + return False + + +def _check_a3_header(deal, hubspot_initial, invoices, qb_cust_by_id): + """Self-contained: find ANY invoice for the deal's company with correct header.""" + target_name = norm(_company_name_for_deal(deal, hubspot_initial)) + if not target_name: + return False + close_date = (deal.get('closeDate') or '').strip() + expected_due = _add_days(close_date, 30) + + for invoice in invoices or []: + if not isinstance(invoice, dict): + continue + cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), '')) + if not cust_name: + cust_name = norm(_invoice_customer_name(invoice)) + if cust_name != target_name: + continue + if norm(invoice.get('terms')) != 'net 30': + continue + if (invoice.get('date') or '').strip() != close_date: + continue + if (invoice.get('dueDate') or '').strip() != expected_due: + continue + try: + tax = float(invoice.get('tax', 0) or 0) + except (TypeError, ValueError): + tax = 0 + if abs(tax) > 0.01: + continue + if norm(invoice.get('status')) != 'sent': + continue + return True + return False + + +def _check_b1_recipient(deal, hubspot_initial, sent_emails): + contact = _primary_contact_for_deal(deal, hubspot_initial) + if not contact: + return None + target_email = norm(contact.get('email')) + if not target_email: + return None + for e in sent_emails or []: + if not isinstance(e, dict): + continue + if target_email in norm(_email_text(e)): + return e + return None + + +def _check_b2_email_body(deal, hubspot_initial, sent_emails): + """Self-contained: find ANY sent email to the deal's primary contact whose + subject contains 'Invoice #', body contains 'INVOICE #' (same ), + 'Total: $', and 'Status: Sent'. Independent of any QB invoice.""" + contact = _primary_contact_for_deal(deal, hubspot_initial) + if not contact: + return False + target_email = norm(contact.get('email')) + if not target_email: + return False + deal_amt = _deal_amount(deal) + amt_int = 'total: ${}'.format(int(round(deal_amt))) + amt_dec = 'total: ${:.2f}'.format(deal_amt) + subject_re = _re.compile(r'invoice\s*#\s*(\d+)') + + for e in sent_emails or []: + if not isinstance(e, dict): + continue + if target_email not in norm(_email_text(e)): + continue + subject = norm(e.get('subject') or '') + body = e.get('body') or '' + body_text = _re.sub(r'<[^>]+>', ' ', body) + nb = norm(body_text) + + m_sub = subject_re.search(subject) + if not m_sub: + continue + n = m_sub.group(1) + # Body must reference the SAME number (self-consistent). + if 'invoice #{}'.format(n) not in nb: + continue + if amt_int not in nb and amt_dec not in nb: + continue + if 'status: sent' not in nb: + continue + return True + return False + + +def _check_c_description(deal_current): + """Self-contained: deal.description contains 'Invoiced INV-.'. + Independent of any QB invoice. (Falls back to deal.notes for legacy agents.)""" + if not deal_current: + return False + desc = deal_current.get('description') or '' + if _INV_NUMBER_RE.search(desc): + return True + notes_text = _notes_text(deal_current) + if _INV_NUMBER_RE.search(notes_text): + return True + return False + + +WEIGHTS = { + 'A1_customer': 0.15, + 'A2_line_item': 0.20, + 'A3_header': 0.15, + 'B1_recipient': 0.10, + 'B2_email': 0.15, + 'C_description': 0.25, +} + + +def reward(go): + hubspot_i = go('hubspot').get('initial_state', {}) or {} + hubspot_c = go('hubspot').get('current_state', {}) or {} + qb_c = go('quickbooks').get('current_state', {}) or {} + gmail_c = go('gmail').get('current_state', {}) or {} + + deals_i = hubspot_i.get('deals', []) or [] + deals_c_by_id = { + d.get('id'): d + for d in (hubspot_c.get('deals', []) or []) + if isinstance(d, dict) + } + invoices = qb_c.get('invoices', []) or [] + qb_cust_by_id = _qb_customer_name_by_id(qb_c) + qb_prod_by_id = _qb_product_by_id(qb_c) + sent_emails = _gmail_sent_emails(gmail_c) + + won = _april_won_deals(deals_i) + n = len(won) + if n == 0: + print('DEBUG_054e615f n=0 -> vacuous REWARD=1.0') + return 1.0 + + per_deal_lines = [] + pass_counts = {k: 0 for k in WEIGHTS} + total = 0.0 + + for d in won: + deal_id = d.get('id') + deal_current = deals_c_by_id.get(deal_id, {}) + + # A1 picks an invoice for debug logging; A2/A3 are self-contained + # but conceptually still belong to the same A group. + invoice = _check_a1_customer(d, hubspot_i, invoices, qb_cust_by_id) + + checks = { + 'A1_customer': invoice is not None, + 'A2_line_item': _check_a2_line_item(d, hubspot_i, invoices, qb_cust_by_id, qb_prod_by_id), + 'A3_header': _check_a3_header(d, hubspot_i, invoices, qb_cust_by_id), + 'B1_recipient': _check_b1_recipient(d, hubspot_i, sent_emails) is not None, + 'B2_email': _check_b2_email_body(d, hubspot_i, sent_emails), + 'C_description': _check_c_description(deal_current), + } + + deal_score = 0.0 + for k, ok in checks.items(): + if ok: + deal_score += WEIGHTS[k] + pass_counts[k] += 1 + total += deal_score + + flags = ' '.join( + '{}={}'.format(k.split('_', 1)[0], 'Y' if v else 'N') + for k, v in checks.items() + ) + company = _company_name_for_deal(d, hubspot_i) or '?' + per_deal_lines.append( + ' {} {:<12s}: score={:.3f} {}'.format(deal_id, company, deal_score, flags) + ) + + score = total / n + + print('DEBUG_054e615f n={}'.format(n)) + for line in per_deal_lines: + print(line) + rates = ' '.join('{}={}/{}'.format(k.split('_', 1)[0], pass_counts[k], n) for k in WEIGHTS) + print('sub-check pass rates: {}'.format(rates)) + print('total = sum / n = {:.4f} / {} = {:.4f}'.format(total, n, score)) + + 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/ar_invoice_003/initial_setup.py b/ar_invoice_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..68005ae32287a04a774de8e14aab72bfbdc9baa5 --- /dev/null +++ b/ar_invoice_003/initial_setup.py @@ -0,0 +1,279 @@ +""" +Initial Setup: AR invoice issuance chain (Salesforce -> Google Sheets -> Slack) +Task ID: ar_invoice_003 +Domain: mock_websites (salesforce_mock + google_sheets_mock + slack_mock) + +Injects the PRE-TASK baseline into all three mocks under the INITIAL sid. + - Salesforce: read-only source of truth, contains the Closed-Won opportunity. + - Google Sheets 'AR Invoice Ledger': invoices through row 14 (INV-1042), NO INV-1043. + - Slack #finance: prior finance chatter, NO INV-1043 issuance message. +""" +import copy +import hashlib +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +TASK_ID = 'ar_invoice_001' +SID = 'cua-' + hashlib.md5(TASK_ID.encode()).hexdigest()[:16] + +SF_URL = 'http://28.7.184.198:8175' +GS_URL = 'http://28.7.184.198:8145' +SL_URL = 'http://28.7.184.198:8178' +PROXY = {'http': 'http://star-proxy.oa.com:3128', 'https': 'http://star-proxy.oa.com:3128'} + + +# ---------------------------------------------------------------- HTTP helpers +def http_get(url): + last = None + for attempt in range(4): + for proxies in (None, PROXY): + try: + r = requests.get(url, timeout=25, proxies=proxies) + if r.status_code == 200: + return r + last = Exception(f'HTTP {r.status_code}: {r.text[:200]}') + except Exception as e: + last = e + time.sleep(1.0) + raise last + + +def http_post(url, payload): + last = None + for attempt in range(4): + for proxies in (None, PROXY): + try: + r = requests.post(url, json=payload, timeout=30, proxies=proxies) + if r.status_code == 200: + return r + last = Exception(f'HTTP {r.status_code}: {r.text[:200]}') + except Exception as e: + last = e + time.sleep(1.0) + raise last + + +# ----------------------------------------------------------- state builders +def build_salesforce_state(): + """Fetch the rich default Salesforce org and patch the target opportunity.""" + probe = 'cua-probe-' + uuid.uuid4().hex[:8] + d = http_get(f'{SF_URL}/go?sid={probe}').json() + state = copy.deepcopy(d.get('initial_state') or d.get('current_state')) + + # Make user-4 the AE "Sarah Chen" (opportunity owner / Slack recipient). + for u in state.get('users', []): + if u.get('userId') == 'user-4': + u['firstName'] = 'Sarah' + u['lastName'] = 'Chen' + u['email'] = 'sarah.chen@company.com' + u['title'] = 'Account Executive' + + # Patch opp-1 into the Closed-Won target opportunity (source of truth). + for opp in state.get('opportunities', []): + if opp.get('opportunityId') == 'opp-1': + opp['name'] = 'Acme Corp - Platform License' + opp['accountId'] = 'account-1' + opp['amount'] = 48000 + opp['stage'] = 'Closed Won' + opp['probability'] = 100 + opp['closeDate'] = '2026-06-24T00:00:00.000Z' + opp['paymentTerms'] = 'Net 30' + opp['type'] = 'New Business' + opp['ownerId'] = 'user-4' + opp['nextStep'] = 'Issue AR invoice' + opp['description'] = 'Platform license deal, closed won. Net 30 payment terms.' + break + return state + + +def _cell(value, fmt=None, bold=False): + c = {'value': str(value), 'formula': str(value)} + style = {} + if bold: + style = {'bold': True, 'bg': '#E8EAED', 'align': 'center'} + if style: + c['style'] = style + if fmt: + c['format'] = fmt + return c + + +# Ledger baseline rows: A=Invoice#, B=Customer, C=Deal/Contract, D=Amount, +# E=Issue Date, F=Due Date, G=Status, H=AE/Owner. Rows 2..14 (INV-1030..INV-1042). +LEDGER_ROWS = [ + ['INV-1030', 'Globex Inc', 'Globex - Annual Support', 12000, '2026-04-02', '2026-05-02', 'Paid', 'Marcus Johnson'], + ['INV-1031', 'Initech', 'Initech - SaaS Subscription', 8500, '2026-04-10', '2026-05-10', 'Paid', 'Sarah Chen'], + ['INV-1032', 'Umbrella LLC', 'Umbrella - Platform License', 30000, '2026-04-15', '2026-05-15', 'Paid', 'Priya Patel'], + ['INV-1033', 'Soylent Corp', 'Soylent - Data Add-on', 5400, '2026-04-22', '2026-05-22', 'Paid', 'Marcus Johnson'], + ['INV-1034', 'Hooli', 'Hooli - Enterprise License', 64000, '2026-05-01', '2026-05-31', 'Paid', 'Sarah Chen'], + ['INV-1035', 'Vandelay Industries', 'Vandelay - Consulting', 15000, '2026-05-06', '2026-06-05', 'Sent', 'Priya Patel'], + ['INV-1036', 'Stark Industries', 'Stark - Platform License', 52000, '2026-05-12', '2026-06-11', 'Sent', 'Marcus Johnson'], + ['INV-1037', 'Wonka Co', 'Wonka - Annual Support', 9800, '2026-05-18', '2026-06-17', 'Sent', 'Sarah Chen'], + ['INV-1038', 'Cyberdyne', 'Cyberdyne - SaaS Subscription', 22000, '2026-05-24', '2026-06-23', 'Sent', 'Priya Patel'], + ['INV-1039', 'Wayne Enterprises', 'Wayne - Data Add-on', 7600, '2026-05-29', '2026-06-28', 'Sent', 'Marcus Johnson'], + ['INV-1040', 'Tyrell Corp', 'Tyrell - Platform License', 41000, '2026-06-03', '2026-07-03', 'Sent', 'Sarah Chen'], + ['INV-1041', 'Gekko & Co', 'Gekko - Consulting', 18500, '2026-06-09', '2026-07-09', 'Draft', 'Priya Patel'], + ['INV-1042', 'Massive Dynamic', 'Massive Dynamic - Enterprise License', 73000, '2026-06-15', '2026-07-15', 'Draft', 'Marcus Johnson'], +] +HEADERS = ['Invoice #', 'Customer', 'Deal/Contract', 'Amount', 'Issue Date', 'Due Date', 'Status', 'AE/Owner'] +COL_FMT = [None, None, None, 'currency', 'date', 'date', None, None] + + +def build_ledger_data(rows): + cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] + data = {} + for i, h in enumerate(HEADERS): + data[f'{cols[i]}1'] = _cell(h, bold=True) + for r, row in enumerate(rows, start=2): + for i, val in enumerate(row): + data[f'{cols[i]}{r}'] = _cell(val, fmt=COL_FMT[i]) + return data + + +def build_sheets_state(rows): + return { + 'id': 'workbook_1', + 'title': 'AR Invoice Ledger', + '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': 'Ledger', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': '#1A73E8', + 'isHidden': False, + 'columnWidths': {'0': 100, '1': 150, '2': 230, '3': 100, '4': 110, '5': 110, '6': 90, '7': 140}, + 'data': build_ledger_data(rows), + }], + } + + +def build_slack_state(include_issuance=False): + users = [ + {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'AR Analyst', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Sarah Chen', 'displayName': 'Sarah', 'email': 'sarah.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Account Executive', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + {'userId': 'user_3', 'fullName': 'Marcus Johnson', 'displayName': 'Marcus', 'email': 'marcus.johnson@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Finance Manager', 'status': 'away', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_4', 'fullName': 'Priya Patel', 'displayName': 'Priya', 'email': 'priya.patel@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Account Executive', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'}, + ] + current_user = copy.deepcopy(users[0]) + channels = [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', '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': 'finance', 'name': 'finance', 'description': 'Accounts receivable & billing', + 'topic': 'Invoicing, AR, collections', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_3', + 'createdAt': '2026-01-05T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ] + finance_msgs = [ + {'messageId': 'msg_f1', 'senderId': 'user_3', 'content': 'Reminder: month-end AR close is this Friday.', + 'timestamp': '2026-06-22T14:00:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_f2', 'senderId': 'user_2', 'content': 'Can someone confirm the Tyrell invoice went out?', + 'timestamp': '2026-06-22T15:10:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_f3', 'senderId': 'user_1', 'content': 'Yes, INV-1040 was sent on the 3rd.', + 'timestamp': '2026-06-22T15:18:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ] + if include_issuance: + finance_msgs.append({ + 'messageId': 'msg_f_inv1043', 'senderId': 'user_1', + 'content': ('@Sarah Chen Invoice INV-1043 for Acme Corp ($48,000, due 2026-07-24) ' + 'has been issued for the Acme Corp - Platform License deal.'), + 'timestamp': '2026-06-24T15:30:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False, + }) + return { + 'currentUser': current_user, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'users': users, + 'channels': channels, + 'messages': { + 'general': [ + {'messageId': 'msg_g1', 'senderId': 'user_2', 'content': 'Morning team!', + 'timestamp': '2026-06-22T09:00:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'finance': finance_msgs, + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + } + + +# ------------------------------------------------------------------- GUI launch +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) + + +# --------------------------------------------------------------------- main +def main(): + with open('/tmp/task_web_sid', 'w') as f: + f.write(SID) + print(f'INITIAL sid = {SID}') + + # Inject baseline (action:set) into all three mocks. + http_post(f'{SF_URL}/post?sid={SID}', {'action': 'set', 'state': build_salesforce_state()}) + print('Salesforce baseline injected.') + http_post(f'{GS_URL}/post?sid={SID}', {'action': 'set', 'state': build_sheets_state(LEDGER_ROWS)}) + print('Google Sheets baseline injected (last row INV-1042).') + http_post(f'{SL_URL}/post?sid={SID}', {'action': 'set', 'state': build_slack_state(include_issuance=False)}) + print('Slack baseline injected (no INV-1043 issuance message).') + + # Verify each baseline. + sf = http_get(f'{SF_URL}/go?sid={SID}').json() + opp = next(o for o in sf['current_state']['opportunities'] if o['opportunityId'] == 'opp-1') + assert opp['name'] == 'Acme Corp - Platform License' and opp['stage'] == 'Closed Won' and opp['amount'] == 48000 + gs = http_get(f'{GS_URL}/go?sid={SID}').json() + data = gs['current_state']['sheets'][0]['data'] + assert data['A14']['value'] == 'INV-1042', f"A14={data['A14']['value']}" + assert 'A15' not in data, 'baseline must NOT contain INV-1043 row' + sl = http_get(f'{SL_URL}/go?sid={SID}').json() + fin = sl['current_state']['messages']['finance'] + assert not any('INV-1043' in m['content'] for m in fin), 'baseline Slack must NOT mention INV-1043' + print('Verified baseline: SF opp Closed Won, sheet ends at INV-1042, no INV-1043 anywhere.') + + # GUI-ready: open all three tabs in Chrome on the VM display. + launch_gui( + f'google-chrome --no-first-run --no-default-browser-check ' + f'"{SF_URL}/?sid={SID}" "{GS_URL}/?sid={SID}" "{SL_URL}/?sid={SID}"', + delay_sec=3.0, + ) + print(f'GUI_READY: launched Chrome with salesforce/sheets/slack tabs (sid={SID})') + + +main() diff --git a/ar_invoice_003/reward.py b/ar_invoice_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..28087edc2d37c891c9b324364c467f0373f5d525 --- /dev/null +++ b/ar_invoice_003/reward.py @@ -0,0 +1,263 @@ +""" +Reward Script: AR invoice chained task (Salesforce -> Google Sheets -> Slack) +Task ID: ar_invoice_003 +Domain: mock_websites (google_sheets + slack) + +Scoring (1.0 total) — ONLY Google Sheet + Slack are scored; Salesforce is READ-ONLY: + - Sheet (0.5): a genuinely NEW ledger row (INV-1043) is appended below the existing + data with all 8 columns A..H matching the expected values, AND existing rows are + left unchanged. Per-cell graded (0.5 * matched_cells/8), gated on the row being new + and existing rows being untouched. + - Slack (0.5): a NEW message in #finance addressed to Sarah Chen announcing that + invoice INV-1043 for Acme Corp ($48,000, due 2026-07-24) has been issued. + Graded over 5 keyword criteria (0.1 each). + +Both components are anchored to task-introduced changes: they FAIL on initial_env +(no new row, no new message) and PASS on golden_env. +""" +# --- injected by remap_cua_gym_ip.py: resolve dynamic mock host -> self-hosted IP --- +_CUA_GYM_REMAP_INJECTED = True +_CUA_GYM_SLUG_MAP = {'12306': 'http://28.7.184.198:8100', 'canvas-lms': 'http://28.7.184.198:8101', 'expensify': 'http://28.7.184.198:8102', 'pacs-viewer': 'http://28.7.184.198:8103', 'sap': 'http://28.7.184.198:8104', 'servicenow': 'http://28.7.184.198:8105', 'tradingview': 'http://28.7.184.198:8106', 'zendesk': 'http://28.7.184.198:8107', 'adp': 'http://28.7.184.198:8108', 'airtable': 'http://28.7.184.198:8109', 'aliyun': 'http://28.7.184.198:8110', 'amazon': 'http://28.7.184.198:8111', 'amazon-seller': 'http://28.7.184.198:8112', 'amplitude': 'http://28.7.184.198:8113', 'asana': 'http://28.7.184.198:8114', 'aws-console': 'http://28.7.184.198:8115', 'azure': 'http://28.7.184.198:8116', 'bamboohr': 'http://28.7.184.198:8117', 'booking-com': 'http://28.7.184.198:8118', 'canva': 'http://28.7.184.198:8119', 'canvas': 'http://28.7.184.198:8120', 'circleci': 'http://28.7.184.198:8121', 'clio': 'http://28.7.184.198:8122', 'cloudflare': 'http://28.7.184.198:8123', 'coinbase': 'http://28.7.184.198:8124', 'confluence': 'http://28.7.184.198:8125', 'contractbook': 'http://28.7.184.198:8126', 'datadog': 'http://28.7.184.198:8127', 'dingtalk': 'http://28.7.184.198:8128', 'discord': 'http://28.7.184.198:8129', 'docusign': 'http://28.7.184.198:8130', 'ebay': 'http://28.7.184.198:8131', 'epic-health': 'http://28.7.184.198:8132', 'expedia': 'http://28.7.184.198:8133', 'facebook': 'http://28.7.184.198:8134', 'feishu': 'http://28.7.184.198:8135', 'github': 'http://28.7.184.198:8136', 'gitlab': 'http://28.7.184.198:8137', 'gmail': 'http://28.7.184.198:8138', 'google-ads': 'http://28.7.184.198:8139', 'google-analytics': 'http://28.7.184.198:8140', 'google-calendar': 'http://28.7.184.198:8141', 'google-docs': 'http://28.7.184.198:8142', 'google-drive': 'http://28.7.184.198:8143', 'google-flights': 'http://28.7.184.198:8144', 'google-sheets': 'http://28.7.184.198:8145', 'greenhouse': 'http://28.7.184.198:8146', 'gusto': 'http://28.7.184.198:8147', 'hotjar': 'http://28.7.184.198:8148', 'hubspot-marketing': 'http://28.7.184.198:8149', 'hubspot': 'http://28.7.184.198:8150', 'instacart': 'http://28.7.184.198:8151', 'instagram': 'http://28.7.184.198:8152', 'jira': 'http://28.7.184.198:8153', 'klaviyo': 'http://28.7.184.198:8154', 'lattice': 'http://28.7.184.198:8155', 'linear': 'http://28.7.184.198:8156', 'linkedin': 'http://28.7.184.198:8157', 'looker-studio': 'http://28.7.184.198:8158', 'lucidchart': 'http://28.7.184.198:8159', 'mailchimp': 'http://28.7.184.198:8160', 'meta-ads': 'http://28.7.184.198:8161', 'microsoft-teams': 'http://28.7.184.198:8162', 'miro': 'http://28.7.184.198:8163', 'mixpanel': 'http://28.7.184.198:8164', 'monday': 'http://28.7.184.198:8165', 'notion': 'http://28.7.184.198:8166', 'openreview': 'http://28.7.184.198:8167', 'outlook-web': 'http://28.7.184.198:8168', 'paypal': 'http://28.7.184.198:8169', 'pinterest': 'http://28.7.184.198:8170', 'postman': 'http://28.7.184.198:8171', 'quickbooks': 'http://28.7.184.198:8172', 'reddit': 'http://28.7.184.198:8173', 'robinhood': 'http://28.7.184.198:8174', 'salesforce': 'http://28.7.184.198:8175', 'sentry': 'http://28.7.184.198:8176', 'shopify-admin': 'http://28.7.184.198:8177', 'slack': 'http://28.7.184.198:8178', 'stripe-dashboard': 'http://28.7.184.198:8179', 'tableau': 'http://28.7.184.198:8180', 'taobao-seller': 'http://28.7.184.198:8181', 'trello': 'http://28.7.184.198:8182', 'tripadvisor': 'http://28.7.184.198:8183', 'twitter': 'http://28.7.184.198:8184', 'uber-eats': 'http://28.7.184.198:8185', 'vercel': 'http://28.7.184.198:8186', 'wandb': 'http://28.7.184.198:8187', 'wechat': 'http://28.7.184.198:8188', 'weibo': 'http://28.7.184.198:8189', 'westlaw': 'http://28.7.184.198:8190', 'woocommerce': 'http://28.7.184.198:8191', 'workday': 'http://28.7.184.198:8192', 'xiaohongshu': 'http://28.7.184.198:8193', 'youtube': 'http://28.7.184.198:8194', 'zhihu': 'http://28.7.184.198:8195', 'zillow': 'http://28.7.184.198:8196', 'zoom-web': 'http://28.7.184.198:8197'} +def _cua_gym_base(_slug): + return _CUA_GYM_SLUG_MAP.get(_slug, 'https://cua-gym-%s.xlang.ai' % _slug) +# --- end injected --- +import json +import re +import sys +import time + +import requests + +# --- 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) + +PROXY = 'http://star-proxy.oa.com:3128' + + +def fetch_state(app): + """Fetch /go for a mock app. Proxy-first, direct fallback, with retries. + Returns parsed JSON dict or None.""" + url = f'{_cua_gym_base(app)}/go?sid={SID}' + attempts = [ + {'proxies': {'http': PROXY, 'https': PROXY}}, + {'proxies': {'http': PROXY, 'https': PROXY}}, + {'proxies': None}, + {'proxies': None}, + ] + for i, kw in enumerate(attempts): + try: + r = requests.get(url, timeout=30, **kw) + r.raise_for_status() + return r.json() + except Exception as e: + print(f'WARN: fetch {app} attempt {i + 1} failed: {e}') + time.sleep(2) + return None + + +def norm(s): + """Lowercase + collapse whitespace for robust text compare.""" + return re.sub(r'\s+', ' ', str(s).strip().lower()) + + +def norm_amount(s): + """Strip currency symbols / commas / spaces. Drop a trailing '.0'/'.00' decimal.""" + if s is None: + return '' + x = re.sub(r'[^0-9.]', '', str(s)) + if '.' in x: + x = x.rstrip('0').rstrip('.') + return x + + +def date_matches(value, expected): + """Match the expected year/month/day regardless of separators or component order.""" + if value is None: + return False + year, month, day = int(expected[:4]), int(expected[4:6]), int(expected[6:8]) + parts = [int(x) for x in re.findall(r'\d+', str(value))] + if year in parts and month in parts and day in parts: + return True + compact = re.sub(r'[^0-9]', '', str(value)) + return compact in { + f'{year:04d}{month:02d}{day:02d}', + f'{month:02d}{day:02d}{year:04d}', + f'{day:02d}{month:02d}{year:04d}', + } + + +def sheet_rows(state): + """Return {row_index: [A..H values or None]} for non-empty rows of sheet 0.""" + sheets = state.get('sheets') or [] + if not sheets: + return {} + data = sheets[0].get('data', {}) + # determine max row referenced + max_r = 0 + for cid in data: + m = re.match(r'^[A-Z]+(\d+)$', cid) + if m: + max_r = max(max_r, int(m.group(1))) + out = {} + for r in range(1, max_r + 1): + vals = [] + for c in 'ABCDEFGH': + cell = data.get(f'{c}{r}') + vals.append(cell.get('value') if cell else None) + if any(v is not None and str(v) != '' for v in vals): + out[r] = vals + return out + + +def verify_sheet(): + """0.5 max. Graded per-cell, gated on row-is-new AND existing-rows-unchanged.""" + data = fetch_state('google-sheets') + if not data: + print('FAIL: Sheet — could not fetch google-sheets state') + return 0.0 + initial = data.get('initial_state') or {} + current = data.get('current_state') or {} + if not current: + print('FAIL: Sheet — current_state empty') + return 0.0 + + init_rows = sheet_rows(initial) + cur_rows = sheet_rows(current) + + # invoice number -> full row, for existing (initial) rows + def inv_map(rows): + m = {} + for _, vals in rows.items(): + a = (vals[0] or '').strip() if vals[0] else '' + if a.upper().startswith('INV-'): + m[a.upper()] = vals + return m + + init_inv = inv_map(init_rows) + cur_inv = inv_map(cur_rows) + + # Gate A: existing rows unchanged (every initial invoice row identical in current) + unchanged = True + for inv, ivals in init_inv.items(): + cvals = cur_inv.get(inv) + if cvals is None or [norm(x) for x in cvals] != [norm(x) for x in ivals]: + print(f'FAIL: Sheet — existing row {inv} was modified or removed') + unchanged = False + if not unchanged: + return 0.0 + + # Gate B: the target row must be genuinely NEW (absent from initial) + if 'INV-1043' in init_inv: + print('FAIL: Sheet — INV-1043 already present in initial_state (not a new row)') + return 0.0 + new_row = cur_inv.get('INV-1043') + if new_row is None: + print('FAIL: Sheet — no new INV-1043 row found in current_state') + return 0.0 + + # Per-cell match against expected (A..H) + expected = { + 'A': ('INV-1043', 'text'), + 'B': ('Acme Corp', 'text'), + 'C': ('Acme Corp - Platform License', 'text'), + 'D': ('48000', 'amount'), + 'E': ('20260624', 'date'), + 'F': ('20260724', 'date'), + 'G': ('Sent', 'text'), + 'H': ('Sarah Chen', 'text'), + } + cols = 'ABCDEFGH' + matched = 0 + for i, c in enumerate(cols): + exp, kind = expected[c] + actual = new_row[i] + ok = False + if kind == 'text': + ok = norm(actual) == norm(exp) + elif kind == 'amount': + ok = norm_amount(actual) == exp + elif kind == 'date': + ok = date_matches(actual, exp) + if ok: + matched += 1 + print(f'PASS: Sheet cell {c}15 = {actual!r}') + else: + print(f'FAIL: Sheet cell {c}15 — expected {exp!r} ({kind}), got {actual!r}') + + score = 0.5 * (matched / len(cols)) + print(f'Sheet score: {score:.4f} ({matched}/{len(cols)} cells)') + return score + + +def verify_slack(): + """0.5 max. Graded over 5 criteria on a NEW #finance message addressed to Sarah Chen.""" + data = fetch_state('slack') + if not data: + print('FAIL: Slack — could not fetch slack state') + return 0.0 + initial = data.get('initial_state') or {} + current = data.get('current_state') or {} + if not current: + print('FAIL: Slack — current_state empty') + return 0.0 + + init_msgs = (initial.get('messages') or {}).get('finance', []) + cur_msgs = (current.get('messages') or {}).get('finance', []) + + if len(cur_msgs) <= len(init_msgs): + print(f'FAIL: Slack — no new #finance message (init={len(init_msgs)}, cur={len(cur_msgs)})') + return 0.0 + + new_msgs = cur_msgs[len(init_msgs):] + # criteria evaluated over the new messages (best match) + criteria = [ + ('addressed to Sarah Chen', lambda t: 'sarah chen' in t or '@sarah' in t), + ('invoice INV-1043', lambda t: 'inv-1043' in t), + ('customer Acme', lambda t: 'acme' in t), + ('amount 48000', lambda t: '48000' in re.sub(r'[$,\s]', '', t)), + ('due date 2026-07-24', lambda t: date_matches(t, '20260724')), + ] + best = 0 + best_content = '' + for m in new_msgs: + t = norm(m.get('content', '')) + hits = sum(1 for _, fn in criteria if fn(t)) + if hits > best: + best = hits + best_content = m.get('content', '') + # report against best message + if best_content: + tb = norm(best_content) + for name, fn in criteria: + print(f"{'PASS' if fn(tb) else 'FAIL'}: Slack — {name}") + score = 0.5 * (best / len(criteria)) + print(f'Slack score: {score:.4f} ({best}/{len(criteria)} criteria) — msg: {best_content!r}') + return score + + +def main(): + total = 0.0 + try: + total += verify_sheet() + except Exception as e: + print(f'ERROR: Sheet component — {e}') + try: + total += verify_slack() + except Exception as e: + print(f'ERROR: Slack component — {e}') + + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + return final + + +main() diff --git a/ar_payment_004/_cua_gym_vm_bridge.sh b/ar_payment_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_payment_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/ar_payment_004/initial_setup.py b/ar_payment_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..caaf35f0561347dad2b089b9a20bbf506f9955ab --- /dev/null +++ b/ar_payment_004/initial_setup.py @@ -0,0 +1,253 @@ +""" +Initial Setup: AR payment INV-1045 (Initech) — PRE-task state. +Task ID: ar_payment_004 +Domain: libreoffice_calc (HYBRID: local Calc ledger + salesforce_mock + slack_mock) + +Pre-task state: + - Ledger /home/user/ar_payment_002.xlsx, sheet 'AR Invoice Ledger', INV-1045 Status='Sent'. + - Salesforce: Closed-Won opp 'Initech CRM Rollout' owned by Priya Nair, NO payment-received activity. + - Slack #finance: prior chatter only, no settlement notification to Priya Nair. +GUI: libreoffice --calc ledger + google-chrome for salesforce & slack mocks (DISPLAY=:0). +""" + +import os +import shlex +import subprocess +import time +import uuid + +import openpyxl +import requests + +WORKDIR = '/home/user' +TASK_ID = 'ar_payment_002' +OUTPUT = f'{WORKDIR}/{TASK_ID}.xlsx' + +SF_URL = 'http://28.7.184.198:8175' +SLACK_URL = 'http://28.7.184.198:8178' + + +# --------------------------------------------------------------------------- +# Shared baseline builders (identical in initial_setup.py and golden_patch.py) +# --------------------------------------------------------------------------- +def ledger_rows(): + """Fixed columns A=Invoice #,B=Customer,C=Deal/Contract,D=Amount, + E=Issue Date,F=Due Date,G=Status,H=AE/Owner. 10 data rows.""" + return [ + ['INV-1042', 'Acme Corp', 'Acme Enterprise License', 25000, '2026-05-10', '2026-06-09', 'Paid', 'John Smith'], + ['INV-1043', 'Globex', 'Globex Analytics Suite', 48000, '2026-05-15', '2026-06-14', 'Paid', 'Sarah Johnson'], + ['INV-1044', 'Soylent', 'Soylent Data Platform', 31500, '2026-05-20', '2026-06-19', 'Sent', 'Mike Chen'], + ['INV-1045', 'Initech', 'Initech CRM Rollout', 72000, '2026-05-25', '2026-06-24', 'Sent', 'Priya Nair'], + ['INV-1046', 'Umbrella', 'Umbrella Security Audit', 15800, '2026-06-01', '2026-07-01', 'Sent', 'Emily Davis'], + ['INV-1047', 'Hooli', 'Hooli Cloud Migration', 96000, '2026-06-03', '2026-07-03', 'Paid', 'Priya Nair'], + ['INV-1048', 'Stark Industries', 'Stark IoT Integration', 54000, '2026-06-05', '2026-07-05', 'Sent', 'Alex Kim'], + ['INV-1049', 'Wayne Enterprises', 'Wayne Security Platform', 120000, '2026-06-08', '2026-07-08', 'Paid', 'Sarah Johnson'], + ['INV-1050', 'Pied Piper', 'Pied Piper Compression API', 22500, '2026-06-12', '2026-07-12', 'Sent', 'Mike Chen'], + ['INV-1051', 'Wonka', 'Wonka Supply Chain', 38000, '2026-06-15', '2026-07-15', 'Overdue', 'Emily Davis'], + ] + + +def build_ledger(paid_inv1045: bool): + wb = openpyxl.Workbook() + ws = wb.active + ws.title = 'AR Invoice Ledger' + headers = ['Invoice #', 'Customer', 'Deal/Contract', 'Amount', + 'Issue Date', 'Due Date', 'Status', 'AE/Owner'] + for col, h in enumerate(headers, 1): + ws.cell(row=1, column=col, value=h) + for r, row in enumerate(ledger_rows(), 2): + vals = list(row) + if paid_inv1045 and vals[0] == 'INV-1045': + vals[6] = 'Paid' # column G = Status + for c, val in enumerate(vals, 1): + ws.cell(row=r, column=c, value=val) + wb.save(OUTPUT) + + +def salesforce_state(): + """Full baseline Salesforce org with Initech Closed-Won opp owned by Priya Nair, + NO payment-received activity on it.""" + user = { + "userId": "user-1", "firstName": "John", "lastName": "Smith", + "email": "john.smith@company.com", "phone": "(555) 123-4567", + "title": "AR Specialist", "department": "Finance", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + } + users = [ + user, + {"userId": "user-2", "firstName": "Sarah", "lastName": "Johnson", + "email": "sarah.johnson@company.com", "phone": "(555) 222-3333", + "title": "Account Executive", "department": "Sales", "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-2", "timezone": "America/New_York", + "locale": "en-US", "theme": "lightning"}, + {"userId": "user-3", "firstName": "Mike", "lastName": "Chen", + "email": "mike.chen@company.com", "phone": "(555) 333-4444", + "title": "Account Executive", "department": "Sales", "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-3", "timezone": "America/Los_Angeles", + "locale": "en-US", "theme": "lightning"}, + {"userId": "user-6", "firstName": "Priya", "lastName": "Nair", + "email": "priya.nair@company.com", "phone": "(555) 666-7788", + "title": "Senior Account Executive", "department": "Sales", "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-6", "timezone": "America/New_York", + "locale": "en-US", "theme": "lightning"}, + ] + accounts = [ + {"accountId": "account-10", "name": "Initech", "type": "Customer", + "industry": "Technology", "revenue": 48000000, "employees": 320, + "ownerId": "user-6", "phone": "(555) 010-2030", "website": "www.initech.com", + "billingStreet": "4120 Freidrich Lane", "billingCity": "Austin", + "billingState": "TX", "billingZip": "78744", "billingCountry": "USA", + "createdDate": "2025-11-02T10:00:00.000Z", "modifiedDate": "2026-06-01T10:00:00.000Z"}, + {"accountId": "account-11", "name": "Globex", "type": "Customer", + "industry": "Manufacturing", "revenue": 92000000, "employees": 540, + "ownerId": "user-2", "phone": "(555) 040-5060", "website": "www.globex.com", + "billingStreet": "200 Market St", "billingCity": "San Francisco", + "billingState": "CA", "billingZip": "94105", "billingCountry": "USA", + "createdDate": "2025-09-15T10:00:00.000Z", "modifiedDate": "2026-05-20T10:00:00.000Z"}, + ] + contacts = [ + {"contactId": "contact-10", "accountId": "account-10", "firstName": "Bill", + "lastName": "Lumbergh", "title": "VP of Operations", "department": "Operations", + "email": "bill.lumbergh@initech.com", "phone": "(555) 010-2031", "ownerId": "user-6"}, + {"contactId": "contact-11", "accountId": "account-11", "firstName": "Hank", + "lastName": "Scorpio", "title": "CEO", "department": "Executive", + "email": "hank.scorpio@globex.com", "phone": "(555) 040-5061", "ownerId": "user-2"}, + ] + opportunities = [ + {"opportunityId": "opp-10", "name": "Initech CRM Rollout", "accountId": "account-10", + "contactId": "contact-10", "amount": 72000, "closeDate": "2026-06-20T00:00:00.000Z", + "stage": "Closed Won", "probability": 100, "type": "New Business", + "leadSource": "Referral", "nextStep": "Kickoff implementation", + "description": "Company-wide CRM rollout for Initech, 320 seats.", + "ownerId": "user-6", "createdDate": "2026-02-10T10:00:00.000Z", + "modifiedDate": "2026-06-20T10:00:00.000Z"}, + {"opportunityId": "opp-11", "name": "Globex Analytics Suite", "accountId": "account-11", + "contactId": "contact-11", "amount": 48000, "closeDate": "2026-07-30T00:00:00.000Z", + "stage": "Negotiation", "probability": 70, "type": "New Business", + "leadSource": "Website", "nextStep": "Send revised proposal", + "description": "Analytics suite expansion for Globex.", + "ownerId": "user-2", "createdDate": "2026-04-01T10:00:00.000Z", + "modifiedDate": "2026-06-18T10:00:00.000Z"}, + ] + activities = [ + {"activityId": "activity-10", "type": "task", "subject": "Send kickoff agenda to Initech", + "status": "Not Started", "priority": "Normal", "dueDate": "2026-06-26T00:00:00.000Z", + "relatedToType": "Opportunity", "relatedToId": "opp-10", "assignedToId": "user-6", + "description": "Prepare and send implementation kickoff agenda to Bill Lumbergh.", + "createdDate": "2026-06-21T10:00:00.000Z"}, + {"activityId": "activity-11", "type": "event", "subject": "Globex proposal review call", + "status": "Scheduled", "priority": "High", + "startDateTime": "2026-07-02T15:00:00.000Z", "endDateTime": "2026-07-02T15:30:00.000Z", + "relatedToType": "Opportunity", "relatedToId": "opp-11", "assignedToId": "user-2", + "description": "Walk through revised analytics suite proposal.", + "createdDate": "2026-06-19T10:00:00.000Z"}, + ] + return { + "user": user, "users": users, "leads": [], "accounts": accounts, + "contacts": contacts, "opportunities": opportunities, "cases": [], + "activities": activities, "chatterPosts": [], "files": [], "following": [], + "recentlyViewed": [], "dismissedNotifications": [], + } + + +def slack_state(): + """Slack workspace with a #finance channel pre-seeded with prior chatter, + NO settlement notification to Priya Nair. Priya Nair present as a user.""" + current_user = { + "userId": "user_1", "fullName": "John Smith", "displayName": "John", + "email": "john.smith@company.com", "avatar": "https://picsum.photos/200/200?random=1", + "title": "AR Specialist", "status": "online", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/New_York", + } + users = [ + current_user, + {"userId": "user_2", "fullName": "Sarah Johnson", "displayName": "Sarah", + "email": "sarah.johnson@company.com", "avatar": "https://picsum.photos/200/200?random=2", + "title": "Account Executive", "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": "Account Executive", "status": "away", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/Los_Angeles"}, + {"userId": "user_9", "fullName": "Priya Nair", "displayName": "Priya", + "email": "priya.nair@company.com", "avatar": "https://picsum.photos/200/200?random=9", + "title": "Senior Account Executive", "status": "online", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/New_York"}, + ] + channels = [ + {"channelId": "general", "name": "general", "description": "Company-wide announcements", + "topic": "Welcome!", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3", "user_9"], "createdBy": "user_1", + "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "finance", "name": "finance", "description": "Accounts receivable, billing, and collections", + "topic": "AR / billing coordination", "isPrivate": False, "isStarred": True, + "members": ["user_1", "user_2", "user_3", "user_9"], "createdBy": "user_1", + "createdAt": "2026-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ] + messages = { + "general": [ + {"messageId": "msg_g1", "senderId": "user_3", "content": "Morning all, quarterly close is next week.", + "timestamp": "2026-06-29T09:00:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + "finance": [ + {"messageId": "msg_f1", "senderId": "user_2", "content": "Reminder: please log payments in Salesforce as they land so AR stays clean.", + "timestamp": "2026-06-26T13:10:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + {"messageId": "msg_f2", "senderId": "user_9", "content": "Still waiting on Initech's wire for the CRM Rollout, will confirm once it clears.", + "timestamp": "2026-06-27T16:45:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + {"messageId": "msg_f3", "senderId": "user_1", "content": "Thanks Priya — I'll mark the invoice paid the moment treasury confirms receipt.", + "timestamp": "2026-06-27T17:02:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + } + return { + "currentUser": current_user, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", "icon": ""}, + "users": users, "channels": channels, "messages": messages, "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), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + + +def main(): + # --- 1. Local ledger (INV-1045 Status='Sent') --- + build_ledger(paid_inv1045=False) + print(f'Initial ledger created: {OUTPUT}') + + # --- 2. Shared sid for both mocks --- + sid = str(uuid.uuid4()) + with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + # --- 3. Inject Salesforce + Slack initial state (action 'set') --- + for name, url, state in [ + ('salesforce', SF_URL, salesforce_state()), + ('slack', SLACK_URL, slack_state()), + ]: + r = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert r.status_code == 200, f'{name} set failed: {r.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + assert go['initial_state'] is not None, f'{name} initial_state is None' + print(f'{name} initial state injected: sid={sid}') + + # --- 4. GUI-ready startup --- + launch_gui(f'libreoffice --calc "{OUTPUT}"', delay_sec=3.0) + launch_gui(f'google-chrome "{SF_URL}/?sid={sid}"', delay_sec=2.0) + launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=2.0) + print('GUI_READY: launched libreoffice calc + chrome (salesforce, slack) with DISPLAY=:0') + + +main() diff --git a/ar_payment_004/reward.py b/ar_payment_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..d8715b0f5916c2faf4d3d20135db833653167fae --- /dev/null +++ b/ar_payment_004/reward.py @@ -0,0 +1,227 @@ +""" +Reward Script: AR payment chain — mark INV-1045 Paid in local ledger, +log a payment-received activity on the Salesforce opportunity 'Initech CRM Rollout', +and notify AE Priya Nair in Slack #finance that it's settled. +Task ID: ar_payment_004 +Domain: libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack) + +Scoring (each component scores ONLY the task-introduced delta): + Component 1 — LOCAL LEDGER (0.34): INV-1045 Status -> 'Paid' AND no other row's + Status changed from its known baseline. + Component 2 — SALESFORCE (0.33): NEW activity (delta vs initial) on opp 'Initech + CRM Rollout' recording payment of $72,000 / INV-1045. + Component 3 — SLACK (0.33): NEW message (delta vs initial) in #finance addressed + to Priya Nair confirming $72,000 / INV-1045 settled. + +Total: 1.0. Fully deterministic; no LLM judge (no OpenAI creds in this env). +Runs on the VM: openpyxl for the local file, requests for the mock /go state. +""" +import sys +import re + +LEDGER_PATH = '/home/user/ar_payment_002.xlsx' +SHEET_NAME = 'AR Invoice Ledger' + +# Known baseline (initial) Status per invoice, from the task context. +# INV-1045 is the ONLY row that should change (Sent -> Paid). +BASELINE_STATUS = { + 'INV-1042': 'Paid', + 'INV-1043': 'Paid', + 'INV-1044': 'Sent', + 'INV-1045': 'Sent', # <- the row the agent must change to 'Paid' + 'INV-1046': 'Sent', + 'INV-1047': 'Paid', + 'INV-1048': 'Sent', + 'INV-1049': 'Paid', + 'INV-1050': 'Sent', + 'INV-1051': 'Overdue', +} + + +def norm(s): + """Lowercase, strip, drop commas/$/spaces around numbers for robust matching.""" + return str(s or '').lower() + + +def amount_present(text): + """True if text mentions 72000 / 72,000 / $72,000.""" + t = re.sub(r'[,\s$]', '', str(text or '')) + return '72000' in t + + +def verify_ledger(): + """Component 1 (0.34): INV-1045 -> Paid, identity intact, no other status changed.""" + try: + import openpyxl + except Exception as e: + print(f"ERROR: Component 1 — openpyxl import failed: {e}") + return 0.0 + try: + wb = openpyxl.load_workbook(LEDGER_PATH, data_only=True) + except Exception as e: + print(f"ERROR: Component 1 — cannot load ledger {LEDGER_PATH}: {e}") + return 0.0 + try: + if SHEET_NAME not in wb.sheetnames: + print(f"FAIL: Component 1 — sheet '{SHEET_NAME}' not found; sheets={wb.sheetnames}") + return 0.0 + ws = wb[SHEET_NAME] + + rows_by_inv = {} + for r in ws.iter_rows(min_row=2, values_only=True): + if r and r[0]: + rows_by_inv[str(r[0]).strip()] = r # A=Invoice#, B=Cust, C=Deal, D=Amt, ... G=Status, H=Owner + + # 1a: INV-1045 identity + Status == 'Paid' (the core change) + target = rows_by_inv.get('INV-1045') + if not target: + print("FAIL: Component 1 — INV-1045 row not found") + return 0.0 + cust = str(target[1]).strip() if target[1] else '' + deal = str(target[2]).strip() if target[2] else '' + amt = target[3] + status = str(target[6]).strip() if target[6] else '' + owner = str(target[7]).strip() if target[7] else '' + + identity_ok = (cust == 'Initech' and deal == 'Initech CRM Rollout' + and amt == 72000 and owner == 'Priya Nair') + if not identity_ok: + print(f"FAIL: Component 1 — INV-1045 identity mismatch " + f"(Customer={cust!r}, Deal={deal!r}, Amount={amt!r}, Owner={owner!r})") + return 0.0 + if status != 'Paid': + print(f"FAIL: Component 1 — INV-1045 Status is {status!r}, expected 'Paid'") + return 0.0 + + # 1b: no OTHER row's Status changed from its baseline + for inv, expected in BASELINE_STATUS.items(): + if inv == 'INV-1045': + continue + row = rows_by_inv.get(inv) + if not row: + print(f"FAIL: Component 1 — expected row {inv} missing") + return 0.0 + actual = str(row[6]).strip() if row[6] else '' + if actual != expected: + print(f"FAIL: Component 1 — {inv} Status changed to {actual!r}, " + f"expected unchanged {expected!r}") + return 0.0 + + print("PASS: Component 1 — INV-1045 marked 'Paid', identity intact, " + "no other row's status changed (0.34 pts)") + return 0.34 + except Exception as e: + print(f"ERROR: Component 1 — {e}") + return 0.0 + + +def verify_salesforce(sid): + """Component 2 (0.33): NEW payment activity on 'Initech CRM Rollout' opportunity.""" + import requests + try: + data = requests.get(f'http://28.7.184.198:8175/go?sid={sid}', timeout=20).json() + except Exception as e: + print(f"ERROR: Component 2 — cannot fetch salesforce state: {e}") + return 0.0 + try: + initial = data.get('initial_state') or {} + current = data.get('current_state') or {} + + # Resolve the Initech opportunity id from current state. + opp_id = None + for o in (current.get('opportunities') or []): + if str(o.get('name', '')).strip() == 'Initech CRM Rollout': + opp_id = o.get('opportunityId') + break + if not opp_id: + print("FAIL: Component 2 — opportunity 'Initech CRM Rollout' not found") + return 0.0 + + # DELTA: activities present now but not in initial. + init_ids = {a.get('activityId') for a in (initial.get('activities') or [])} + new_acts = [a for a in (current.get('activities') or []) + if a.get('activityId') not in init_ids] + if not new_acts: + print("FAIL: Component 2 — no new activity logged (delta empty)") + return 0.0 + + # A new activity must relate to the Initech opp AND record the payment. + for a in new_acts: + if a.get('relatedToId') != opp_id: + continue + blob = norm(a.get('subject', '')) + ' ' + norm(a.get('description', '')) + if 'inv-1045' in blob and amount_present(blob): + print(f"PASS: Component 2 — new payment activity {a.get('activityId')} on " + f"'Initech CRM Rollout' records INV-1045 / $72,000 (0.33 pts)") + return 0.33 + + print("FAIL: Component 2 — new activity exists but none on the Initech opp " + "mentions both INV-1045 and $72,000") + return 0.0 + except Exception as e: + print(f"ERROR: Component 2 — {e}") + return 0.0 + + +def verify_slack(sid): + """Component 3 (0.33): NEW #finance message to Priya Nair confirming settlement.""" + import requests + try: + data = requests.get(f'http://28.7.184.198:8178/go?sid={sid}', timeout=20).json() + except Exception as e: + print(f"ERROR: Component 3 — cannot fetch slack state: {e}") + return 0.0 + try: + initial = data.get('initial_state') or {} + current = data.get('current_state') or {} + + init_fin = (initial.get('messages') or {}).get('finance', []) + cur_fin = (current.get('messages') or {}).get('finance', []) + + # DELTA: messages beyond the initial #finance snapshot. + new_msgs = cur_fin[len(init_fin):] if len(cur_fin) > len(init_fin) else [] + if not new_msgs: + print("FAIL: Component 3 — no new message in #finance (delta empty)") + return 0.0 + + for m in new_msgs: + c = norm(m.get('content', '')) + addresses_priya = ('priya' in c) # @Priya Nair / Priya + confirms = ('inv-1045' in c and amount_present(c) + and ('settl' in c or 'paid' in c or 'received' in c)) + if addresses_priya and confirms: + print(f"PASS: Component 3 — new #finance message {m.get('messageId')} addresses " + f"Priya Nair and confirms INV-1045 / $72,000 settled (0.33 pts)") + return 0.33 + + print("FAIL: Component 3 — new #finance message(s) do not address Priya Nair " + "AND confirm INV-1045 / $72,000 settled") + return 0.0 + except Exception as e: + print(f"ERROR: Component 3 — {e}") + return 0.0 + + +def main(): + # sid for the mock surfaces (per-env) + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid empty') + except Exception as e: + print(f"CRITICAL: cannot read /tmp/task_web_sid: {e}") + print("REWARD: 0.0") + return + + total = 0.0 + total += verify_ledger() + total += verify_salesforce(sid) + total += verify_slack(sid) + + final = round(min(total, 1.0), 4) + print(f"\nScore: {total}/1.0") + print(f"REWARD: {final}") + + +main() diff --git a/ar_payment_004/reward_label.json b/ar_payment_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..e8d275dfaba83b7e199ca1d35222b79de1c92ae1 --- /dev/null +++ b/ar_payment_004/reward_label.json @@ -0,0 +1,63 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_payment_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:22:47", + "label": { + "task_id": "ar_payment_004", + "domain": "libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)", + "summary": "验证代理是否将本地 Excel 账本中 INV-1045 标记为 Paid、在 Salesforce 的 'Initech CRM Rollout' 机会上新增 $72,000 付款活动,并在 Slack #finance 频道向 Priya Nair 发送确认结清的消息。", + "is_placeholder": false, + "data_sources": [ + "/home/user/ar_payment_002.xlsx", + "/tmp/task_web_sid", + "salesforce_mock (http://28.7.186.212:8195/go)", + "slack_mock (http://28.7.186.212:8198/go)" + ], + "scoring_components": [ + { + "name": "Component 1 — LOCAL LEDGER", + "weight": 0.34, + "description": "检查本地 Excel 账本中 INV-1045 是否被正确标记为 Paid,且其他行状态未被篡改。", + "check_logic": "使用 openpyxl 加载 LEDGER_PATH 的 SHEET_NAME 工作表,遍历所有行建立 Invoice# 到行的映射。对 INV-1045 检查:Customer='Initech'、Deal='Initech CRM Rollout'、Amount=72000、Owner='Priya Nair'、Status='Paid'。对 BASELINE_STATUS 中其余发票检查:行必须存在且 Status 与基准值完全一致。", + "pass_condition": "INV-1045 的身份字段完全匹配且 Status 为 'Paid',其他所有发票行的 Status 与 BASELINE_STATUS 基准一致且无缺失。" + }, + { + "name": "Component 2 — SALESFORCE", + "weight": 0.33, + "description": "检查 Salesforce 中 'Initech CRM Rollout' 机会上是否新增了记录 INV-1045 / $72,000 付款的活动。", + "check_logic": "通过 requests GET 请求 salesforce_mock /go 端点,获取 initial_state 与 current_state。从 current_state.opportunities 中解析 name 为 'Initech CRM Rollout' 的 opportunityId。计算 activities 的 delta(current 中存在但 initial 中 activityId 不存在的记录)。在新增活动中查找 relatedToId 等于该 opp_id,且 subject 与 description 的归一化文本同时包含 'inv-1045' 和金额 72000 的记录。", + "pass_condition": "存在一条新增 activity,关联到 'Initech CRM Rollout' 机会,且其内容同时提及 INV-1045 和 $72,000。" + }, + { + "name": "Component 3 — SLACK", + "weight": 0.33, + "description": "检查 Slack #finance 频道是否新增了向 Priya Nair 确认 INV-1045 / $72,000 已结清的消息。", + "check_logic": "通过 requests GET 请求 slack_mock /go 端点,获取 initial_state 与 current_state。提取 #finance 频道的消息列表,取 delta(current 中超出 initial 长度的尾部消息)。在新增消息中查找归一化内容同时满足:包含 'priya'、包含 'inv-1045'、包含金额 72000、包含 'settl'/'paid'/'received' 之一。", + "pass_condition": "#finance 频道存在一条新增消息,内容同时提及 Priya Nair、INV-1045、$72,000 并使用确认结清的关键词。" + } + ], + "total_max_score": 1.0, + "score_aggregation": "三个组件得分直接相加,随后使用 min(total, 1.0) 钳制到上限 1.0,最后 round(..., 4) 得到最终 REWARD。", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:CRITICAL 提前退出,输出 REWARD: 0.0", + "openpyxl 导入失败:Component 1 返回 0.0", + "Excel 文件加载失败或工作表 'AR Invoice Ledger' 不存在:Component 1 返回 0.0", + "INV-1045 行缺失或身份字段(Customer/Deal/Amount/Owner)不匹配:Component 1 返回 0.0", + "INV-1045 Status 不是 'Paid':Component 1 返回 0.0", + "其他发票行缺失或 Status 偏离 BASELINE_STATUS:Component 1 返回 0.0", + "Salesforce mock 请求失败:Component 2 返回 0.0", + "未找到 'Initech CRM Rollout' 机会:Component 2 返回 0.0", + "activities delta 为空:Component 2 返回 0.0", + "新增 activity 未同时包含 INV-1045 和 $72,000:Component 2 返回 0.0", + "Slack mock 请求失败:Component 3 返回 0.0", + "#finance 无新增消息:Component 3 返回 0.0", + "新增消息未同时满足 Priya + INV-1045 + 金额 + 确认词:Component 3 返回 0.0", + "任何未捕获异常导致对应 Component 返回 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID。随后按顺序执行三个验证:1) verify_ledger() 使用 openpyxl 打开本地 Excel,确认 INV-1045 被改为 Paid 且身份正确,同时确保其他行状态与基准一致,通过得 0.34;2) verify_salesforce(sid) 请求 salesforce_mock,对比 initial 与 current state,在 'Initech CRM Rollout' 机会上查找新增且同时提及 INV-1045 和 $72,000 的 activity,通过得 0.33;3) verify_slack(sid) 请求 slack_mock,对比 #finance 消息增量,查找同时提及 Priya Nair、INV-1045、$72,000 及确认结清关键词的新消息,通过得 0.33。三个组件分数累加后,经 min(total, 1.0) 钳制并四舍五入到 4 位小数输出最终分数。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ar_payment_002(从 docstring 中明确提取)\n - Domain: libreoffice_calc + mock_websites (HYBRID)(从 docstring 中提取)\n\n2. **脚本功能概述**:\n 验证三个组件:\n - 本地账本(Excel):将 INV-1045 标记为 Paid,且不改变其他行\n - Salesforce:在 \"Initech CRM Rollout\" 机会上新增记录 $72,000 / INV-1045 的活动\n - Slack:在 #finance 频道向 Priya Nair 发送新消息确认 $72,000 / INV-1045 已结清\n\n3. **is_placeholder**:false,因为脚本有详细的验证逻辑。\n\n4. **data_sources**:\n - 本地文件:`/home/user/ar_payment_002.xlsx`(openpyxl 读取)\n - Salesforce mock:`http://28.7.186.212:8195/go?sid={sid}`(requests 获取)\n - Slack mock:`http://28.7.186.212:8198/go?sid={sid}`(requests 获取)\n - `/tmp/task_web_sid`(读取 sid)\n\n5. **scoring_components**:\n - Component 1:weight 0.34,验证本地账本\n - Component 2:weight 0.33,验证 Salesforce\n - Component 3:weight 0.33,验证 Slack\n\n6. **score_aggregation**:相加,然后 `min(total, 1.0)` 钳制到上限,再 round 到 4 位小数。\n\n7. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败会提前退出(CRITICAL)\n - openpyxl 导入失败\n - Excel 文件加载失败\n - 工作表未找到\n - INV-1045 行未找到\n - INV-1045 身份不匹配(Customer, Deal, Amount, Owner)\n - INV-1045 Status 不是 'Paid'\n - 其他行 Status 被改变或缺失\n - Salesforce mock 拉取失败\n - 未找到 \"Initech CRM Rollout\" 机会\n - 没有新活动(delta 为空)\n - 新活动未关联到正确机会或未提及 INV-1045 和金额\n - Slack mock 拉取失败\n - #finance 没有新消息\n - 新消息未同时满足:提及 Priya、包含 INV-1045、金额、确认词(settl/paid/received)\n\n8. **scoring_logic_explanation**:按执行顺序:\n - 从 /tmp/task_web_sid 读取 sid\n - Component 1:用 openpyxl 打开 Excel,检查 INV-1045 行身份(Customer=Initech, Deal=Initech CRM Rollout, Amount=72000, Owner=Priya Nair)且 Status='Paid';检查其他所有发票状态与 BASELINE_STATUS 一致未改变。通过得 0.34。\n - Component 2:用 sid 请求 Salesforce mock,对比 initial/current state,找到 \"Initech CRM Rollout\" 机会 ID,检查新增活动中是否有 relatedToId 匹配且 subject/description 同时包含 inv-1045 和 $72,000。通过得 0.33。\n - Component 3:用 sid 请求 Slack mock,对比 initial/current 的 #finance 消息,取增量消息,检查是否有消息同时满足:内容包含 \"priya\"、包含 \"inv-1045\"、包含金额 72000、包含 \"settl\"/\"paid\"/\"received\" 之一。通过得 0.33。\n - 汇总:三个组件分数相加,min(total, 1.0) 钳制,round(..., 4)。\n\n9. **confidence**:1.0,因为代码清晰完整。\n\n现在构建 JSON,确保:\n- 只输出 JSON,无 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- 不要臆测\n\n让我再检查一下 weight 字段。代码中显式给出:\n- Component 1: 0.34\n- Component 2: 0.33\n- Component 3: 0.33\n\ntotal_max_score: 1.0\n\n检查 pass_condition 和 check_logic 要准确:\n\nComponent 1:\n- check_logic: 使用 openpyxl 加载 /home/user/ar_payment_002.xlsx 的 'AR Invoice Ledger' 工作表,遍历所有行。检查 INV-1045 行的 Customer='Initech'、Deal='Initech CRM Rollout'、Amount=72000、Owner='Priya Nair' 且 Status='Paid';同时遍历 BASELINE_STATUS 中除 INV-1045 外的所有发票,确认其 Status 与基准值一致且行存在。\n- pass_condition: INV-1045 的身份字段完全匹配且 Status 为 'Paid',且其他所有发票行的 Status 与 BASELINE_STATUS 基准一致、无缺失。\n\nComponent 2:\n- check_logic: 通过 HTTP GET 请求 salesforce_mock 的 /go 端点获取 initial_state 和 current_state。从 current_state.opportunities 中找到 name 为 'Initech CRM Rollout' 的 opportunityId。计算 activities 的 delta(current 中存在但 initial 中 activityId 不存在的记录)。在新增活动中查找 relatedToId 等于该 opp_id 且 subject 与 description 的归一化文本同时包含 'inv-1045' 和金额 72000 的活动。\n- pass_condition: 存在一条新增 activity,其关联到 'Initech CRM Rollout' 机会,且内容同时提及 INV-1045 和 $72,000。\n\nComponent 3:\n- check_logic: 通过 HTTP GET 请求 slack_mock 的 /go 端点获取 initial_state 和 current_state。提取 #finance 频道的消息列表,计算 delta(current 中超出 initial 长度的尾部消息)。在新增消息中查找归一化内容同时满足:包含 'priya'、包含 'inv-1045'、包含金额 72000、包含 'settl'/'paid'/'received' 之一。\n- pass_condition: #finance 频道存在一条新增消息,内容同时提及 Priya Nair、INV-1045、$72,000 并使用确认结清的关键词。\n\nfailure_modes:\n- /tmp/task_web_sid 读取失败或为空:CRITICAL 提前退出,REWARD 0.0\n- openpyxl 导入失败:Component 1 返回 0.0\n- Excel 文件加载失败:Component 1 返回 0.0\n- 工作表 'AR Invoice Ledger' 不存在:Component 1 返回 0.0\n- INV-1045 行缺失:Component 1 返回 0.0\n- INV-1045 身份字段不匹配:Component 1 返回 0.0\n- INV-1045 Status 不是 'Paid':Component 1 返回 0.0\n- 其他发票行缺失或 Status 偏离基准:Component 1 返回 0.0\n- Salesforce mock 请求失败:Component 2 返回 0.0\n- 未找到 'Initech CRM Rollout' 机会:Component 2 返回 0.0\n- activities delta 为空:Component 2 返回 0.0\n- 新增 activity 未同时包含 INV-1045 和 $72,000:Component 2 返回 0.0\n- Slack mock 请求失败:Component 3 返回 0.0\n- #finance 无新增消息:Component 3 返回 0.0\n- 新增消息未同时满足 Priya + INV-1045 + 金额 + 确认词:Component 3 返回 0.0\n- 任何未捕获异常:对应 Component 返回 0.0\n\nscore_aggregation: 三个组件得分相加,使用 min(total, 1.0) 钳制上限,再 round(..., 4) 得到最终 REWARD。\n\nsummary: 验证代理是否将本地 Excel 账本中 INV-1045 标记为 Paid、在 Salesforce 机会上记录付款活动、并在 Slack #finance 通知 Priya Nair。\n\ndomain 应该是 \"libreoffice_calc + mock_websites\" 还是只取一个?docstring 中写的是 \"libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\"。按照要求,从 docstring 中提取的领域。我保留原样 \"libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\" 或者简化为 \"libreoffice_calc + mock_websites\"。看要求说 \"如 mock_websites / software_engineer / libreoffice_calc\"。这里 hybrid 比较特殊,我保留原文中的描述。\n\n等等,用户要求 \"domain\": \"从 docstring 中提取的领域\"。docstring 中明确写了 \"Domain: libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\"。我就用这个。\n\n现在确保 JSON 格式正确,没有多余内容。 {\"task_id\":\"ar_payment_002\",\"domain\":\"libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\",\"summary\":\"验证代理是否将本地 Excel 账本中 INV-1045 标记为 Paid、在 Salesforce 的 'Initech CRM Rollout' 机会上新增 $72,000 付款活动,并在 Slack #finance 频道向 Priya Nair 发送确认结清的消息。\",\"is_placeholder\":false,\"data_sources\":[\"/home/user/ar_payment_002.xlsx\",\"/tmp/task_web_sid\",\"salesforce_mock (http://28.7.186.212:8195/go)\",\"slack_mock (http://28.7.186.212:8198/go)\"],\"scoring_components\":[{\"name\":\"Component 1 — LOCAL LEDGER\",\"weight\":0.34,\"description\":\"检查本地 Excel 账本中 INV-1045 是否被正确标记为 Paid,且其他行状态未被篡改。\",\"check_logic\":\"使用 openpyxl 加载 LEDGER_PATH 的 SHEET_NAME 工作表,遍历所有行建立 Invoice# 到行的映射。对 INV-1045 检查:Customer='Initech'、Deal='Initech CRM Rollout'、Amount=72000、Owner='Priya Nair'、Status='Paid'。对 BASELINE_STATUS 中其余发票检查:行必须存在且 Status 与基准值完全一致。\",\"pass_condition\":\"INV-1045 的身份字段完全匹配且 Status 为 'Paid',其他所有发票行的 Status 与 BASELINE_STATUS 基准一致且无缺失。\"},{\"name\":\"Component 2 — SALESFORCE\",\"weight\":0.33,\"description\":\"检查 Salesforce 中 'Initech CRM Rollout' 机会上是否新增了记录 INV-1045 / $72,000 付款的活动。\",\"check_logic\":\"通过 requests GET 请求 salesforce_mock /go 端点,获取 initial_state 与 current_state。从 current_state.opportunities 中解析 name 为 'Initech CRM Rollout' 的 opportunityId。计算 activities 的 delta(current 中存在但 initial 中 activityId 不存在的记录)。在新增活动中查找 relatedToId 等于该 opp_id,且 subject 与 description 的归一化文本同时包含 'inv-1045' 和金额 72000 的记录。\",\"pass_condition\":\"存在一条新增 activity,关联到 'Initech CRM Rollout' 机会,且其内容同时提及 INV-1045 和 $72,000。\"},{\"name\":\"Component 3 — SLACK\",\"weight\":0.33,\"description\":\"检查 Slack #finance 频道是否新增了向 Priya Nair 确认 INV-1045 / $72,000 已结清的消息。\",\"check_logic\":\"通过 requests GET 请求 slack_mock /go 端点,获取 initial_state 与 current_state。提取 #finance 频道的消息列表,取 delta(current 中超出 initial 长度的尾部消息)。在新增消息中查找归一化内容同时满足:包含 'priya'、包含 'inv-1045'、包含金额 72000、包含 'settl'/'paid'/'received' 之一。\",\"pass_condition\":\"#finance 频道存在一条新增消息,内容同时提及 Priya Nair、INV-1045、$72,000 并使用确认结清的关键词。\"}],\"total_max_score\":1.0,\"score_aggregation\":\"三个组件得分直接相加,随后使用 min(total, 1.0) 钳制到上限 1.0,最后 round(..., 4) 得到最终 REWARD。\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:CRITICAL 提前退出,输出 REWARD: 0.0\",\"openpyxl 导入失败:Component 1 返回 0.0\",\"Excel 文件加载失败或工作表 'AR Invoice Ledger' 不存在:Component 1 返回 0.0\",\"INV-1045 行缺失或身份字段(Customer/Deal/Amount/Owner)不匹配:Component 1 返回 0.0\",\"INV-1045 Status 不是 'Paid':Component 1 返回 0.0\",\"其他发票行缺失或 Status 偏离 BASELINE_STATUS:Component 1 返回 0.0\",\"Salesforce mock 请求失败:Component 2 返回 0.0\",\"未找到 'Initech CRM Rollout' 机会:Component 2 返回 0.0\",\"activities delta 为空:Component 2 返回 0.0\",\"新增 activity 未同时包含 INV-1045 和 $72,000:Component 2 返回 0.0\",\"Slack mock 请求失败:Component 3 返回 0.0\",\"#finance 无新增消息:Component 3 返回 0.0\",\"新增消息未同时满足 Priya + INV-1045 + 金额 + 确认词:Component 3 返回 0.0\",\"任何未捕获异常导致对应 Component 返回 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID。随后按顺序执行三个验证:1) verify_ledger() 使用 openpyxl 打开本地 Excel,确认 INV-1045 被改为 Paid 且身份正确,同时确保其他行状态与基准一致,通过得 0.34;2) verify_salesforce(sid) 请求 salesforce_mock,对比 initial 与 current state,在 'Initech CRM Rollout' 机会上查找新增且同时提及 INV-1045 和 $72,000 的 activity,通过得 0.33;3) verify_slack(sid) 请求 slack_mock,对比 #finance 消息增量,查找同时提及 Priya Nair、INV-1045、$72,000 及确认结清关键词的新消息,通过得 0.33。三个组件分数累加后,经 min(total, 1.0) 钳制并四舍五入到 4 位小数输出最终分数。\",\"confidence\":1.0}" +} diff --git a/ar_payment_alert_010__long/_cua_gym_vm_bridge.sh b/ar_payment_alert_010__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_payment_alert_010__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/ar_payment_alert_010__long/initial_setup.py b/ar_payment_alert_010__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..04b94b98d92faed60e956748e9e4b1e2e5405fc6 --- /dev/null +++ b/ar_payment_alert_010__long/initial_setup.py @@ -0,0 +1,969 @@ +""" +Initial Setup: Clear the overnight payment-alert inbox +Task ID: ar_payment_alert_010__long +Mocks: stripe_dashboard_mock (8179), quickbooks_mock (8172), + gmail_mock (8138), slack_mock (8178) + +Scenario (multi-branch finance-ops, "today" = 2026-06-29) +--------------------------------------------------------- +A finance-ops analyst clears the overnight PAYMENT-ALERT inbox in Gmail. Each +alert email (from the billing system) flags one payment event and names the +customer + amount (+ invoice # where relevant). For every alert the analyst +derives the corrective action from the alert TYPE, carries the customer / amount +/ invoice into Stripe or QuickBooks, performs the (hidden) control there, labels +the alert with a status label, replies to the customer, then posts + pins a +one-line summary to Slack #billing-ops. + +Branch rule (stated in the instruction; VERIFIED against current app state): + * Duplicate charge -> REFUND the matching Stripe payment + (skip if that payment is already refunded). + * Chargeback opened -> SUBMIT EVIDENCE on the matching Stripe dispute + (skip if its status is not 'needs_response'). + * Payment received -> RECEIVE PAYMENT on the matching QuickBooks invoice + (skip if the invoice is already Paid). + * Under investigation -> LEAVE (pending — must NOT act; tempting distractor). + * Alert whose customer/invoice has no matching Stripe/QB record -> SKIP. + +Alert plan (10 emails) => 6 require action, 4 must be skipped: + 2 REFUND (Duplicate charge), 2 SUBMIT_EVIDENCE (Chargeback opened), + 2 RECEIVE_PAYMENT (Payment received), 2 LEAVE (Under investigation), + 1 already-refunded 'Duplicate charge' (arms the refund skip guard), + 1 no-match 'Payment received' (unresolvable distractor). + +Cross-app data flow (H3): + Customer + Amount read in the Gmail alert -> locate the matching Stripe payment + (customer_name + amount in cents) to refund, and the matching Stripe dispute + (by customer / charge) to submit evidence on. Invoice # in the alert -> matching + QuickBooks invoice number to receive payment on. Customer email (from the + matched Stripe payment / QB customer) -> the To of the Gmail reply. + +Ground-truth embedding (Rule 2), PRECOMPUTED in Python from the visible alert +type + VERIFIED against the injected Stripe/QB records so visible <=> key can +never disagree: + * gmail.initial_state.emails[*]._alert -> per-alert worklist (inline hidden key) + * slack.initial_state._task_adapter.summary_channel = 'billing-ops' + +Observable result kept ABSENT at injection (Rule 3): + * the 2 REFUND-target payments: amount_refunded=0, refunded=False; refunds[] + holds only a decoy that does NOT reference any target. + * the 2 SUBMIT_EVIDENCE-target disputes: status='needs_response'. + * the 2 RECEIVE_PAYMENT-target QB invoices: status Sent/Overdue, paidAmount=0, + paidDate=None. + * every Gmail alert email: labels=[]; no 'sent'-folder reply to a target customer. + * Slack #billing-ops starts EMPTY (no messages, nothing pinned). + * the already-done distractor payment IS already refunded (must be left alone); + the LEAVE-row dispute IS 'needs_response' (must be left alone). + +NOTE: Stripe amounts are in CENTS, QuickBooks amounts are in DOLLARS. +""" +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 = 'c4b39a92-99cd-45d5-9e0c-a08817d82cb8' +TODAY = _dt.date(2026, 6, 29) +SUMMARY_CHANNEL = 'billing-ops' + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- +def _ts(date_str): + """Unix seconds for date_str at 12:00 UTC (stable displayed date across TZs).""" + d = _dt.datetime.strptime(date_str, '%Y-%m-%d').replace( + hour=12, minute=0, second=0, microsecond=0, tzinfo=_dt.timezone.utc + ) + return int(d.timestamp()) + + +_CREATED = _ts('2026-01-08') +_NOW_TS = _ts('2026-06-29') + + +# =========================================================================== +# 1) STRIPE — payments + disputes (+ customers, refunds) +# =========================================================================== +# Shared customer registry: name -> (stripe_customer_id, email, card) +_STRIPE_CUSTS = { + 'Acme Corporation': ('cus_acme00000001', 'billing@acmecorp.com', {'brand': 'visa', 'last4': '4242', 'exp_month': 12, 'exp_year': 2027}), + 'Globex Industries': ('cus_globex0000012', 'ap@globexind.com', {'brand': 'mastercard', 'last4': '5555', 'exp_month': 8, 'exp_year': 2028}), + 'TechStart Inc.': ('cus_techstart0001', 'finance@techstart.io', {'brand': 'visa', 'last4': '1234', 'exp_month': 3, 'exp_year': 2027}), + 'Riverside Medical Group': ('cus_riverside0001', 'it@riversidemedical.org', {'brand': 'visa', 'last4': '8888', 'exp_month': 1, 'exp_year': 2028}), + 'CloudSync Pro': ('cus_cloudsync0001', 'billing@cloudsyncpro.com', {'brand': 'visa', 'last4': '6543', 'exp_month': 10, 'exp_year': 2028}), + 'DataVault Systems': ('cus_datavault0001', 'procurement@datavault.io', {'brand': 'amex', 'last4': '0001', 'exp_month': 6, 'exp_year': 2028}), + 'Pioneer Labs': ('cus_pioneer000001', 'admin@pioneerlabs.io', {'brand': 'visa', 'last4': '7777', 'exp_month': 12, 'exp_year': 2027}), + 'Northwind Traders': ('cus_northwind0001', 'ap@northwindtraders.com', {'brand': 'mastercard', 'last4': '2323', 'exp_month': 5, 'exp_year': 2027}), + 'Summit Retail': ('cus_summit0000001', 'billing@summitretail.com', {'brand': 'visa', 'last4': '9090', 'exp_month': 9, 'exp_year': 2028}), +} + + +def _stripe_customer(name): + cid, email, _card = _STRIPE_CUSTS[name] + return { + 'id': cid, 'name': name, 'email': email, 'phone': None, 'description': None, + 'address': {'line1': '200 Market St', 'line2': None, 'city': 'San Francisco', + 'state': 'CA', 'postal_code': '94105', 'country': 'US'}, + 'balance': 0, 'currency': 'usd', 'default_payment_method': None, + 'metadata': {}, 'created': _CREATED, 'livemode': True, 'delinquent': False, + 'total_spent': 0, 'payments_count': 1, + } + + +def _payment(pid, cust_name, amount_cents, date_str, description, + refunded=False, disputed=False, status='succeeded'): + cid, email, card = _STRIPE_CUSTS[cust_name] + captured = (status == 'succeeded') + return { + 'id': pid, + 'amount': amount_cents, + 'currency': 'usd', + 'status': status, + 'description': description, + 'customer': cid, + 'customer_email': email, + 'customer_name': cust_name, + 'payment_method': {'type': 'card', 'card': dict(card, funding='credit')}, + 'amount_received': amount_cents if captured else 0, + 'amount_refunded': amount_cents if refunded else 0, + 'refunded': bool(refunded), + 'disputed': bool(disputed), + 'captured': captured, + 'receipt_email': email, + 'receipt_url': None, + 'metadata': {}, + 'created': _ts(date_str), + 'livemode': True, + 'risk_score': 12, + 'risk_level': 'normal', + 'outcome': {'type': 'authorized' if captured else 'pending', + 'risk_level': 'normal', 'risk_score': 12, 'reason': None}, + 'invoice': None, + } + + +# Payments: 2 refund targets + 1 already-refunded distractor + 1 LEAVE bait +# (DataVault, refunding it = FALSE POSITIVE) + 3 disputed charges (backing the +# disputes) + 2 watermark decoys (backing the decoy disputes). +_STRIPE_PAYMENTS = [ + # --- REFUND targets (Duplicate charge) — ABSENT result: refunded=False --- + _payment('pi_refund_acme_0001', 'Acme Corporation', 25000, '2026-06-27', + 'Pro Plan - Monthly (duplicate charge)', refunded=False), # $250.00 + _payment('pi_refund_globex_0002', 'Globex Industries', 9999, '2026-06-28', + 'Starter Plan - Monthly (duplicate charge)', refunded=False), # $99.99 + + # --- already-refunded distractor (Pioneer): must be LEFT alone --- + _payment('pi_already_pioneer_09', 'Pioneer Labs', 4999, '2026-06-20', + 'API Access Add-on (already refunded)', refunded=True), # $49.99 + + # --- LEAVE-row bait (DataVault 'Under investigation'): refunding = leak/FP --- + _payment('pi_leave_datavault_08', 'DataVault Systems', 18000, '2026-06-26', + 'Team Plan - Monthly', refunded=False), # $180.00 + + # --- disputed charges backing the SUBMIT_EVIDENCE targets + LEAVE dispute --- + _payment('pi_disp_techstart_01', 'TechStart Inc.', 12000, '2026-06-10', + 'Team Plan - Monthly', disputed=True), # $120.00 + _payment('pi_disp_riverside_01', 'Riverside Medical Group', 45000, '2026-06-08', + 'Clinic Suite - Monthly', disputed=True), # $450.00 + _payment('pi_disp_cloudsync_01', 'CloudSync Pro', 48000, '2026-06-12', + 'CloudSync Platform - Monthly', disputed=True), # $480.00 + + # --- watermark decoys (backing the decoy disputes; NOT named by any alert) --- + _payment('pi_decoy_north_0011', 'Northwind Traders', 12000, '2026-06-12', + 'Pro Plan Upgrade - Monthly', disputed=True), + _payment('pi_decoy_summit_0012', 'Summit Retail', 30000, '2026-06-14', + 'Enterprise Annual - Prepaid', disputed=True), +] + + +def _dispute(dispute_id, cust_name, charge_id, amount_cents, reason, status, + due_date='2026-07-06'): + cid, _email, _card = _STRIPE_CUSTS[cust_name] + return { + 'id': dispute_id, + 'amount': amount_cents, + 'currency': 'usd', + 'charge': charge_id, + 'customer': cid, + 'customer_name': cust_name, + 'reason': reason, + 'status': status, + 'evidence_due_by': _ts(due_date), + 'created': _ts('2026-06-15'), + 'metadata': {}, + } + + +# Disputes: 2 SUBMIT_EVIDENCE targets (needs_response) + 1 LEAVE bait +# (CloudSync needs_response; responding = FALSE POSITIVE) + 2 decoys already +# past needs_response (under_review / won — excluded from the diff). +_STRIPE_DISPUTES = [ + # --- SUBMIT_EVIDENCE targets — ABSENT result: status stays 'needs_response' --- + _dispute('dp_techstart_0001', 'TechStart Inc.', 'pi_disp_techstart_01', + 12000, 'fraudulent', 'needs_response'), + _dispute('dp_riverside_0001', 'Riverside Medical Group', 'pi_disp_riverside_01', + 45000, 'product_not_received', 'needs_response'), + + # --- LEAVE-row bait (CloudSync 'Under investigation'): responding = leak/FP --- + _dispute('dp_cloudsync_0001', 'CloudSync Pro', 'pi_disp_cloudsync_01', + 48000, 'unrecognized', 'needs_response'), + + # --- watermark decoys (already past needs_response; never enter the diff) --- + _dispute('dp_decoy_north_001', 'Northwind Traders', 'pi_decoy_north_0011', + 12000, 'duplicate', 'under_review'), + _dispute('dp_decoy_summit_01', 'Summit Retail', 'pi_decoy_summit_0012', + 30000, 'fraudulent', 'won'), +] + +_STRIPE_CUSTOMERS = [_stripe_customer(nm) for nm in _STRIPE_CUSTS] + +# Decoy refund that references a NON-target payment (watermark; not the targets). +_STRIPE_REFUNDS = [ + {'id': 're_decoy_pioneer_01', 'amount': 4999, 'currency': 'usd', + 'charge': 'pi_already_pioneer_09', 'reason': 'duplicate', 'status': 'succeeded', + 'created': _ts('2026-06-21'), 'metadata': {}}, +] + +_STRIPE_STATE = { + 'business': { + 'name': 'Northwind SaaS', 'email': 'admin@northwind-saas.com', + 'url': 'https://northwind-saas.com', 'support_email': 'support@northwind-saas.com', + 'country': 'US', 'currency': 'usd', 'timezone': 'America/Los_Angeles', + }, + 'currentUser': {'id': 'user_admin', 'name': 'Finance Admin', + 'email': 'admin@northwind-saas.com', 'role': 'administrator', 'avatar': None}, + 'balance': {'available': 8421500, 'pending': 1530000, 'reserved': 0, 'currency': 'usd'}, + 'customers': _STRIPE_CUSTOMERS, + 'payments': _STRIPE_PAYMENTS, + 'products': [], + 'prices': [], + 'invoices': [], + 'subscriptions': [], + 'payouts': [], + 'disputes': _STRIPE_DISPUTES, + 'refunds': _STRIPE_REFUNDS, # decoy only; NONE references a refund target (Rule 3) + 'balanceTransactions': [], + 'events': [], + 'paymentMethods': [], + 'testMode': False, + 'searchQuery': '', + 'selectedDateRange': '30d', + 'metrics': { + 'today': {'grossVolume': 0, 'grossVolumeChart': []}, + 'summary': { + 'grossVolume': {'amount': 100097, 'change': 0, 'previousAmount': 0}, + 'netVolume': {'amount': 97000, 'change': 0, 'previousAmount': 0}, + 'disputeActivity': {'rate': 0, 'change': 0, 'previousRate': 0}, + }, + 'chartData': {'grossVolume': [], 'netVolume': [], 'disputeRate': []}, + }, +} + + +# =========================================================================== +# 2) QUICKBOOKS — invoices (+ customers). Amounts in DOLLARS. +# =========================================================================== +_QB_CUSTOMERS = [ + {'id': 'c1', 'name': 'Dev Solutions LLC', 'company': 'Dev Solutions LLC', 'email': 'accounts@devsolutions.co', 'phone': '(555) 100-2001'}, + {'id': 'c2', 'name': 'BrightPath Education', 'company': 'BrightPath Education', 'email': 'admin@brightpath.edu', 'phone': '(555) 100-2002'}, + {'id': 'c3', 'name': 'Summit Retail', 'company': 'Summit Retail', 'email': 'billing@summitretail.com', 'phone': '(555) 100-2003'}, + {'id': 'c4', 'name': 'Harbor Logistics', 'company': 'Harbor Logistics', 'email': 'ap@harborlogistics.com', 'phone': '(555) 100-2004'}, +] +for _c in _QB_CUSTOMERS: + _c.setdefault('address', '100 Market St, San Francisco, CA 94105') + _c.setdefault('balance', 0) + _c.setdefault('notes', '') + _c.setdefault('isActive', True) + _c.setdefault('createdAt', '2026-01-08') + + +def _qb_invoice(inv_id, number, customer_id, due_date, total, status): + inv_date = (_dt.date.fromisoformat(due_date) - _dt.timedelta(days=30)).isoformat() + paid = (status == 'Paid') + return { + 'id': inv_id, + 'number': number, + 'customerId': customer_id, + 'date': inv_date, + 'dueDate': due_date, + 'items': [{'id': f'{inv_id}_li1', 'productId': 'p1', + 'description': 'Professional services', 'qty': 1, + 'rate': total, 'amount': total}], + 'subtotal': total, + 'tax': 0, + 'total': total, + 'status': status, + 'paidAmount': total if paid else 0, + 'paidDate': inv_date if paid else None, + 'terms': 'Net 30', + 'message': '', + 'createdAt': f'{inv_date}T09:00:00Z', + } + + +# Invoices: 2 receive-payment targets (Sent/Overdue) + 1 unpaid decoy (receiving +# payment on it = FALSE POSITIVE) + 2 already-Paid decoys + 1 Draft decoy. +_QB_INVOICES = [ + # --- RECEIVE_PAYMENT targets — ABSENT: not Paid, paidAmount=0 --- + _qb_invoice('inv_dev_1042', '1042', 'c1', '2026-06-10', 1800.00, 'Sent'), # target + _qb_invoice('inv_bright_1057', '1057', 'c2', '2026-05-20', 3200.00, 'Overdue'), # target + + # --- leak bait: an unpaid invoice NOT referenced by any alert --- + _qb_invoice('inv_summit_1099', '1099', 'c3', '2026-06-15', 500.00, 'Sent'), # receiving = FP + + # --- watermark decoys (already Paid / Draft) --- + _qb_invoice('inv_paid_1001', '1001', 'c4', '2026-05-01', 2200.00, 'Paid'), + _qb_invoice('inv_paid_1002', '1002', 'c1', '2026-04-25', 9900.00, 'Paid'), + _qb_invoice('inv_draft_1100', '1100', 'c4', '2026-06-25', 1750.00, 'Draft'), +] + +_QB_STATE = { + 'company': { + 'name': 'Northwind SaaS', 'address': '123 Business Rd, San Francisco, CA 94105', + 'email': 'admin@northwind-saas.com', 'industry': 'Technology Services', + 'accountingMethod': 'Accrual', + }, + 'customers': _QB_CUSTOMERS, + 'invoices': _QB_INVOICES, +} + + +# =========================================================================== +# 3) THE ALERT WORKLIST + PRECOMPUTED ANSWER KEY (single source of truth) +# =========================================================================== +# Index injected records so the key can point at real ids + verify pre-state. +_PAY_BY_ID = {p['id']: p for p in _STRIPE_PAYMENTS} +_DISP_BY_ID = {d['id']: d for d in _STRIPE_DISPUTES} +_INV_BY_ID = {i['id']: i for i in _QB_INVOICES} +_QB_CUST_BY_ID = {c['id']: c for c in _QB_CUSTOMERS} + +# Status label per action, matched by NAME. +_LABEL_FOR_ACTION = { + 'refund': 'Refunded', + 'submit_evidence': 'Disputed', + 'receive_payment': 'Reconciled', +} + +# Each alert references its target record id (or None for the no-match row). +_ALERT_SPECS = [ + # --- REFUND (Duplicate charge) --- + dict(eid='m01', customer='Acme Corporation', alert_type='Duplicate charge', + amount_display='$250.00', invoice_num='', + stripe_payment_id='pi_refund_acme_0001', stripe_dispute_id=None, qb_invoice_id=None), + dict(eid='m02', customer='Globex Industries', alert_type='Duplicate charge', + amount_display='$99.99', invoice_num='', + stripe_payment_id='pi_refund_globex_0002', stripe_dispute_id=None, qb_invoice_id=None), + # --- SUBMIT_EVIDENCE (Chargeback opened) --- + dict(eid='m03', customer='TechStart Inc.', alert_type='Chargeback opened', + amount_display='$120.00', invoice_num='', + stripe_payment_id=None, stripe_dispute_id='dp_techstart_0001', qb_invoice_id=None), + dict(eid='m04', customer='Riverside Medical Group', alert_type='Chargeback opened', + amount_display='$450.00', invoice_num='', + stripe_payment_id=None, stripe_dispute_id='dp_riverside_0001', qb_invoice_id=None), + # --- RECEIVE_PAYMENT (Payment received) --- + dict(eid='m05', customer='Dev Solutions LLC', alert_type='Payment received', + amount_display='$1,800.00', invoice_num='1042', + stripe_payment_id=None, stripe_dispute_id=None, qb_invoice_id='inv_dev_1042'), + dict(eid='m06', customer='BrightPath Education', alert_type='Payment received', + amount_display='$3,200.00', invoice_num='1057', + stripe_payment_id=None, stripe_dispute_id=None, qb_invoice_id='inv_bright_1057'), + # --- LEAVE (Under investigation) — tempting distractors --- + dict(eid='m07', customer='DataVault Systems', alert_type='Under investigation', + amount_display='$180.00', invoice_num='', + stripe_payment_id='pi_leave_datavault_08', stripe_dispute_id=None, qb_invoice_id=None), + dict(eid='m08', customer='CloudSync Pro', alert_type='Under investigation', + amount_display='$480.00', invoice_num='', + stripe_payment_id=None, stripe_dispute_id='dp_cloudsync_0001', qb_invoice_id=None), + # --- already-refunded 'Duplicate charge' -> must be SKIPPED --- + dict(eid='m09', customer='Pioneer Labs', alert_type='Duplicate charge', + amount_display='$49.99', invoice_num='', + stripe_payment_id='pi_already_pioneer_09', stripe_dispute_id=None, qb_invoice_id=None), + # --- no matching Stripe/QB record -> SKIP --- + dict(eid='m10', customer='Zenith Partners', alert_type='Payment received', + amount_display='$750.00', invoice_num='9999', + stripe_payment_id=None, stripe_dispute_id=None, qb_invoice_id=None), +] + + +def _decide(spec): + """Derive (action, requires_action) from the alert TYPE, VERIFIED against the + current injected state. Precomputed so the visible alert <=> key can't drift.""" + t = norm(spec['alert_type']) + + if t == 'duplicate charge': + pid = spec['stripe_payment_id'] + pay = _PAY_BY_ID.get(pid) if pid else None + if pay is None: + return 'skip', False + already = bool(pay.get('refunded')) or ( + pay.get('amount', 0) > 0 and pay.get('amount_refunded', 0) >= pay.get('amount', 0)) + return 'refund', (not already) + + if t == 'chargeback opened': + did = spec['stripe_dispute_id'] + disp = _DISP_BY_ID.get(did) if did else None + if disp is None: + return 'skip', False + already = norm(disp.get('status')) != 'needs_response' + return 'submit_evidence', (not already) + + if t == 'payment received': + iid = spec['qb_invoice_id'] + inv = _INV_BY_ID.get(iid) if iid else None + if inv is None: + return 'skip', False + already = (norm(inv.get('status')) == 'paid') + return 'receive_payment', (not already) + + # 'Under investigation' (and anything else) -> LEAVE + return 'leave', False + + +def _customer_email(spec, action): + """Cross-app carry: the reply-To is read from the matched Stripe payment / + dispute customer (refund / submit_evidence) or the QB customer (receive).""" + if action == 'refund': + pay = _PAY_BY_ID.get(spec['stripe_payment_id']) + return pay.get('customer_email') if pay else None + if action == 'submit_evidence': + disp = _DISP_BY_ID.get(spec['stripe_dispute_id']) + if disp: + _cid, email, _card = _STRIPE_CUSTS.get(disp.get('customer_name'), (None, None, None)) + return email + return None + if action == 'receive_payment': + inv = _INV_BY_ID.get(spec['qb_invoice_id']) + cust = _QB_CUST_BY_ID.get(inv.get('customerId')) if inv else None + return cust.get('email') if cust else None + return None + + +ALERT_SUBJECTS = { + 'Duplicate charge': lambda s: f"Payment alert: Duplicate charge flagged for {s['customer']} ({s['amount_display']})", + 'Chargeback opened': lambda s: f"Payment alert: Chargeback opened by {s['customer']} ({s['amount_display']})", + 'Payment received': lambda s: f"Payment alert: Payment received from {s['customer']} — invoice #{s['invoice_num']} ({s['amount_display']})", + 'Under investigation': lambda s: f"Payment alert: {s['customer']} account under investigation ({s['amount_display']})", +} + + +def _alert_body(spec, action, customer_email): + lines = [ + f"Automated billing alert ({spec['alert_type']}).", + f"Customer: {spec['customer']}", + f"Amount: {spec['amount_display']}", + ] + if spec['invoice_num']: + lines.append(f"Invoice #: {spec['invoice_num']}") + if customer_email: + lines.append(f"Customer contact: {customer_email}") + lines.append("Review this event and take the corrective action its type calls for.") + return '\n'.join(lines) + + +GMAIL_USER = { + 'userId': 'u1', + 'username': 'Finance Ops', + 'email': 'billing-ops@northwind-saas.com', + 'avatar': 'https://picsum.photos/200/200?random=1', +} +BILLING_BOT = {'name': 'Billing System', 'email': 'billing-bot@northwind-saas.com', 'avatar': ''} + + +emails = [] +expected = [] +for idx, spec in enumerate(_ALERT_SPECS): + action, requires_action = _decide(spec) + customer_email = _customer_email(spec, action) + subject = ALERT_SUBJECTS[spec['alert_type']](spec) + + refund_amount_cents = None + if action == 'refund' and spec['stripe_payment_id']: + refund_amount_cents = _PAY_BY_ID[spec['stripe_payment_id']].get('amount') + qb_invoice_number = None + if action == 'receive_payment' and spec['qb_invoice_id'] in _INV_BY_ID: + qb_invoice_number = _INV_BY_ID[spec['qb_invoice_id']].get('number') + label_name = _LABEL_FOR_ACTION.get(action) if requires_action else None + + # ---- inline hidden answer key (reward reads emails[*]._alert) ---- + _alert = { + 'type': spec['alert_type'], + 'action': action, + 'requires_action': bool(requires_action), + 'customer': spec['customer'], + 'customer_email': customer_email if requires_action else None, + 'stripe_payment_id': spec['stripe_payment_id'] if action == 'refund' else None, + 'refund_amount_cents': refund_amount_cents, + 'stripe_dispute_id': spec['stripe_dispute_id'] if action == 'submit_evidence' else None, + 'qb_invoice_id': spec['qb_invoice_id'] if action == 'receive_payment' else None, + 'qb_invoice_number': qb_invoice_number, + 'label_name': label_name, + 'reply_subject': f'Re: {subject}' if requires_action else None, + } + + minutes_ago = 60 * (len(_ALERT_SPECS) - idx) # spread overnight, all before today + ts_dt = _dt.datetime(2026, 6, 29, 6, 0, tzinfo=_dt.timezone.utc) - _dt.timedelta(minutes=minutes_ago) + body = _alert_body(spec, action, customer_email) + emails.append({ + 'id': spec['eid'], + 'threadId': f"thread_{spec['eid']}", + 'from': dict(BILLING_BOT), + 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}], + 'cc': [], 'bcc': [], + 'folder': 'inbox', + 'subject': subject, + 'body': body, + 'snippet': body[:120], + 'timestamp': ts_dt.strftime('%Y-%m-%dT%H:%M:%SZ'), + 'read': False, 'starred': False, 'important': False, + 'labels': [], # Rule 3: no status label yet + 'category': 'primary', + 'attachments': [], + '_alert': _alert, # inline hidden answer key + }) + + expected.append({'eid': spec['eid'], **_alert}) + + +# ---- resolved partitions (for asserts + the DEBUG line) ---- +refund_rows = [e for e in expected if e['action'] == 'refund' and e['requires_action']] +dispute_rows = [e for e in expected if e['action'] == 'submit_evidence' and e['requires_action']] +receive_rows = [e for e in expected if e['action'] == 'receive_payment' and e['requires_action']] +leave_rows = [e for e in expected if e['action'] == 'leave'] +refund_done = [e for e in expected if e['action'] == 'refund' and not e['requires_action']] +skip_rows = [e for e in expected if e['action'] == 'skip'] +requires_rows = [e for e in expected if e['requires_action']] +resolved_count = len(requires_rows) + + +# --------------------------------------------------------------------------- +# Build-time asserts — pin the partition sizes + Rule-3 absences. +# --------------------------------------------------------------------------- +assert len(_ALERT_SPECS) == 10, len(_ALERT_SPECS) +assert len(refund_rows) == 2, refund_rows # 2 REFUND require action +assert len(dispute_rows) == 2, dispute_rows # 2 SUBMIT_EVIDENCE require action +assert len(receive_rows) == 2, receive_rows # 2 RECEIVE_PAYMENT require action +assert len(leave_rows) == 2, leave_rows # 2 LEAVE (Under investigation) +assert len(refund_done) == 1, refund_done # 1 already-refunded distractor +assert len(skip_rows) == 1, skip_rows # 1 no-match +assert resolved_count == 6, resolved_count # 6 require action +assert (len(leave_rows) + len(refund_done) + len(skip_rows)) == 4 # 4 must be skipped + +# every require-action alert carries a status label + reply target + customer email +for e in requires_rows: + assert e['label_name'] in ('Refunded', 'Disputed', 'Reconciled'), e + assert e['customer_email'], e + assert e['reply_subject'] and e['reply_subject'].startswith('Re: '), e + +# Rule 3: refund targets NOT yet refunded. +for e in refund_rows: + p = _PAY_BY_ID[e['stripe_payment_id']] + assert p['refunded'] is False and p['amount_refunded'] == 0, p['id'] +# Rule 3: the already-done distractor IS refunded (must be left alone). +_pioneer = _PAY_BY_ID['pi_already_pioneer_09'] +assert _pioneer['refunded'] is True and _pioneer['amount_refunded'] == _pioneer['amount'] +# Rule 3: submit-evidence targets are 'needs_response' at injection. +for e in dispute_rows: + d = _DISP_BY_ID[e['stripe_dispute_id']] + assert norm(d['status']) == 'needs_response', d['id'] +# Rule 3: the LEAVE-row dispute IS 'needs_response' (bait — must be left alone). +assert norm(_DISP_BY_ID['dp_cloudsync_0001']['status']) == 'needs_response' +# Rule 3: receive targets NOT yet Paid. +for e in receive_rows: + inv = _INV_BY_ID[e['qb_invoice_id']] + assert norm(inv['status']) in ('sent', 'overdue'), inv['status'] + assert inv['paidAmount'] == 0 and inv['paidDate'] is None, inv['id'] +# Rule 3: NO refund references any refund target. +_target_pay_ids = {e['stripe_payment_id'] for e in refund_rows} +assert all(r['charge'] not in _target_pay_ids for r in _STRIPE_REFUNDS) +# Rule 3: every alert email ships with no status label. +assert all(em['labels'] == [] for em in emails) + +print(f'Precomputed worklist: refund={len(refund_rows)} submit_evidence={len(dispute_rows)} ' + f'receive_payment={len(receive_rows)} leave={len(leave_rows)} ' + f'already_refunded={len(refund_done)} no_match={len(skip_rows)} ' + f'-> requires_action={resolved_count}, skipped={10 - resolved_count}') + + +# =========================================================================== +# 4) GMAIL — the alert inbox. Status labels seeded by NAME (Rule 3: unused). +# =========================================================================== +GMAIL_LABELS = [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'l4', 'name': 'Finance', 'color': '#eab308'}, + # status labels the SELECTION-GATED Label button applies (matched by NAME) --- + {'id': 'lbl-refunded', 'name': 'Refunded', 'color': '#22c55e'}, + {'id': 'lbl-disputed', 'name': 'Disputed', 'color': '#eb5a46'}, + {'id': 'lbl-reconciled', 'name': 'Reconciled', 'color': '#0ea5e9'}, +] + +_GMAIL_STATE = { + 'user': GMAIL_USER, + 'emails': emails, + 'labels': GMAIL_LABELS, + 'drafts': [], + 'settings': {'density': 'default', 'undoSend': 10}, + 'today': '2026-06-29', + '_task_adapter': { + 'task_id': TASK_ID, + 'variant': 'eval', + 'resolved_count': resolved_count, + }, +} + + +# =========================================================================== +# 5) SLACK — #billing-ops starts EMPTY (Rule 3); decoy chatter elsewhere. +# =========================================================================== +_SLACK_STATE = { + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', + 'topic': 'Welcome to Northwind SaaS!', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'billing-ops', 'name': 'billing-ops', + 'description': 'Billing operations — payment alerts and reconciliation', + 'topic': 'Post a summary when you finish clearing the payment-alert inbox', 'isPrivate': False, + 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1', + 'createdAt': '2026-06-01T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana', + 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + 'users': [ + {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana', + 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya', + 'email': 'maya.lindqvist@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Controller', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'Europe/Stockholm'}, + ], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind SaaS', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', + 'content': 'Morning all — overnight payment alerts are in the finance inbox.', + 'timestamp': '2026-06-29T13:02:00Z', 'reactions': [], 'isEdited': False, + 'threadId': None, 'attachments': []}, + ], + # #billing-ops starts EMPTY — the gradable post + pin are the agent's work. + 'billing-ops': [], + }, + '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, # agent posts + pins here (empty at injection) + 'resolved_count': resolved_count, + }, +} + +# Rule 3 guard: #billing-ops has no messages and nothing pinned at injection. +_bo = next(c for c in _SLACK_STATE['channels'] if c['name'] == SUMMARY_CHANNEL) +assert _bo['pinnedMessages'] == [], 'billing-ops must have no pinned messages at injection' +assert _SLACK_STATE['messages'].get(SUMMARY_CHANNEL) == [], 'billing-ops must be empty at injection' + + +# =========================================================================== +# 6) INJECT + VERIFY + LAUNCH (domain order: stripe, quickbooks, gmail, slack) +# =========================================================================== +APP_STATES = [ + ('http://28.7.184.198:8179', _STRIPE_STATE), # stripe_dashboard_mock + ('http://28.7.184.198:8172', _QB_STATE), # quickbooks_mock + ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_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/ar_payment_alert_010__long/reward.py b/ar_payment_alert_010__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..6240abc7f406ef999fd218029cb9b738719fcf39 --- /dev/null +++ b/ar_payment_alert_010__long/reward.py @@ -0,0 +1,689 @@ +""" +Reward Script: Clear the overnight payment-alert inbox +Task ID: ar_payment_alert_010__long +Mocks: stripe_dashboard_mock,quickbooks_mock,gmail_mock,slack_mock + +Scoring (all components in [0,1]; weights sum to EXACTLY 1.0; NO subtracted +penalties — leak is punished ONLY by precision inside the three F1 +set-membership components): + 0.24 refund set correctness — F1(true, pred): + true = {stripe_payment_id of REFUND alerts that require action} + pred = {payment ids REFUNDED now AND NOT refunded at injection} (a diff). + Refunding the already-refunded distractor cannot enter pred (no diff); + refunding the LEAVE-row / a non-target payment IS a false positive. + 0.22 dispute-evidence set correctness — F1(true, pred): + true = {stripe_dispute_id of SUBMIT_EVIDENCE alerts that require action} + pred = {dispute ids 'under_review' (evidence submitted) now AND NOT + 'under_review' at injection}. Submitting evidence sets a dispute's + status to 'under_review' (source-verified: Disputes.jsx handleSubmitEvidence + dispatches UPDATE_DISPUTE -> status='under_review'). The already-under_review + decoys cannot enter pred (no diff); responding to the LEAVE dispute = FP. + 0.22 receive-payment set correctness — F1(true, pred): + true = {qb_invoice_id of RECEIVE_PAYMENT alerts that require action} + pred = {invoice ids 'Paid' now AND NOT 'Paid' at injection}. + 0.12 gmail status label — frac of require-action alerts whose CURRENT gmail + labels include _alert.label_name (Refunded/Disputed/Reconciled), matched + by NAME (id-agnostic). Emails ship labels=[] so this is 0 at do-nothing. + 0.10 customer reply — frac of require-action alerts with a 'sent' email either + addressed to _alert.customer_email OR whose subject == _alert.reply_subject. + 0.05 slack #billing-ops post: a non-empty message containing a digit. + 0.05 slack #billing-ops pin: a pinned real #billing-ops message (gated on post). + +Answer key: read from gmail.initial_state.emails[*]._alert + .action ∈ {refund, submit_evidence, receive_payment, leave, skip} + .requires_action: bool + .stripe_payment_id | .refund_amount_cents (refund target) + .stripe_dispute_id (submit_evidence target) + .qb_invoice_id | .qb_invoice_number (receive_payment target) + .label_name | .customer_email | .reply_subject +and slack.initial_state._task_adapter.summary_channel -> 'billing-ops'. + +Stripe amounts are CENTS, QuickBooks amounts are DOLLARS. +""" +import copy +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 = {'stripe_dashboard': 'http://28.7.184.198:8179', 'quickbooks': 'http://28.7.184.198:8172', + '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): + if not isinstance(msg, dict): + return '' + return msg.get('content') or msg.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) if isinstance(slack_state, dict) else [] + target = None + for ch in channels: + if isinstance(ch, dict) and 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 target.get('id'), []) or [] + return [] + + +def _to_float(v): + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _sheet_rows(sheet): + if not isinstance(sheet, dict): + return [] + rows = sheet.get('rows', []) + return rows if isinstance(rows, list) else [] + + +def _sheet_tabs(sheets): + if isinstance(sheets, dict): + return sheets + if isinstance(sheets, list): + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') + if name: + out[name] = sh + return out + return {} + + +def _jaccard(a, b): + if not a and not b: + return 1.0 + u = a | b + return (len(a & b) / len(u)) if u else 1.0 + + +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 [], + 'attachments': m.get('attachments') if isinstance(m.get('attachments'), 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 +# +# Answer key lives in gmail.initial_state.emails[*]._alert — one dict per alert: +# action ∈ {refund, submit_evidence, receive_payment, leave, skip} +# requires_action: bool +# stripe_payment_id | refund_amount_cents (refund target) +# stripe_dispute_id (submit_evidence target) +# qb_invoice_id | qb_invoice_number (receive_payment target) +# label_name | customer_email | reply_subject +# slack.initial_state._task_adapter.summary_channel names the aux channel. +# We score CURRENT state against this key using precision-aware F1 set-membership +# for the three action sets (computed as a diff vs the injected state) — acting on +# a distractor / LEAVE item / wrong record lowers precision but never drives the +# score below 0. +# ============================================================================= +def _refunded_id_set(stripe_state): + """Payment ids that are (fully) refunded in this Stripe state — union of the + payments[].refunded/amount_refunded flags and any refunds[].charge id.""" + ids = set() + for p in (stripe_state.get('payments') or []): + if not isinstance(p, dict): + continue + pid = norm(p.get('id')) + if not pid: + continue + amt = p.get('amount') or 0 + ar = p.get('amount_refunded') or 0 + try: + fully = (float(amt) > 0 and float(ar) >= float(amt)) + except (TypeError, ValueError): + fully = False + if p.get('refunded') is True or fully: + ids.add(pid) + for r in (stripe_state.get('refunds') or []): + if isinstance(r, dict) and r.get('charge'): + ids.add(norm(r.get('charge'))) + return ids + + +def _evidenced_dispute_id_set(stripe_state): + """Dispute ids that have had evidence submitted — status flipped to + 'under_review' (the only status the mock's Submit-Evidence flow sets) or an + explicit evidence_submitted_at timestamp present.""" + ids = set() + for d in (stripe_state.get('disputes') or []): + if not isinstance(d, dict): + continue + did = norm(d.get('id')) + if not did: + continue + if norm(d.get('status')) == 'under_review' or d.get('evidence_submitted_at'): + ids.add(did) + return ids + + +def _paid_invoice_id_set(qb_state): + ids = set() + for inv in (qb_state.get('invoices') or []): + if isinstance(inv, dict) and norm(inv.get('status')) == 'paid': + ids.add(norm(inv.get('id'))) + return ids + + +def _recipient_emails(email): + """All recipient emails on a gmail email (To), normalized.""" + out = set() + to = email.get('to') if isinstance(email, dict) else None + if isinstance(to, list): + for x in to: + if isinstance(x, dict): + if x.get('email'): + out.add(norm(x.get('email'))) + elif x: + out.add(norm(x)) + elif isinstance(to, dict): + if to.get('email'): + out.add(norm(to.get('email'))) + elif to: + out.add(norm(to)) + return out + + +def _gmail_sent_emails(gmail_state): + """Sent-folder emails (plus isSent/sentAt fallbacks, then sent/outbox lists).""" + out = [] + if not isinstance(gmail_state, dict): + return out + for e in (gmail_state.get('emails') or []): + if not isinstance(e, dict): + continue + if norm(e.get('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 reward(go): + W_REFUND = 0.24 + W_DISPUTE = 0.22 + W_RECEIVE = 0.22 + W_LABEL = 0.12 + W_REPLY = 0.10 + W_POST = 0.05 + W_PIN = 0.05 + + # ---- 1) Answer key from gmail initial_state.emails[*]._alert ---- + gmail = go('gmail') + gm_init = gmail.get('initial_state', {}) if isinstance(gmail.get('initial_state'), dict) else {} + gm_cur = gmail.get('current_state', {}) if isinstance(gmail.get('current_state'), dict) else {} + + emails_i = gm_init.get('emails', []) or [] + alerts = [e for e in emails_i if isinstance(e, dict) and isinstance(e.get('_alert'), dict)] + if not alerts: + print('DEBUG_c4b39a92 fatal=no_alert_worklist total=0.0') + return 0.0 + + def _key(e): + return e.get('_alert', {}) + + require_alerts = [e for e in alerts if _key(e).get('requires_action')] + + refund_true = {norm(_key(e).get('stripe_payment_id')) for e in alerts + if _key(e).get('action') == 'refund' and _key(e).get('requires_action') + and _key(e).get('stripe_payment_id')} + dispute_true = {norm(_key(e).get('stripe_dispute_id')) for e in alerts + if _key(e).get('action') == 'submit_evidence' and _key(e).get('requires_action') + and _key(e).get('stripe_dispute_id')} + receive_true = {norm(_key(e).get('qb_invoice_id')) for e in alerts + if _key(e).get('action') == 'receive_payment' and _key(e).get('requires_action') + and _key(e).get('qb_invoice_id')} + + # ---- 2) Stripe: refund set + dispute-evidence set (diff vs injection) ---- + stripe = go('stripe_dashboard') + st_init = stripe.get('initial_state', {}) if isinstance(stripe.get('initial_state'), dict) else {} + st_cur = stripe.get('current_state', {}) if isinstance(stripe.get('current_state'), dict) else {} + + refunded_init = _refunded_id_set(st_init) + refunded_now = _refunded_id_set(st_cur) + refund_pred = refunded_now - refunded_init # newly-refunded (diff) + + evidenced_init = _evidenced_dispute_id_set(st_init) + evidenced_now = _evidenced_dispute_id_set(st_cur) + dispute_pred = evidenced_now - evidenced_init # newly-evidenced (diff) + + # ---- 3) QuickBooks: receive-payment set (diff vs injection) ---- + qb = go('quickbooks') + qb_init = qb.get('initial_state', {}) if isinstance(qb.get('initial_state'), dict) else {} + qb_cur = qb.get('current_state', {}) if isinstance(qb.get('current_state'), dict) else {} + paid_init = _paid_invoice_id_set(qb_init) + paid_now = _paid_invoice_id_set(qb_cur) + receive_pred = paid_now - paid_init # newly-paid invoices + + # F1 components (precision punishes leak; gate on a non-empty true set so a + # malformed/empty key can never hand out free credit at do-nothing). + refund_f1 = f1(refund_true, refund_pred) if refund_true else 0.0 + dispute_f1 = f1(dispute_true, dispute_pred) if dispute_true else 0.0 + receive_f1 = f1(receive_true, receive_pred) if receive_true else 0.0 + s_refund = W_REFUND * refund_f1 + s_dispute = W_DISPUTE * dispute_f1 + s_receive = W_RECEIVE * receive_f1 + + # ---- 4) Gmail status label among require-action alerts (matched by NAME) ---- + emails_c = {e.get('id'): e for e in (gm_cur.get('emails', []) or []) if isinstance(e, dict)} + labels_i = gm_init.get('labels', []) or [] + labels_c = gm_cur.get('labels', []) or [] + gmail_id_to_name = {} + for lab in list(labels_i) + list(labels_c): + if isinstance(lab, dict) and lab.get('id') is not None: + gmail_id_to_name[lab.get('id')] = norm(lab.get('name')) + label_ok = 0 + for e in require_alerts: + want = norm(_key(e).get('label_name')) + cur = emails_c.get(e.get('id'), {}) + got_names = {gmail_id_to_name.get(lid) for lid in (cur.get('labels') or [])} + # tolerate a label carried as a raw name too + got_names |= {norm(lid) for lid in (cur.get('labels') or [])} + if want and want in got_names: + label_ok += 1 + label_score = frac(label_ok, len(require_alerts)) if require_alerts else 0.0 + s_label = W_LABEL * label_score + + # ---- 5) Customer reply among require-action alerts ---- + sent = _gmail_sent_emails(gm_cur) + reply_ok = 0 + for e in require_alerts: + want_email = norm(_key(e).get('customer_email')) + want_subj = norm(_key(e).get('reply_subject')) + matched = False + for s in sent: + if want_email and want_email in _recipient_emails(s): + matched = True + break + subj = norm(s.get('subject')) + if want_subj and subj == want_subj: + matched = True + break + if matched: + reply_ok += 1 + reply_score = frac(reply_ok, len(require_alerts)) if require_alerts else 0.0 + s_reply = W_REPLY * reply_score + + # ---- 6) Slack #billing-ops: post (non-empty w/ a digit) + pin ---- + slack = go('slack') + sl_init = slack.get('initial_state', {}) if isinstance(slack.get('initial_state'), dict) else {} + sl_cur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + s_adapter = sl_init.get('_task_adapter', {}) if isinstance(sl_init.get('_task_adapter'), dict) else {} + summary_channel = s_adapter.get('summary_channel') or 'billing-ops' + + bo_msgs = _slack_channel_messages(sl_cur, summary_channel) + post_ok = any(re.search(r'\d', _msg_text(m)) for m in bo_msgs if isinstance(m, dict)) + s_post = W_POST * (1.0 if post_ok else 0.0) + + # Pin: at least one pinned id in #billing-ops that matches a real posted message. + msg_ids = set() + for m in bo_msgs: + if isinstance(m, dict): + mid = m.get('messageId') or m.get('id') + if mid is not None: + msg_ids.add(norm(mid)) + pinned = [] + for ch in (sl_cur.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel): + pinned = ch.get('pinnedMessages') or [] + break + pinned_ids = set() + for pm in pinned: + if isinstance(pm, dict): + pid = pm.get('messageId') or pm.get('id') + else: + pid = pm + if pid is not None: + pinned_ids.add(norm(pid)) + pin_ok = bool(post_ok and (pinned_ids & msg_ids)) + s_pin = W_PIN * (1.0 if pin_ok else 0.0) + + score = s_refund + s_dispute + s_receive + s_label + s_reply + s_post + s_pin + + print( + 'DEBUG_c4b39a92 ' + f'refund_true={len(refund_true)} refund_pred={len(refund_pred)} refund_f1={round(refund_f1, 4)} ' + f'dispute_true={len(dispute_true)} dispute_pred={len(dispute_pred)} dispute_f1={round(dispute_f1, 4)} ' + f'receive_true={len(receive_true)} receive_pred={len(receive_pred)} receive_f1={round(receive_f1, 4)} ' + f'require={len(require_alerts)} label_ok={label_ok} label_score={round(label_score, 4)} ' + f'reply_ok={reply_ok} reply_score={round(reply_score, 4)} ' + f'post_ok={int(post_ok)} pin_ok={int(pin_ok)} ' + f'w_refund={round(s_refund, 4)} w_dispute={round(s_dispute, 4)} w_receive={round(s_receive, 4)} ' + f'w_label={round(s_label, 4)} w_reply={round(s_reply, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} ' + 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/csm_escalation_001/_cua_gym_vm_bridge.sh b/csm_escalation_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csm_escalation_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/csm_escalation_001/initial_setup.py b/csm_escalation_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c3f7e39725d4c5013eac128011eab0fb822cc227 --- /dev/null +++ b/csm_escalation_001/initial_setup.py @@ -0,0 +1,528 @@ +# --- 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: CSM escalation -> tracked bug across Slack/Jira/Salesforce/Notion +Task ID: csm_escalation_001 +Domain: mock_websites +Mocks: slack_mock, jira_mock, salesforce_mock, notion_mock + +NOTE on sid: initial_env and golden_env are SEPARATE VMs that do NOT share /tmp. +We therefore use a DETERMINISTIC sid derived from the task id. This script owns the +*_initial sid; golden_patch.py owns the *_golden sid. Both also write their sid to +/tmp/task_web_sid so reward.py can read it on whichever VM it runs on. +""" +import os +import shlex +import subprocess +import time + +import requests + +TASK_ID = 'csm_escalation_004' +SID = f'cuagym-{TASK_ID}-initial' + +MOCKS = { + 'slack_mock': 'http://28.7.184.198:8178', + 'jira_mock': 'http://28.7.184.198:8153', + 'salesforce_mock': 'http://28.7.184.198:8175', + 'notion_mock': 'http://28.7.184.198:8166', +} +PRIMARY_URL = MOCKS['slack_mock'] + +with open('/tmp/task_web_sid', 'w') as f: + f.write(SID) +print(f'sid={SID}') + +# --- Egress proxy helper (MANDATORY) --- +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def resolve_proxy(probe_url): + try: + requests.get(probe_url, timeout=8) + return None + except Exception: + pass + for candidate in PROXY_CANDIDATES: + if not candidate: + continue + try: + requests.get(probe_url, timeout=12, proxies={'http': candidate, 'https': candidate}) + return candidate + except Exception: + continue + raise RuntimeError('No working route to mock servers; direct and proxy attempts failed') + + +PROXY = resolve_proxy(f'{PRIMARY_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +# =========================================================================== +# BASELINE BUILDERS (shared, conceptually, with golden_patch.py) +# =========================================================================== +def build_slack_state(): + users = [ + {"userId": "user_1", "fullName": "Jordan Rivera", "displayName": "Jordan", "email": "jordan.rivera@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=1", "title": "Customer Success Manager", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_2", "fullName": "Alex Park", "displayName": "Alex", "email": "alex.park@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=2", "title": "Engineering Lead", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_3", "fullName": "Priya Anand", "displayName": "Priya", "email": "priya.anand@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=3", "title": "Support Lead", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"}, + {"userId": "user_4", "fullName": "Diego Morales", "displayName": "Diego", "email": "diego.morales@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=4", "title": "Solutions Engineer", "status": "away", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"}, + {"userId": "user_5", "fullName": "Hannah Brooks", "displayName": "Hannah", "email": "hannah.brooks@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=5", "title": "Product Manager", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_6", "fullName": "Tom Becker", "displayName": "Tom", "email": "tom.becker@cedarworks.example.com", "avatar": "https://picsum.photos/200/200?random=6", "title": "Ops Manager (Cedar Works)", "status": "online", "statusMessage": "Guest", "statusEmoji": "", "timeZone": "America/Chicago"}, + {"userId": "user_7", "fullName": "Maria Vance", "displayName": "Maria", "email": "maria.vance@vertexmfg.example.com", "avatar": "https://picsum.photos/200/200?random=7", "title": "Admin (Vertex Manufacturing)", "status": "online", "statusMessage": "Guest", "statusEmoji": "", "timeZone": "America/New_York"}, + ] + current = next(u for u in users if u['userId'] == 'user_1') + + def channel(cid, name, desc, members, topic=""): + return {"channelId": cid, "name": name, "description": desc, "topic": topic, "isPrivate": False, + "isStarred": False, "members": members, "createdBy": "user_1", + "createdAt": "2026-01-04T09:00:00Z", "pinnedMessages": [], "unreadCount": 0} + + am = ["user_1", "user_2", "user_3", "user_4", "user_5"] + channels = [ + channel("general", "general", "Company-wide announcements", am), + channel("random", "random", "Non-work banter", am), + channel("engineering", "engineering", "Engineering team", ["user_1", "user_2", "user_4"]), + channel("design", "design", "Design team", ["user_1", "user_5"]), + channel("marketing", "marketing", "Marketing team", ["user_1", "user_5"]), + channel("project-alpha", "project-alpha", "Project Alpha workstream", ["user_1", "user_2"]), + channel("acct-vertex", "acct-vertex", "Shared channel with customer Vertex Manufacturing", + ["user_1", "user_3", "user_7"], topic="Vertex Manufacturing <> Northwind Cloud"), + channel("acct-cedar", "acct-cedar", "Shared channel with customer Cedar Works", + ["user_1", "user_3", "user_6"], topic="Cedar Works <> Northwind Cloud"), + ] + messages = { + "general": [ + {"messageId": "msg_g1", "senderId": "user_5", "content": "Reminder: quarterly customer reviews are due Friday.", "timestamp": "2026-06-22T13:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_g2", "senderId": "user_2", "content": "Deploy window for v4.2 is tomorrow 6pm ET.", "timestamp": "2026-06-23T15:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "random": [ + {"messageId": "msg_r1", "senderId": "user_4", "content": "Coffee machine on 3rd floor is fixed.", "timestamp": "2026-06-23T10:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "engineering": [ + {"messageId": "msg_e1", "senderId": "user_2", "content": "Staging integration latency is being investigated, low impact.", "timestamp": "2026-06-23T11:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "design": [ + {"messageId": "msg_d1", "senderId": "user_5", "content": "New dashboard mockups in Figma.", "timestamp": "2026-06-22T16:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "marketing": [ + {"messageId": "msg_m1", "senderId": "user_5", "content": "Case study draft ready for review.", "timestamp": "2026-06-21T14:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "project-alpha": [ + {"messageId": "msg_pa1", "senderId": "user_2", "content": "Alpha milestone 2 on track.", "timestamp": "2026-06-20T09:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "acct-vertex": [ + {"messageId": "msg_v1", "senderId": "user_1", "content": "Hi Maria, welcome to our shared channel! Reach out here any time.", "timestamp": "2026-06-18T09:15:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_v2", "senderId": "user_7", "content": "Thanks Jordan, this is great. Things have been running smoothly so far.", "timestamp": "2026-06-18T09:20:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_v3", "senderId": "user_7", "content": "Our Salesforce↔Northwind integration has been DOWN since this morning — every sync fails with a 500 error and it's blocking our ops team from pushing orders. Steps to reproduce: (1) open Integrations, (2) click Sync Now, (3) it errors out with a 500. This is urgent, can someone help?", "timestamp": "2026-06-24T13:05:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "acct-cedar": [ + {"messageId": "msg_c1", "senderId": "user_6", "content": "Hi team — not urgent at all, but it would be nice to have a dark mode option in the reporting view someday. Just a feature idea for the backlog.", "timestamp": "2026-06-24T10:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + } + return { + "currentUser": current, + "workspace": {"workspaceId": "ws_northwind", "workspaceName": "Northwind Cloud", "icon": ""}, + "users": users, + "channels": channels, + "messages": messages, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + + +def build_jira_state(): + users = [ + {"id": "u1", "name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u1"}, + {"id": "u2", "name": "Alex Park", "email": "alex.park@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u2"}, + {"id": "u3", "name": "Priya Anand", "email": "priya.anand@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u3"}, + {"id": "u4", "name": "Diego Morales", "email": "diego.morales@northwindcloud.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"}, + {"id": "p2", "key": "SCRUM", "name": "Scrum Alpha", "leadId": "u2", "category": "Software", "icon": "https://picsum.photos/64/64?random=p2"}, + ] + sprints = [ + {"id": "s1", "projectId": "p2", "name": "Sprint 7", "goal": "Stabilize integrations", "startDate": "2026-06-16T12:00:00.000Z", "endDate": "2026-06-30T12:00:00.000Z", "state": "active"}, + {"id": "s2", "projectId": "p2", "name": "Sprint 8", "goal": "Reporting improvements", "startDate": "2026-07-01T12:00:00.000Z", "endDate": "2026-07-14T12:00:00.000Z", "state": "future"}, + ] + + def issue(iid, key, pid, summary, desc, itype, status, priority, sp, reporter, assignee, sprint=None, labels=None): + return {"id": iid, "key": key, "projectId": pid, "summary": summary, "description": desc, + "type": itype, "status": status, "priority": priority, "storyPoints": sp, + "reporterId": reporter, "assigneeId": assignee, "sprintId": sprint, "epicId": None, + "labels": labels or [], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-06-15T12:00:00.000Z", "updatedAt": "2026-06-20T12:00:00.000Z"} + + issues = [ + issue("i1", "KAN-1", "p1", "Set up CI/CD pipeline", "Configure build and deploy automation.", "Story", "In Progress", "High", 5, "u1", "u2"), + issue("i2", "KAN-2", "p1", "Add SSO login support", "Support SAML-based single sign-on.", "Story", "To Do", "Medium", 8, "u1", "u4"), + issue("i3", "KAN-3", "p1", "Improve onboarding docs", "Rewrite the getting-started guide.", "Task", "To Do", "Low", 3, "u3", None), + issue("i4", "SCRUM-1", "p2", "Integration latency on staging", "Sync jobs on the STAGING environment are slower than expected (around 2-3s added latency). Low customer impact; investigate query plan. This is NOT a production outage.", "Bug", "In Progress", "Low", 2, "u2", "u4", sprint="s1", labels=["staging", "performance"]), + issue("i5", "SCRUM-2", "p2", "Export to CSV button missing", "The CSV export button disappeared on the reports page.", "Bug", "To Do", "Medium", 3, "u3", "u2", sprint="s1"), + issue("i6", "SCRUM-3", "p2", "Dark mode for reports", "Add a dark theme to the reporting view.", "Story", "To Do", "Low", 5, "u3", None, sprint="s2"), + ] + return { + "currentUser": users[0], + "users": users, + "projects": projects, + "sprints": sprints, + "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": [], + } + + +def build_salesforce_state(): + users = [ + {"userId": "user-1", "firstName": "Jordan", "lastName": "Rivera", "email": "jordan.rivera@northwindcloud.com", "phone": "(555) 123-4567", "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM", "avatar": "https://i.pravatar.cc/150?u=user-1", "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"}, + {"userId": "user-2", "firstName": "Emma", "lastName": "Wilson", "email": "emma.wilson@northwindcloud.com", "phone": "(555) 234-5678", "title": "Account Executive", "department": "Sales", "role": "Rep", "avatar": "https://i.pravatar.cc/150?u=user-2", "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"}, + {"userId": "user-3", "firstName": "Priya", "lastName": "Anand", "email": "priya.anand@northwindcloud.com", "phone": "(555) 345-6789", "title": "Support Lead", "department": "Support", "role": "Support", "avatar": "https://i.pravatar.cc/150?u=user-3", "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning"}, + {"userId": "user-4", "firstName": "Sarah", "lastName": "Davis", "email": "sarah.davis@northwindcloud.com", "phone": "(555) 456-7890", "title": "Support Engineer", "department": "Support", "role": "Support", "avatar": "https://i.pravatar.cc/150?u=user-4", "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning"}, + {"userId": "user-5", "firstName": "David", "lastName": "Brown", "email": "david.brown@northwindcloud.com", "phone": "(555) 567-8901", "title": "Sales Rep", "department": "Sales", "role": "Rep", "avatar": "https://i.pravatar.cc/150?u=user-5", "timezone": "America/Denver", "locale": "en-US", "theme": "lightning"}, + ] + + def account(aid, name, industry, owner, desc): + return {"accountId": aid, "name": name, "phone": "(555) 100-2000", "website": "https://example.com", + "type": "Customer", "industry": industry, "revenue": 30000000, "employees": 400, + "description": desc, "ownerId": owner, + "billingStreet": "100 Main St", "billingCity": "Detroit", "billingState": "MI", "billingZip": "48201", "billingCountry": "United States", + "shippingStreet": "100 Main St", "shippingCity": "Detroit", "shippingState": "MI", "shippingZip": "48201", "shippingCountry": "United States", + "createdDate": "2025-02-01T00:00:00.000Z", "modifiedDate": "2026-05-01T00:00:00.000Z"} + + accounts = [ + account("account-1", "Vertex Manufacturing", "Manufacturing", "user-1", "Key mid-market customer; uses the Salesforce<->Northwind integration heavily."), + account("account-2", "Vertex Logistics", "Logistics", "user-2", "Unrelated prospect with a similar name; no active integration issues."), + account("account-3", "Cedar Works", "Consumer Goods", "user-1", "Mid-market customer; stable account."), + account("account-4", "Summit Retail Group", "Retail", "user-5", "Growing retail customer."), + ] + contacts = [ + {"contactId": "contact-1", "accountId": "account-1", "firstName": "Maria", "lastName": "Vance", "title": "IT Admin", "department": "Operations", "email": "maria.vance@vertexmfg.example.com", "phone": "(555) 700-1000", "ownerId": "user-1"}, + {"contactId": "contact-2", "accountId": "account-2", "firstName": "Greg", "lastName": "Hall", "title": "Operations Director", "department": "Operations", "email": "greg.hall@vertexlog.example.com", "phone": "(555) 700-2000", "ownerId": "user-2"}, + {"contactId": "contact-3", "accountId": "account-3", "firstName": "Tom", "lastName": "Becker", "title": "Ops Manager", "department": "Operations", "email": "tom.becker@cedarworks.example.com", "phone": "(555) 700-3000", "ownerId": "user-1"}, + ] + + def case(cid, num, subject, status, priority, acct, contact, owner, ctype, desc): + return {"caseId": cid, "caseNumber": num, "subject": subject, "status": status, "priority": priority, + "origin": "Email", "type": ctype, "accountId": acct, "contactId": contact, + "description": desc, "ownerId": owner, + "createdDate": "2026-06-20T11:00:00.000Z", "modifiedDate": "2026-06-22T11:00:00.000Z", "closedDate": None} + + cases = [ + case("case-1", "00001001", "Dashboard access error", "New", "Medium", "account-3", "contact-3", "user-4", "Problem", "Customer reports occasional 403 on the analytics dashboard."), + case("case-2", "00001002", "Billing question on latest invoice", "Working", "Low", "account-4", None, "user-3", "Question", "Customer asks for a breakdown of usage charges."), + case("case-3", "00001003", "Feature request: bulk export", "New", "Low", "account-2", "contact-2", "user-2", "Feature Request", "Prospect would like a bulk export option."), + ] + return { + "user": users[0], + "users": users, + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": [], + "cases": cases, + "activities": [], + "chatterPosts": [], + "files": [], + "following": ["user-2", "user-3"], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +def build_notion_state(): + HEALTH_DB_ID = "db-health-tracker" + HOME_PAGE = "page-home" + P_HEALTH, P_MAU, P_NOTE, P_OWNER = "prop-health", "prop-mau", "prop-risknote", "prop-owner" + ROW_VERTEX, ROW_CEDAR, ROW_SUMMIT = "row-vertex", "row-cedar", "row-summit" + + def health_row(rid, name, health, mau, note): + return {"id": rid, "title": name, "icon": "\U0001f3e2", "cover": None, "parentId": HEALTH_DB_ID, + "blockIds": [], "favorite": False, "createdDate": "2026-06-01T09:00:00.000Z", + "lastEditedDate": "2026-06-20T09:00:00.000Z", + "properties": {P_HEALTH: health, P_MAU: mau, P_NOTE: note, P_OWNER: ["user-1"]}} + + pages = { + HOME_PAGE: {"id": HOME_PAGE, "title": "Customer Success Home", "icon": "\U0001f4cb", "cover": None, + "parentId": None, "blockIds": [], "favorite": True, + "createdDate": "2026-05-01T09:00:00.000Z", "lastEditedDate": "2026-06-20T09:00:00.000Z", "properties": {}}, + HEALTH_DB_ID: {"id": HEALTH_DB_ID, "title": "Customer Health Tracker", "icon": "\U0001f4ca", "cover": None, + "parentId": None, "type": "database", "viewType": "table", + "properties": [ + {"id": P_HEALTH, "name": "Health", "type": "select", "options": ["Green", "Yellow", "Red"]}, + {"id": P_MAU, "name": "MAU Trend", "type": "select", "options": ["Up", "Flat", "Down"]}, + {"id": P_NOTE, "name": "Risk Note", "type": "text"}, + {"id": P_OWNER, "name": "CSM", "type": "person"}], + "views": [{"id": "view-1", "name": "All Accounts", "type": "table", "filters": [], "sorts": [], "groupBy": None, "visibleProperties": [P_HEALTH, P_MAU, P_NOTE, P_OWNER]}], + "items": [ROW_VERTEX, ROW_CEDAR, ROW_SUMMIT], + "blockIds": [], "favorite": True, "createdDate": "2026-05-01T09:00:00.000Z"}, + ROW_VERTEX: health_row(ROW_VERTEX, "Vertex Manufacturing", "Yellow", "Flat", ""), + ROW_CEDAR: health_row(ROW_CEDAR, "Cedar Works", "Green", "Up", "Stable; expansion conversation in Q3."), + ROW_SUMMIT: health_row(ROW_SUMMIT, "Summit Retail Group", "Green", "Up", "Onboarding completed."), + } + return { + "user": {"id": "user-1", "name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com", "avatar": ""}, + "workspace": {"id": "ws-1", "name": "Northwind Cloud", "icon": "", "members": ["user-1", "user-2", "user-3"]}, + "pages": pages, + "blocks": {}, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"}, + "notifications": [], + "pageOrder": [HOME_PAGE, HEALTH_DB_ID], + } + + +STATES = { + 'slack_mock': build_slack_state(), + 'jira_mock': build_jira_state(), + 'salesforce_mock': build_salesforce_state(), + 'notion_mock': build_notion_state(), +} + +# --- Inject all (reset first so re-runs are clean) --- +for name, url in MOCKS.items(): + requests.post(f'{url}/post?sid={SID}', json={'action': 'reset'}, timeout=60, proxies=PROXIES) + resp = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': STATES[name]}, timeout=30, proxies=PROXIES) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={SID}', timeout=15, proxies=PROXIES).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None after injection' + print(f'State injected: {name} sid={SID}') + + +# --- Launch browser on primary mock (Slack) --- +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 +chrome_proxy = f'--proxy-server={PROXY}' if PROXY else '' +_primary_mock_url = PRIMARY_URL +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={SID}"', delay_sec=2.0) +_open_remaining_mock_tabs(_primary_mock_url) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={SID}') diff --git a/csm_escalation_001/reward.py b/csm_escalation_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..4352d004b2e08691ab05db365a82f6248cb714a7 --- /dev/null +++ b/csm_escalation_001/reward.py @@ -0,0 +1,466 @@ +# --- 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: CSM escalation -> tracked engineering bug + SF case + Notion health + Slack reply +Task ID: csm_escalation_001 +Domain: mock_websites (multi-mock: slack, jira, salesforce, notion) +Scoring (sums to 1.0, all components measure task-introduced changes only): + - Component 1 (0.30): NEW Jira issue naming the Vertex integration incident, with repro + evidence, high priority, a real status, and a real project. + - Component 2 (0.30): NEW Salesforce case on account-1 (Vertex Manufacturing), + priority High/Critical, and an available active/completed status. + - Component 3 (0.20): Notion 'Vertex Manufacturing' health row -> Health 'Red' AND non-empty + Risk Note. + - Component 4a (0.10): NEW Slack reply by the CSM (user_1) in 'acct-vertex' (programmatic). + - Component 4b (0.10): That reply acknowledges the outage AND states a concrete next-update + time/ETA (programmatic pattern detection). +All 1.0 is programmatic — fully deterministic and reproducible. +""" +import json +import os +import re +import sys +from datetime import datetime, timedelta + +import requests + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +MOCKS = { + 'slack': 'http://28.7.184.198:8178', + 'jira': 'http://28.7.184.198:8153', + 'salesforce': 'http://28.7.184.198:8175', + 'notion': 'http://28.7.184.198:8166', +} + +# --- Egress proxy helper (MANDATORY) --- +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def resolve_proxy(probe_url): + try: + requests.get(probe_url, timeout=8) + return None + except Exception: + pass + for candidate in PROXY_CANDIDATES: + if not candidate: + continue + try: + requests.get(probe_url, timeout=12, + proxies={'http': candidate, 'https': candidate}) + return candidate + except Exception: + continue + return None + + +PROXY = resolve_proxy(f"{MOCKS['slack']}/go?sid=conn-probe") +PROXIES = None + + +def text_value(value): + """Flatten mock field values that may be raw strings or typed objects.""" + if value is None: + return '' + if isinstance(value, str): + return value + if isinstance(value, (int, float, bool)): + return str(value) + if isinstance(value, dict): + return ' '.join(text_value(v) for v in value.values()) + if isinstance(value, (list, tuple, set)): + return ' '.join(text_value(v) for v in value) + return str(value) + + +def norm_text(value): + return re.sub(r'\s+', ' ', text_value(value)).strip().lower() + + +def canon_option(value): + return re.sub(r'[^a-z0-9]+', ' ', text_value(value)).strip().lower() + + +def option_in(value, allowed): + current = canon_option(value) + return current in {canon_option(v) for v in allowed} + + +def contains_any(text, needles): + low = norm_text(text) + return any(needle in low for needle in needles) + + +def field_blob(record, keys): + return ' '.join(text_value(record.get(k)) for k in keys) + + +def parse_iso_datetime(value): + raw = text_value(value).strip() + if not raw: + return None + try: + return datetime.fromisoformat(raw.replace('Z', '+00:00')) + except ValueError: + return None + + +def relative_date_tokens(reference_dt): + """Build date tokens dynamically instead of baking in one calendar date.""" + if reference_dt is None: + return set() + tokens = set() + months = [ + 'january', 'february', 'march', 'april', 'may', 'june', + 'july', 'august', 'september', 'october', 'november', 'december' + ] + for delta in range(0, 8): + cur = reference_dt + timedelta(days=delta) + month = months[cur.month - 1] + tokens.update({ + cur.strftime('%Y-%m-%d').lower(), + cur.strftime('%m/%d').lstrip('0').replace('/0', '/'), + cur.strftime('%m/%d/%Y').lstrip('0').replace('/0', '/'), + f'{month} {cur.day}', + f'{month[:3]} {cur.day}', + cur.strftime('%A').lower(), + }) + return tokens + + +def has_next_update_eta(text, reference_dt=None): + low = norm_text(text) + number_word = ( + r'\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|' + r'eleven|twelve|couple|few' + ) + eta_patterns = [ + r'\b\d{1,2}:\d{2}\s*(?:am|pm)?\s*(?:et|pt|ct|mt|utc|gmt)?\b', + r'\b\d{1,2}\s*(?:am|pm)\s*(?:et|pt|ct|mt|utc|gmt)?\b', + r'\b(?:within|in|after|every)\s+(?:' + number_word + r')\s*' + r'(?:mins?|minutes?|hrs?|hours?|days?|business days?)\b', + r'\b(?:by|before)\s+(?:eod|eob|cob|end of (?:the )?day|' + r'close of business|noon|midday|midnight|today|tomorrow|tonight|' + r'this (?:morning|afternoon|evening)|next business day|' + r'(?:mon|tues|wednes|thurs|fri|satur|sun)day|' + r'\d{1,2}(?::\d{2})?\s*(?:am|pm)?)\b', + r'\b(?:later today|this (?:morning|afternoon|evening)|tomorrow|' + r'tonight|next business day)\b', + r'\b(?:next update|update you|follow up|get back to you|circle back)' + r'\b.{0,80}\b(?:today|tomorrow|tonight|morning|afternoon|evening|' + r'eod|eob|cob|hour|minute|day|business day|am|pm|\d)\b', + r'\b\d{4}-\d{1,2}-\d{1,2}\b', + r'\b\d{1,2}/\d{1,2}(?:/\d{2,4})?\b', + r'\b(?:jan|january|feb|february|mar|march|apr|april|may|jun|june|' + r'jul|july|aug|august|sep|sept|september|oct|october|nov|november|' + r'dec|december)\s+\d{1,2}\b', + ] + if any(re.search(pattern, low) for pattern in eta_patterns): + return True + return any(token and token in low for token in relative_date_tokens(reference_dt)) + + +# --- Fetch state from all mocks --- +states = {} +for name, url in MOCKS.items(): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json() + states[name] = data + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {name} ({url}): {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def verify_task(): + total_score = 0.0 + + # ===================================================================== + # Component 1 — Jira: NEW issue for the Vertex integration outage (0.30) + # Measures a task change: there is NO Vertex outage bug in initial_env. + # ===================================================================== + try: + j_init = states['jira']['initial_state'] + j_cur = states['jira']['current_state'] + init_ids = {i.get('id') for i in j_init.get('issues', [])} + new_issues = [i for i in j_cur.get('issues', []) if i.get('id') not in init_ids] + + matched = None + for issue in new_issues: + blob = norm_text(field_blob(issue, ('summary', 'description'))) + # Names the customer and the integration/sync incident without + # requiring an exact outage wording. + names_vertex = 'vertex' in blob + names_incident = ( + contains_any(blob, ('integration', 'sync', 'salesforce')) + and contains_any(blob, ( + 'down', 'outage', 'fail', 'failure', 'error', '500', + 'blocked', 'blocking', 'urgent', 'incident', 'escalat' + )) + ) + if names_vertex and names_incident: + matched = issue + break + + if matched is None: + print('FAIL: Component 1 — no NEW Jira issue naming the Vertex integration outage') + else: + blob = norm_text(field_blob(matched, ('summary', 'description'))) + # Jira's mock issue types are Story/Task/Bug/Epic; Bug is preferred + # for this incident, while Story/Task are still reasonable tracked work. + good_type = option_in(matched.get('type'), ('Bug', 'Task', 'Story')) + # Repro evidence is accepted by core signals rather than exact + # phrasing: open Integrations -> Sync Now -> 500/error. + repro_signals = [ + contains_any(blob, ('integration', 'integrations')), + contains_any(blob, ('sync', 'sync now')), + contains_any(blob, ('500', 'error', 'fails', 'failed', 'failure')), + ] + has_repro = ( + sum(1 for ok in repro_signals if ok) >= 2 + or contains_any(blob, ('repro', 'reproduce', 'steps')) + ) + good_priority = option_in(matched.get('priority'), ( + 'High', 'Highest', 'Critical', 'Urgent' + )) + allowed_statuses = { + s for issue in j_cur.get('issues', []) for s in [issue.get('status')] if s + } | {'To Do', 'In Progress', 'In Review', 'Done'} + good_status = option_in(matched.get('status'), allowed_statuses) + real_project_ids = {p.get('id') for p in j_cur.get('projects', []) if p.get('id')} + real_project = matched.get('projectId') in real_project_ids + checks = { + 'type Bug/Task/Story': good_type, + 'has_repro_steps': has_repro, + 'priority High/Highest': good_priority, + 'status is a real Jira option': good_status, + 'real Jira project': real_project, + } + if all(checks.values()): + print(f"PASS: Component 1 — new Jira issue {matched.get('key')} " + f"'{matched.get('summary')}' (0.30 pts)") + total_score += 0.30 + else: + failed = [k for k, v in checks.items() if not v] + print(f"FAIL: Component 1 — new issue {matched.get('key')} missing: {failed}") + except Exception as e: + print(f'ERROR: Component 1 (Jira) — {e}') + + # ===================================================================== + # Component 2 — Salesforce: NEW escalation case on Vertex Mfg (0.30) + # Measures a task change: NO Vertex outage case exists in initial_env. + # ===================================================================== + try: + s_init = states['salesforce']['initial_state'] + s_cur = states['salesforce']['current_state'] + init_case_ids = {c.get('caseId') for c in s_init.get('cases', [])} + new_cases = [c for c in s_cur.get('cases', []) + if c.get('caseId') not in init_case_ids] + + account_by_id = {a.get('accountId'): a + for a in s_cur.get('accounts', [])} + + def is_vertex_case(case): + account_id = case.get('accountId') + account_name = ( + account_by_id.get(account_id, {}).get('name') or '') + case_blob = norm_text(field_blob(case, ( + 'accountName', 'company', 'subject', 'description' + ))) + return ( + account_id == 'account-1' + or 'vertex manufacturing' in norm_text(account_name) + or 'vertex manufacturing' in case_blob + ) + + # Restrict to newly created cases tied to the Vertex Manufacturing account. + candidates = [c for c in new_cases if is_vertex_case(c)] + + # Select the case to score WITHOUT keyword matching on + # subject/description/type (keyword matching was unreliable). Among the + # new Vertex Manufacturing cases, prefer one that already satisfies the + # meaningful checks (priority + real status); otherwise fall back to the + # first candidate so the failure is still reported. + def _case_scores(case): + return ( + option_in(case.get('priority'), ('High', 'Critical')) + and option_in(case.get('status'), ( + 'new', 'working', 'escalated', 'closed', + 'not started', 'not start', 'in progress', 'completed' + )) + ) + + matched = next((c for c in candidates if _case_scores(c)), + candidates[0] if candidates else None) + + if matched is None: + print('FAIL: Component 2 — no NEW Salesforce case on account-1 (Vertex Manufacturing)') + else: + good_account = is_vertex_case(matched) + good_priority = option_in(matched.get('priority'), ('High', 'Critical')) + good_status = option_in(matched.get('status'), ( + 'new', 'working', 'escalated', 'closed', + 'not started', 'not start', 'in progress', 'completed' + )) + checks = { + 'Vertex Manufacturing account': good_account, + 'priority High/Critical': good_priority, + 'status is a real Salesforce option': good_status, + } + if all(checks.values()): + print(f"PASS: Component 2 — new case {matched.get('caseNumber')} " + f"'{matched.get('subject')}' (0.30 pts)") + total_score += 0.30 + else: + failed = [k for k, v in checks.items() if not v] + print(f"FAIL: Component 2 — new case missing: {failed}") + except Exception as e: + print(f'ERROR: Component 2 (Salesforce) — {e}') + + # ===================================================================== + # Component 3 — Notion: Vertex health row -> Red + Risk Note (0.20) + # Measures a task change: initial health is Yellow/Green, Risk Note blank. + # ===================================================================== + try: + n_init = states['notion']['initial_state'] + n_cur = states['notion']['current_state'] + + def find_vertex_row(pages): + # Locate the Customer Health Tracker DB, then its Vertex Manufacturing row + for pid, p in pages.items(): + if p.get('type') == 'database' and 'health' in norm_text(p.get('title')): + # map property name -> id + name_to_id = {norm_text(pr.get('name')): pr.get('id') + for pr in p.get('properties', [])} + for itid in p.get('items', []): + itp = pages.get(itid, {}) + if 'vertex manufacturing' in norm_text(itp.get('title')): + return itp, name_to_id + return None, {} + + cur_row, name_to_id = find_vertex_row(n_cur.get('pages', {})) + if cur_row is None: + print('FAIL: Component 3 — Vertex Manufacturing health row not found') + else: + props = cur_row.get('properties', {}) + health_id = name_to_id.get('health') + risk_id = ( + name_to_id.get('risk note') + or next((pid for name, pid in name_to_id.items() + if 'risk' in name and 'note' in name), None) + ) + health_val = props.get(health_id) + risk_val = props.get(risk_id) + health_red = option_in(health_val, ('Red',)) + risk_text = norm_text(risk_val) + risk_ok = bool(risk_text) + checks = {"Health == 'Red'": health_red, 'Risk Note is non-empty': risk_ok} + if all(checks.values()): + print(f"PASS: Component 3 — Notion Vertex row Health=Red + Risk Note set (0.20 pts)") + total_score += 0.20 + else: + failed = [k for k, v in checks.items() if not v] + print(f"FAIL: Component 3 — Notion row missing: {failed} " + f"(health={health_val!r}, risk={risk_val!r})") + except Exception as e: + print(f'ERROR: Component 3 (Notion) — {e}') + + # ===================================================================== + # Component 4 — Slack: CSM acknowledgement reply in 'acct-vertex' + # 4a (0.10, programmatic): new message by user_1 in acct-vertex + # 4b (0.10, programmatic): acknowledges outage AND states next-update ETA + # Measures a task change: no CSM ack reply exists in initial_env. + # ===================================================================== + new_vertex_msgs = [] + try: + sl_init = states['slack']['initial_state'] + sl_cur = states['slack']['current_state'] + init_v = sl_init.get('messages', {}).get('acct-vertex', []) + cur_v = sl_cur.get('messages', {}).get('acct-vertex', []) + # New messages authored by the CSM (user_1). Compare message IDs so + # thread replies or timestamp reordering do not hide valid replies. + init_ids = {m.get('messageId') for m in init_v} + added = [m for m in cur_v if m.get('messageId') not in init_ids] + if not added and len(cur_v) > len(init_v): + added = cur_v[len(init_v):] + new_vertex_msgs = [m for m in added if m.get('senderId') == 'user_1'] + + if new_vertex_msgs: + print(f"PASS: Component 4a — new CSM reply in 'acct-vertex' (0.10 pts)") + total_score += 0.10 + else: + print("FAIL: Component 4a — no new CSM (user_1) reply in 'acct-vertex'") + except Exception as e: + print(f'ERROR: Component 4a (Slack) — {e}') + + # Component 4b — PROGRAMMATIC: acknowledgement + concrete next-update ETA (0.10) + # The task requires the reply to "acknowledge the issue and tell them when we'll + # update them next." We verify both intents via pattern detection rather than an + # LLM judge, so the score is fully deterministic and reproducible: + # (a) acknowledgement: references the outage/issue/escalation it is responding to + # (b) concrete next-update time/ETA: a clock time, a relative window, or a named day. + try: + if new_vertex_msgs: + reply_text = (new_vertex_msgs[-1].get('content') or '') + + # (a) acknowledges the reported issue / outage + ack = contains_any(reply_text, ( + 'outage', 'integration', 'sync', 'issue', '500', + 'escalat', 'sorry', 'flag', 'disruption', 'down', + 'received', 'acknowledge', 'acknowledged', 'reported', + 'looking into', 'investigating', 'engineering', 'ticket', + 'incident', 'blocked', 'blocking' + )) + + # (b) states a concrete next-update time / ETA. The reference date + # comes from the customer report so relative terms are evaluated + # dynamically instead of against a hard-coded calendar day. + customer_times = [ + parse_iso_datetime(m.get('timestamp')) + for m in init_v + if m.get('senderId') != 'user_1' + ] + customer_times = [t for t in customer_times if t is not None] + reference_dt = max(customer_times) if customer_times else None + has_eta = has_next_update_eta(reply_text, reference_dt) + + checks = {'acknowledges issue': ack, 'states next-update ETA': has_eta} + if all(checks.values()): + print(f"PASS: Component 4b — reply acknowledges outage + gives ETA (0.10 pts)") + total_score += 0.10 + else: + failed = [k for k, v in checks.items() if not v] + print(f"FAIL: Component 4b — reply missing: {failed} (text={reply_text[:120]!r})") + else: + print("FAIL: Component 4b — no CSM reply to evaluate") + except Exception as e: + print(f'ERROR: Component 4b (Slack) — {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/csm_escalation_001/reward_label.json b/csm_escalation_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..ef1a030db245b77a13b6878c0564261d36875baa --- /dev/null +++ b/csm_escalation_001/reward_label.json @@ -0,0 +1,71 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_escalation_004/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-03 20:20:42", + "label": { + "task_id": "csm_escalation_001", + "domain": "mock_websites", + "summary": "验证 CSM 升级任务:在 Jira 创建 Vertex 集成事故工单、在 Salesforce 创建 Vertex Manufacturing 升级案例、在 Notion 更新健康状态为 Red 并填写 Risk Note、在 Slack 的 acct-vertex 频道以 CSM 身份回复确认事故并给出下次更新时间", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "slack_mock (http://28.7.186.212:8198)", + "jira_mock (http://28.7.186.212:8173)", + "salesforce_mock (http://28.7.186.212:8195)", + "notion_mock (http://28.7.186.212:8186)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.3, + "description": "Jira 中新建了针对 Vertex 集成事故的工单,且包含复现证据、高优先级、真实状态与真实项目", + "check_logic": "对比 jira 的 initial_state 与 current_state 的 issues,筛选出 id 不在初始集合中的新工单。要求新工单的 summary/description 同时包含 'vertex' 与集成/同步/事故相关词;type 为 Bug/Task/Story;priority 为 High/Highest/Critical/Urgent;status 为当前 issues 中已存在的真实选项或预定义集合之一;projectId 属于 current_state 中的真实项目;复现证据通过关键词组合(integration/integrations、sync/sync now、500/error/fails/failed/failure 中至少两项)或包含 repro/reproduce/steps 判定", + "pass_condition": "新增 Jira 工单同时满足:命名 Vertex 事故、类型合法、有复现证据、高优先级、status 真实、项目真实" + }, + { + "name": "Component 2", + "weight": 0.3, + "description": "Salesforce 中在 Vertex Manufacturing 账户下新建了升级案例,优先级高,状态有效", + "check_logic": "对比 salesforce 的 initial_state 与 current_state 的 cases,筛选 caseId 为新的案例,并限制为关联 Vertex Manufacturing(accountId == 'account-1' 或名称/内容包含 'vertex manufacturing')。在候选案例中优先选取 subject/description/type 包含集成/事故相关词的案例;若无则取首个候选。要求该案例 is_vertex_case 为真、priority 为 High/Critical、status 属于允许的真实选项(new/working/escalated/closed/not started/not start/in progress/completed)", + "pass_condition": "新增案例属于 Vertex Manufacturing、优先级 High/Critical、status 为真实 Salesforce 选项" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "Notion 的 Customer Health Tracker 中 Vertex Manufacturing 行 Health 设为 Red 且 Risk Note 非空", + "check_logic": "在 notion current_state 的 pages 中查找 type 为 database 且标题含 'health' 的数据库,再定位标题含 'vertex manufacturing' 的行。读取 Health 属性值要求为 Red;读取 Risk Note 属性值(支持 'risk note' 或名称同时含 risk 与 note 的属性)要求归一化后非空", + "pass_condition": "Vertex Manufacturing 行的 Health 为 Red 且 Risk Note 非空" + }, + { + "name": "Component 4a", + "weight": 0.1, + "description": "Slack 的 acct-vertex 频道中有 CSM(user_1)发送的新消息", + "check_logic": "对比 slack 的 initial_state 与 current_state 中 'acct-vertex' 频道的消息列表,按 messageId 差集找出新增消息;若差集为空但消息总数增加,则取末尾新增部分。筛选 senderId == 'user_1' 的消息,存在即得分", + "pass_condition": "存在至少一条 user_1 在 acct-vertex 频道发送的新消息" + }, + { + "name": "Component 4b", + "weight": 0.1, + "description": "CSM 的 Slack 回复内容确认事故并给出具体的下次更新 ETA", + "check_logic": "取 Component 4a 中最后一条新消息的 content。acknowledgement 通过检测 outage/integration/sync/issue/500/escalat/sorry/flag/disruption/down/received/acknowledge/acknowledged/reported/looking into/investigating/engineering/ticket/incident/blocked/blocking 等关键词判定。concrete next-update ETA 通过多组正则(如具体时间、相对时间窗口、星期、日期格式等)以及基于客户最后消息时间动态生成的未来 7 天日期 token 进行判定", + "pass_condition": "回复内容同时满足:确认/回应事故,且包含具体的下次更新时间或 ETA" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件得分相加,最终通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数", + "failure_modes": [ + "/tmp/task_web_sid 读取失败或为空:打印 CRITICAL 并返回 0.0", + "任一 mock 服务(slack/jira/salesforce/notion)状态拉取失败:打印 CRITICAL 并返回 0.0", + "Jira 无新增 Vertex 集成事故工单或字段校验未通过:Component 1 失败,扣 0.30", + "Salesforce 无新增 Vertex Manufacturing 案例或字段校验未通过:Component 2 失败,扣 0.30", + "Notion 未找到 Vertex Manufacturing 健康行,或 Health 非 Red,或 Risk Note 为空:Component 3 失败,扣 0.20", + "Slack acct-vertex 频道无 CSM(user_1)新回复:Component 4a 失败,扣 0.10", + "CSM 回复未确认事故或未给出下次更新 ETA:Component 4b 失败,扣 0.10" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后通过 HTTP GET 从 slack、jira、salesforce、notion 四个 mock 服务拉取 initial_state 与 current_state,任一服务拉取失败也直接返回 0.0。接着按顺序执行 5 项检查:1)Jira:找新增 Vertex 事故工单,验证类型、复现证据、高优先级、真实状态与项目,通过得 0.30;2)Salesforce:找 Vertex Manufacturing 账户下的新增案例,验证事故相关主题、高优先级与有效状态,通过得 0.30;3)Notion:定位 Customer Health Tracker 的 Vertex Manufacturing 行,验证 Health 为 Red 且 Risk Note 非空,通过得 0.20;4)Slack:对比 acct-vertex 频道消息,验证 CSM(user_1)发了新回复,得 0.10;再对该回复做模式检测,验证其确认事故并给出具体下次更新 ETA,得 0.10。各组件得分累加,最终用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数输出。任一组件异常仅记录 ERROR 或 FAIL,不影响其他组件计分。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n首先,我需要从源码中提取关键信息:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: csm_escalation_004`\n2. **Domain**: 从 docstring 中可以看到 `Domain: mock_websites (multi-mock: slack, jira, salesforce, notion)`\n3. **Summary**: 一句话概括。这个脚本验证 CSM 升级任务:在 Jira 创建 Vertex 集成事故工单、在 Salesforce 创建 Vertex Manufacturing 升级案例、在 Notion 更新健康状态为红色并添加风险备注、在 Slack 的 acct-vertex 频道回复客户确认事故并给出下次更新时间。\n4. **is_placeholder**: false。这个脚本有完整的评分逻辑,不是占位脚本。\n5. **data_sources**: 脚本从 `/tmp/task_web_sid` 读取 sid,然后从多个 mock 服务获取状态:slack (`http://28.7.186.212:8178`)、jira (`http://28.7.186.212:8153`)、salesforce (`http://28.7.186.212:8175`)、notion (`http://28.7.186.212:8166`)。\n6. **scoring_components**:\n - Component 1 (0.30): Jira 新建 Vertex 集成事故工单,包含复现证据、高优先级、真实状态、真实项目。\n - Component 2 (0.30): Salesforce 在 account-1 (Vertex Manufacturing) 新建案例,高优先级,状态有效。\n - Component 3 (0.20): Notion 中 Vertex Manufacturing 健康行 -> Health 为 Red 且 Risk Note 非空。\n - Component 4a (0.10): Slack 中 CSM (user_1) 在 'acct-vertex' 频道的新回复。\n - Component 4b (0.10): 该回复确认故障并给出具体的下次更新时间/ETA。\n\n让我详细分析每个组件的检查逻辑:\n\n**Component 1**:\n- 比较 initial_state 和 current_state 的 issues,找出新创建的 issue。\n- 检查 summary/description 中是否包含 \"vertex\" 以及集成/同步/事故相关词汇。\n- 检查 type 是否为 Bug/Task/Story。\n- 检查是否有复现证据(包含 integration/integrations、sync/sync now、500/error/fails/failed/failure 中至少两个,或包含 repro/reproduce/steps)。\n- 检查 priority 是否为 High/Highest/Critical/Urgent。\n- 检查 status 是否为真实选项(从 current issues 中提取或预定义集合)。\n- 检查 projectId 是否存在于真实项目中。\n- 全部通过得 0.30。\n\n**Component 2**:\n- 比较 initial_state 和 current_state 的 cases,找出新案例。\n- 检查是否关联 Vertex Manufacturing 账户(accountId == 'account-1' 或名称/内容包含 'vertex manufacturing')。\n- 检查 subject/description/type 是否包含集成/同步/事故相关词汇。\n- 检查 priority 是否为 High/Critical。\n- 检查 status 是否为真实 Salesforce 选项(new, working, escalated, closed, not started, not start, in progress, completed)。\n- 全部通过得 0.30。\n\n**Component 3**:\n- 在 Notion 的 current_state.pages 中查找 Customer Health Tracker 数据库。\n- 找到 Vertex Manufacturing 行。\n- 检查 Health 属性是否为 Red。\n- 检查 Risk Note 属性是否非空。\n- 全部通过得 0.20。\n\n**Component 4a**:\n- 比较 Slack initial_state 和 current_state 中 'acct-vertex' 频道的消息。\n- 找出 user_1 (CSM) 发送的新消息。\n- 有新消息得 0.10。\n\n**Component 4b**:\n- 检查 4a 中找到的回复内容。\n- 是否确认问题(包含 outage/integration/sync/issue/500/escalat/sorry 等关键词)。\n- 是否给出下次更新时间/ETA(通过正则表达式匹配时间、相对时间窗口、日期等,或动态生成的日期 token)。\n- 全部通过得 0.10。\n\n**Score aggregation**:\n- 各组件分数相加,最后 `round(min(total_score, 1.0), 4)`。所以是相加并钳制到 1.0。\n\n**Failure modes**:\n- 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n- 从任一 mock 服务获取状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n- 各组件检查失败会打印 FAIL 但不退出,只是不得分。\n- 异常会被捕获并打印 ERROR,不得分。\n\n**Confidence**: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON。注意:\n- 只输出 JSON,不要 Markdown 代码块。\n- 第一个字符是 {,最后一个字符是 }。\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n- weight 填写代码中显式给出的分值。\n\n让我确认每个组件的 weight:\n- Component 1: 0.30\n- Component 2: 0.30\n- Component 3: 0.20\n- Component 4a: 0.10\n- Component 4b: 0.10\n\ntotal_max_score: 1.0\n\nscoring_logic_explanation 需要按执行顺序详细说明。\n\n让我组织中文描述:\n\n脚本首先读取 /tmp/task_web_sid 获取会话 ID;若失败则直接返回 0.0。接着通过 HTTP GET 从 slack、jira、salesforce、notion 四个 mock 服务拉取 initial_state 与 current_state;任一服务拉取失败也直接返回 0.0。\n\n随后逐项检查:\n1. Jira:对比 initial_state 与 current_state 的 issues,找出新增工单。要求新工单 summary/description 同时包含 \"vertex\" 与集成/同步/事故相关词;type 为 Bug/Task/Story;priority 为 High/Highest/Critical/Urgent;status 为真实存在的选项;projectId 对应真实项目;且包含复现证据(特定关键词组合或 repro/reproduce/steps)。通过得 0.30。\n2. Salesforce:对比 cases 找出新增案例,且必须关联 Vertex Manufacturing(account-1)。要求 subject/description/type 包含集成/事故相关词;priority 为 High/Critical;status 为允许的真实选项。通过得 0.30。\n3. Notion:在 current_state 中定位 Customer Health Tracker 数据库的 Vertex Manufacturing 行。要求 Health 字段为 Red,Risk Note 字段非空。通过得 0.20。\n4. Slack:对比 acct-vertex 频道消息,找出 CSM(user_1)发送的新消息。\n - 4a:存在新消息即得 0.10。\n - 4b:取该消息内容,要求同时满足:(a) 通过关键词确认/回应事故;(b) 通过正则与动态日期 token 检测给出具体的下次更新 ETA。通过得 0.10。\n\n各组件得分累加,最终用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数输出。\n\nfailure_modes:\n- /tmp/task_web_sid 读取失败或为空:打印 CRITICAL 并返回 0.0\n- mock 服务状态拉取失败:打印 CRITICAL 并返回 0.0\n- Jira 无新增 Vertex 事故工单:Component 1 失败,不得 0.30\n- Salesforce 无新增 Vertex Manufacturing 案例或字段不符:Component 2 失败,不得 0.30\n- Notion 未找到 Vertex 行或 Health 非 Red / Risk Note 为空:Component 3 失败,不得 0.20\n- Slack 无 CSM 新回复:Component 4a 失败,不得 0.10\n- CSM 回复未确认事故或未给出 ETA:Component 4b 失败,不得 0.10\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记。\n- 不要输出额外解释。\n- 不要输出思考过程。\n- 不要输出 标签。\n- 输出的第一个字符必须是 {,最后一个字符必须是 }。\n\n我需要确保 JSON 是有效的,所有字符串正确转义。\n\n让我再仔细检查一下 Component 1 的 check_logic:\n- names_vertex: 'vertex' in blob\n- names_incident: contains_any(integration, sync, salesforce) AND contains_any(down, outage, fail, failure, error, 500, blocked, blocking, urgent, incident, escalat)\n- good_type: option_in(type, (Bug, Task, Story))\n- has_repro: sum(repro_signals) >= 2 OR contains_any(repro, reproduce, steps)\n - repro_signals: contains_any(integration, integrations), contains_any(sync, sync now), contains_any(500, error, fails, failed, failure)\n- good_priority: option_in(priority, (High, Highest, Critical, Urgent))\n- good_status: option_in(status, allowed_statuses) where allowed_statuses 从 current issues 提取 + {'To Do', 'In Progress', 'In Review', 'Done'}\n- real_project: matched.get('projectId') in real_project_ids\n\nComponent 2:\n- is_vertex_case: account_id == 'account-1' OR 'vertex manufacturing' in account_name OR 'vertex manufacturing' in case_blob\n- candidates: new_cases filtered by is_vertex_case\n- matched: first candidate with subject/description/type containing integration/sync/outage/escalat/incident/down/500/blocked/blocking; if none but candidates exist, matched = candidates[0]\n- good_account: is_vertex_case(matched)\n- good_priority: option_in(priority, (High, Critical))\n- good_status: option_in(status, (new, working, escalated, closed, not started, not start, in progress, completed))\n\nComponent 3:\n- find_vertex_row: find database with 'health' in title, then item with 'vertex manufacturing' in title\n- health_id: name_to_id.get('health')\n- risk_id: name_to_id.get('risk note') or find name containing 'risk' and 'note'\n- health_red: option_in(health_val, ('Red',))\n- risk_ok: bool(norm_text(risk_val))\n\nComponent 4a:\n- init_ids = {m.get('messageId') for m in init_v}\n- added = [m for m in cur_v if m.get('messageId') not in init_ids]\n- if not added and len(cur_v) > len(init_v): added = cur_v[len(init_v):]\n- new_vertex_msgs = [m for m in added if m.get('senderId') == 'user_1']\n\nComponent 4b:\n- reply_text = new_vertex_msgs[-1].get('content') or ''\n- ack: contains_any(outage, integration, sync, issue, 500, escalat, sorry, flag, disruption, down, received, acknowledge, acknowledged, reported, looking into, investigating, engineering, ticket, incident, blocked, blocking)\n- has_eta: has_next_update_eta(reply_text, reference_dt)\n - reference_dt: max customer message timestamps (non-user_1)\n - has_next_update_eta checks various regex patterns and relative_date_tokens\n\n一切看起来都正确。现在生成 JSON。 {\"task_id\": \"csm_escalation_004\", \"domain\": \"mock_websites\", \"summary\": \"验证 CSM 升级任务:在 Jira 创建 Vertex 集成事故工单、在 Salesforce 创建 Vertex Manufacturing 升级案例、在 Notion 更新健康状态为 Red 并填写 Risk Note、在 Slack 的 acct-vertex 频道以 CSM 身份回复确认事故并给出下次更新时间\", \"is_placeholder\": false, \"data_sources\": [\"/tmp/task_web_sid\", \"slack_mock (http://28.7.186.212:8198)\", \"jira_mock (http://28.7.186.212:8173)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"notion_mock (http://28.7.186.212:8186)\"], \"scoring_components\": [{\"name\": \"Component 1\", \"weight\": 0.3, \"description\": \"Jira 中新建了针对 Vertex 集成事故的工单,且包含复现证据、高优先级、真实状态与真实项目\", \"check_logic\": \"对比 jira 的 initial_state 与 current_state 的 issues,筛选出 id 不在初始集合中的新工单。要求新工单的 summary/description 同时包含 'vertex' 与集成/同步/事故相关词;type 为 Bug/Task/Story;priority 为 High/Highest/Critical/Urgent;status 为当前 issues 中已存在的真实选项或预定义集合之一;projectId 属于 current_state 中的真实项目;复现证据通过关键词组合(integration/integrations、sync/sync now、500/error/fails/failed/failure 中至少两项)或包含 repro/reproduce/steps 判定\", \"pass_condition\": \"新增 Jira 工单同时满足:命名 Vertex 事故、类型合法、有复现证据、高优先级、status 真实、项目真实\"}, {\"name\": \"Component 2\", \"weight\": 0.3, \"description\": \"Salesforce 中在 Vertex Manufacturing 账户下新建了升级案例,优先级高,状态有效\", \"check_logic\": \"对比 salesforce 的 initial_state 与 current_state 的 cases,筛选 caseId 为新的案例,并限制为关联 Vertex Manufacturing(accountId == 'account-1' 或名称/内容包含 'vertex manufacturing')。在候选案例中优先选取 subject/description/type 包含集成/事故相关词的案例;若无则取首个候选。要求该案例 is_vertex_case 为真、priority 为 High/Critical、status 属于允许的真实选项(new/working/escalated/closed/not started/not start/in progress/completed)\", \"pass_condition\": \"新增案例属于 Vertex Manufacturing、优先级 High/Critical、status 为真实 Salesforce 选项\"}, {\"name\": \"Component 3\", \"weight\": 0.2, \"description\": \"Notion 的 Customer Health Tracker 中 Vertex Manufacturing 行 Health 设为 Red 且 Risk Note 非空\", \"check_logic\": \"在 notion current_state 的 pages 中查找 type 为 database 且标题含 'health' 的数据库,再定位标题含 'vertex manufacturing' 的行。读取 Health 属性值要求为 Red;读取 Risk Note 属性值(支持 'risk note' 或名称同时含 risk 与 note 的属性)要求归一化后非空\", \"pass_condition\": \"Vertex Manufacturing 行的 Health 为 Red 且 Risk Note 非空\"}, {\"name\": \"Component 4a\", \"weight\": 0.1, \"description\": \"Slack 的 acct-vertex 频道中有 CSM(user_1)发送的新消息\", \"check_logic\": \"对比 slack 的 initial_state 与 current_state 中 'acct-vertex' 频道的消息列表,按 messageId 差集找出新增消息;若差集为空但消息总数增加,则取末尾新增部分。筛选 senderId == 'user_1' 的消息,存在即得分\", \"pass_condition\": \"存在至少一条 user_1 在 acct-vertex 频道发送的新消息\"}, {\"name\": \"Component 4b\", \"weight\": 0.1, \"description\": \"CSM 的 Slack 回复内容确认事故并给出具体的下次更新 ETA\", \"check_logic\": \"取 Component 4a 中最后一条新消息的 content。acknowledgement 通过检测 outage/integration/sync/issue/500/escalat/sorry/flag/disruption/down/received/acknowledge/acknowledged/reported/looking into/investigating/engineering/ticket/incident/blocked/blocking 等关键词判定。concrete next-update ETA 通过多组正则(如具体时间、相对时间窗口、星期、日期格式等)以及基于客户最后消息时间动态生成的未来 7 天日期 token 进行判定\", \"pass_condition\": \"回复内容同时满足:确认/回应事故,且包含具体的下次更新时间或 ETA\"}], \"total_max_score\": 1.0, \"score_aggregation\": \"各组件得分相加,最终通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数\", \"failure_modes\": [\"/tmp/task_web_sid 读取失败或为空:打印 CRITICAL 并返回 0.0\", \"任一 mock 服务(slack/jira/salesforce/notion)状态拉取失败:打印 CRITICAL 并返回 0.0\", \"Jira 无新增 Vertex 集成事故工单或字段校验未通过:Component 1 失败,扣 0.30\", \"Salesforce 无新增 Vertex Manufacturing 案例或字段校验未通过:Component 2 失败,扣 0.30\", \"Notion 未找到 Vertex Manufacturing 健康行,或 Health 非 Red,或 Risk Note 为空:Component 3 失败,扣 0.20\", \"Slack acct-vertex 频道无 CSM(user_1)新回复:Component 4a 失败,扣 0.10\", \"CSM 回复未确认事故或未给出下次更新 ETA:Component 4b 失败,扣 0.10\"], \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后通过 HTTP GET 从 slack、jira、salesforce、notion 四个 mock 服务拉取 initial_state 与 current_state,任一服务拉取失败也直接返回 0.0。接着按顺序执行 5 项检查:1)Jira:找新增 Vertex 事故工单,验证类型、复现证据、高优先级、真实状态与项目,通过得 0.30;2)Salesforce:找 Vertex Manufacturing 账户下的新增案例,验证事故相关主题、高优先级与有效状态,通过得 0.30;3)Notion:定位 Customer Health Tracker 的 Vertex Manufacturing 行,验证 Health 为 Red 且 Risk Note 非空,通过得 0.20;4)Slack:对比 acct-vertex 频道消息,验证 CSM(user_1)发了新回复,得 0.10;再对该回复做模式检测,验证其确认事故并给出具体下次更新 ETA,得 0.10。各组件得分累加,最终用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数输出。任一组件异常仅记录 ERROR 或 FAIL,不影响其他组件计分。\", \"confidence\": 1.0}" +} diff --git a/csm_health_risk_002/_cua_gym_vm_bridge.sh b/csm_health_risk_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csm_health_risk_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/csm_health_risk_002/initial_setup.py b/csm_health_risk_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..11faf29a507d44e25cc9ee753ae42afcdaa2705b --- /dev/null +++ b/csm_health_risk_002/initial_setup.py @@ -0,0 +1,593 @@ +# --- 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: CSM identifies the one Red/declining account in their book and logs risk +Task ID: csm_health_risk_002 +Domain: mock_websites +Mocks: notion_mock, salesforce_mock, slack_mock +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +MOCKS = { + 'notion_mock': 'http://28.7.184.198:8166', + 'salesforce_mock': 'http://28.7.184.198:8175', + 'slack_mock': 'http://28.7.184.198:8178', +} + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid={sid}') + +NOW = '2026-06-20T09:00:00.000Z' + +# --- Network helper: VM egress to the mocks may require a proxy. Probe once, +# then use direct or the cluster proxy for all requests. --- +PROXY = None +PROXIES = None # decided by _probe() + + +def _probe(): + global PROXIES + test = 'http://28.7.184.198:8166/go?sid=conntest' + try: + requests.get(test, timeout=5) + PROXIES = None + print('Network: direct egress works') + return + except requests.exceptions.RequestException: + pass + PROXIES = None + print(f'Network: using proxy {PROXY}') + + +def http_post(url, payload): + return requests.post(url, json=payload, timeout=30, proxies=PROXIES) + + +def http_get(url): + return requests.get(url, timeout=30, proxies=PROXIES) + + +_probe() + + +# ========================================================================= +# NOTION STATE +# ========================================================================= +def build_notion_state(): + user = { + 'id': 'user-1', + 'name': 'Jordan Rivera', + 'email': 'jordan.rivera@northwindcloud.com', + 'avatar': '', + } + workspace = { + 'id': 'ws-1', + 'name': 'Northwind Cloud', + 'icon': '', + 'members': ['user-1'], + } + + db_id = 'db-health' + # Database property definitions + properties = [ + {'id': 'prop-account', 'name': 'Account', 'type': 'title'}, + {'id': 'prop-health', 'name': 'Health', 'type': 'status', + 'options': ['Green', 'Yellow', 'Red']}, + {'id': 'prop-mau', 'name': 'MAU Trend', 'type': 'select', + 'options': ['Up', 'Flat', 'Down']}, + {'id': 'prop-arr', 'name': 'ARR', 'type': 'number'}, + {'id': 'prop-csm', 'name': 'CSM', 'type': 'text'}, + {'id': 'prop-risk', 'name': 'Risk Note', 'type': 'text'}, + ] + + # Each database row is itself a page (item). Properties keyed by prop id. + rows = [ + # (page_id, account, health, mau, arr, csm, risk_note) + ('item-summit', 'Summit Retail Group', 'Red', 'Down', 120000, 'Jordan Rivera', ''), + ('item-cedar', 'Cedar Grove Health', 'Yellow', 'Flat', 95000, 'Jordan Rivera', ''), + ('item-river', 'Riverstone Media', 'Green', 'Up', 64000, 'Jordan Rivera', ''), + ('item-blue', 'BlueHarbor Logistics', 'Yellow', 'Down', 78000, 'Jordan Rivera', ''), + ('item-north', 'Northstar Apparel', 'Red', 'Down', 110000, 'Dana Lee', ''), + ] + + pages = {} + item_ids = [] + for pid, account, health, mau, arr, csm, risk in rows: + item_ids.append(pid) + pages[pid] = { + 'id': pid, + 'title': account, + 'icon': '', + 'cover': None, + 'parentId': db_id, + 'blockIds': [], + 'favorite': False, + 'createdDate': '2026-01-05T00:00:00.000Z', + 'lastEditedDate': '2026-06-01T00:00:00.000Z', + 'properties': { + 'prop-account': account, + 'prop-health': health, + 'prop-mau': mau, + 'prop-arr': arr, + 'prop-csm': csm, + 'prop-risk': risk, + }, + } + + # The database page itself + pages[db_id] = { + 'id': db_id, + 'title': 'Customer Health Tracker', + 'icon': '', + 'cover': None, + 'parentId': None, + 'type': 'database', + 'viewType': 'table', + 'properties': properties, + 'views': [{ + 'id': 'view-1', + 'name': 'All Accounts', + 'type': 'table', + 'filters': [], + 'sorts': [], + 'groupBy': None, + 'visibleProperties': ['prop-account', 'prop-health', 'prop-mau', + 'prop-arr', 'prop-csm', 'prop-risk'], + }], + 'items': item_ids, + 'blockIds': [], + 'favorite': True, + 'createdDate': '2026-01-05T00:00:00.000Z', + } + + return { + 'user': user, + 'workspace': workspace, + 'pages': pages, + 'blocks': {}, + 'trash': [], + 'comments': {}, + 'settings': {'appearance': 'light', 'startWeekMonday': False, 'fontSize': 'default'}, + 'notifications': [], + 'pageOrder': [db_id], + 'focusBlockId': None, + } + + +# ========================================================================= +# SALESFORCE STATE +# ========================================================================= +def build_salesforce_state(): + user = { + 'userId': 'user-1', + 'firstName': 'Jordan', + 'lastName': 'Rivera', + 'email': 'jordan.rivera@northwindcloud.com', + 'phone': '(555) 204-7781', + 'title': 'Customer Success Manager', + 'department': 'Customer Success', + 'role': 'Manager', + 'avatar': 'https://i.pravatar.cc/150?u=user-1', + 'timezone': 'America/New_York', + 'locale': 'en-US', + 'theme': 'lightning', + } + users = [ + user, + {'userId': 'user-2', 'firstName': 'Dana', 'lastName': 'Lee', + 'email': 'dana.lee@northwindcloud.com', 'phone': '(555) 204-7782', + 'title': 'Customer Success Manager', 'department': 'Customer Success', + 'role': 'Manager', 'avatar': 'https://i.pravatar.cc/150?u=user-2', + 'timezone': 'America/Los_Angeles', 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'user-3', 'firstName': 'Priya', 'lastName': 'Nair', + 'email': 'priya.nair@northwindcloud.com', 'phone': '(555) 204-7783', + 'title': 'Account Executive', 'department': 'Sales', + 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=user-3', + 'timezone': 'America/Chicago', 'locale': 'en-US', 'theme': 'lightning'}, + ] + + def acct(aid, name, atype, industry, revenue, employees, owner): + return { + 'accountId': aid, 'name': name, 'type': atype, 'industry': industry, + 'revenue': revenue, 'employees': employees, 'ownerId': owner, + 'billingStreet': '', 'billingCity': '', 'billingState': '', + 'billingZip': '', 'billingCountry': 'USA', + 'shippingStreet': '', 'shippingCity': '', 'shippingState': '', + 'shippingZip': '', 'shippingCountry': 'USA', + 'phone': '', 'website': '', + 'createdDate': '2025-09-01T00:00:00.000Z', + 'modifiedDate': '2026-05-01T00:00:00.000Z', + } + + accounts = [ + acct('account-1', 'Summit Retail Group', 'Customer', 'Retail', 4200000, 540, 'user-1'), + acct('account-2', 'Cedar Grove Health', 'Customer', 'Healthcare', 3100000, 410, 'user-1'), + acct('account-3', 'Riverstone Media', 'Customer', 'Media', 1800000, 220, 'user-1'), + acct('account-4', 'Northstar Apparel', 'Customer', 'Apparel', 2600000, 300, 'user-2'), + acct('account-5', 'BlueHarbor Logistics', 'Customer', 'Logistics', 2900000, 360, 'user-1'), + ] + + # Default-style activities, NONE referencing Summit churn/usage risk. + activities = [ + {'activityId': 'activity-1', 'type': 'task', + 'subject': 'Quarterly business review prep — Riverstone Media', + 'status': 'Open', 'priority': 'Normal', 'dueDate': '2026-07-01', + 'relatedToType': 'account', 'relatedToId': 'account-3', 'assignedToId': 'user-1'}, + {'activityId': 'activity-2', 'type': 'event', + 'subject': 'Onboarding sync — Cedar Grove Health', + 'status': 'Open', 'priority': 'Normal', + 'startDateTime': '2026-06-25T15:00:00.000Z', + 'endDateTime': '2026-06-25T15:30:00.000Z', + 'relatedToType': 'account', 'relatedToId': 'account-2', 'assignedToId': 'user-1'}, + {'activityId': 'activity-3', 'type': 'task', + 'subject': 'Send renewal paperwork — BlueHarbor Logistics', + 'status': 'Open', 'priority': 'Normal', 'dueDate': '2026-07-10', + 'relatedToType': 'account', 'relatedToId': 'account-5', 'assignedToId': 'user-1'}, + {'activityId': 'activity-4', 'type': 'task', + 'subject': 'Update contact roster — Northstar Apparel', + 'status': 'Completed', 'priority': 'Low', 'dueDate': '2026-06-10', + 'relatedToType': 'account', 'relatedToId': 'account-4', 'assignedToId': 'user-2'}, + ] + + return { + 'user': user, + 'users': users, + 'leads': [], + 'accounts': accounts, + 'contacts': [], + 'opportunities': [], + 'cases': [], + 'activities': activities, + 'chatterPosts': [], + 'files': [], + 'following': [], + 'recentlyViewed': [], + 'dismissedNotifications': [], + } + + +# ========================================================================= +# SLACK STATE +# ========================================================================= +def build_slack_state(): + current_user = { + 'userId': 'user_1', 'fullName': 'Jordan Rivera', 'displayName': 'Jordan', + 'email': 'jordan.rivera@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Customer Success Manager', + 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York', + } + users = [ + current_user, + {'userId': 'user_2', 'fullName': 'Dana Lee', 'displayName': 'Dana', + 'email': 'dana.lee@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Customer Success Manager', + 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + {'userId': 'user_3', 'fullName': 'Priya Nair', 'displayName': 'Priya', + 'email': 'priya.nair@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Account Executive', + 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'}, + ] + + def channel(cid, name, desc, members): + return { + 'channelId': cid, 'name': name, 'description': desc, 'topic': '', + 'isPrivate': False, 'isStarred': False, 'members': members, + 'createdBy': 'user_1', 'createdAt': '2026-01-02T10:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0, + } + + channels = [ + channel('general', 'general', 'Company-wide announcements', ['user_1', 'user_2', 'user_3']), + channel('random', 'random', 'Non-work banter', ['user_1', 'user_2', 'user_3']), + channel('customer-success', 'customer-success', 'CS team coordination', ['user_1', 'user_2']), + channel('acct-summit-retail', 'acct-summit-retail', + 'Account channel for Summit Retail Group', ['user_1', 'user_3']), + channel('acct-northstar', 'acct-northstar', + 'Account channel for Northstar Apparel', ['user_2', 'user_3']), + ] + + def msg(mid, sender, content, ts): + return { + 'messageId': mid, 'senderId': sender, 'content': content, + 'timestamp': ts, 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False, + } + + messages = { + 'general': [ + msg('msg_g1', 'user_2', 'Morning all — reminder that QBR season kicks off next week.', + '2026-06-18T13:02:00Z'), + msg('msg_g2', 'user_3', 'Thanks Dana, calendars are going out today.', + '2026-06-18T13:05:00Z'), + ], + 'random': [ + msg('msg_r1', 'user_3', 'Coffee machine on 4th floor is fixed.', + '2026-06-17T16:20:00Z'), + ], + 'customer-success': [ + msg('msg_cs1', 'user_2', 'Let me know if anyone needs help with renewals this quarter.', + '2026-06-19T14:00:00Z'), + ], + 'acct-summit-retail': [ + msg('msg_sr1', 'user_3', 'Welcome to the Summit Retail Group account channel.', + '2026-01-02T10:30:00Z'), + msg('msg_sr2', 'user_1', 'Adding our latest usage dashboard link to the bookmarks.', + '2026-05-12T11:15:00Z'), + ], + 'acct-northstar': [ + msg('msg_ns1', 'user_2', 'Northstar Apparel account channel — main contact is Alex Moreno.', + '2026-01-03T09:00:00Z'), + ], + } + + return { + 'currentUser': current_user, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind Cloud', 'icon': ''}, + 'users': users, + 'channels': channels, + 'messages': messages, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + } + + +# ========================================================================= +# INJECT +# ========================================================================= +builders = { + 'notion_mock': build_notion_state, + 'salesforce_mock': build_salesforce_state, + 'slack_mock': build_slack_state, +} + +for name, url in MOCKS.items(): + state = builders[name]() + resp = http_post(f'{url}/post?sid={sid}', {'action': 'set', 'state': state}) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + go = http_get(f'{url}/go?sid={sid}').json() + assert go.get('initial_state') is not None, f'{name}: initial_state is None after injection' + print(f'Injected {name}: sid={sid}') + +print('All mock states injected successfully.') + + +# ========================================================================= +# GUI-READY: launch browser tabs for all three mocks +# ========================================================================= +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 +launch_gui(f'google-chrome "{MOCKS["notion_mock"]}/?sid={sid}"', delay_sec=2.5) +launch_gui(f'google-chrome "{MOCKS["salesforce_mock"]}/?sid={sid}"', delay_sec=2.0) +launch_gui(f'google-chrome "{MOCKS["slack_mock"]}/?sid={sid}"', delay_sec=2.0) +wait_mocks_loaded() +print('GUI_READY: launched Chrome tabs for notion, salesforce, slack with DISPLAY=:0') diff --git a/csm_health_risk_002/reward.py b/csm_health_risk_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..828b2eb551656fca11ae56f09ccd04ce17f13067 --- /dev/null +++ b/csm_health_risk_002/reward.py @@ -0,0 +1,399 @@ +# --- 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: CSM logs churn risk for the one Red+declining account in their book + (Summit Retail Group) across Notion, Salesforce, and Slack. +Task ID: csm_health_risk_002 +Domain: mock_websites (multi-mock: notion_mock, salesforce_mock, slack_mock) + +Scoring (1.0 total, 100% PROGRAMMATIC — LLM judge intentionally NOT used): + Component 1 — Notion Risk Note on Jordan Rivera's Summit Retail Group row (0.34) + 0.17 item-summit 'Risk Note' went blank -> non-empty, AND every OTHER + account row's Risk Note remains blank, with the row owned by Jordan Rivera + 0.17 the note content explains the risk (declining/Down usage + Red/churn) + Component 2 — Salesforce risk task on Jordan Rivera's account-1 (0.33) + 0.13 at least one new task (type 'task') added to activities + 0.20 the new task: relatedToType 'account', relatedToId 'account-1', + account owner/assignedToId 'user-1' (Jordan Rivera), + status != 'Completed', and text indicates health/risk or usage decline + Component 3 — Slack heads-up from Jordan Rivera in acct-summit-retail (0.33) + 0.13 a new message in 'acct-summit-retail', AND 'acct-northstar' + and 'general' untouched, sent by 'user_1' Jordan Rivera + 0.20 the message names Summit, states Red/at-risk + declining usage, + and gives a next step or owner + +All checks are anchored to the initial->current delta so reward(initial_env)==0.0. +""" +import os +import re +import sys + +import requests + +CURRENT_USER_NAME = 'Jordan Rivera' +NOTION_USER_ID = 'user-1' +SALESFORCE_USER_ID = 'user-1' +SLACK_USER_ID = 'user_1' +TARGET_NOTION_ITEM_ID = 'item-summit' +TARGET_ACCOUNT_ID = 'account-1' +TARGET_SLACK_CHANNEL_ID = 'acct-summit-retail' + +# --------------------------------------------------------------------------- +# Read sid +# --------------------------------------------------------------------------- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +MOCKS = { + 'notion': 'http://28.7.184.198:8166', + 'salesforce': 'http://28.7.184.198:8175', + 'slack': 'http://28.7.184.198:8178', +} + +# --------------------------------------------------------------------------- +# Egress proxy helper (MANDATORY in this cluster — direct egress to +# *.xlang.ai fails from inside the Docker VMs) +# --------------------------------------------------------------------------- +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 + + +def fetch_state(name, url): + """Return (initial_state, current_state) dicts for a mock, or (None, None).""" + proxy = resolve_proxy(f'{url}/go?sid=conn-probe') + proxies = {'http': proxy, 'https': proxy} if proxy else None + resp = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=proxies) + resp.raise_for_status() + data = resp.json() + return data.get('initial_state') or {}, data.get('current_state') or {} + + +# --------------------------------------------------------------------------- +# Fetch all three mocks up front; any failure -> 0.0 +# --------------------------------------------------------------------------- +states = {} +try: + for name, url in MOCKS.items(): + init, curr = fetch_state(name, url) + if not curr: + print(f'CRITICAL: current_state empty for {name}') + print('REWARD: 0.0') + sys.exit(0) + states[name] = (init, curr) +except Exception as e: + print(f'CRITICAL: Cannot fetch combined mock state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def value_text(value): + """Return a comparable text value for raw or lightly typed mock fields.""" + if value is None: + return '' + if isinstance(value, str): + return value + if isinstance(value, (int, float, bool)): + return str(value) + if isinstance(value, dict): + parts = [] + for key in ('name', 'label', 'title', 'text', 'content', 'value', 'id'): + if key in value: + parts.append(value_text(value.get(key))) + if not parts: + parts = [value_text(v) for v in value.values()] + return ' '.join(p for p in parts if p) + if isinstance(value, list): + return ' '.join(value_text(v) for v in value) + return str(value) + + +def normalize(text): + text = value_text(text).lower() + text = text.replace('&', ' and ') + text = re.sub(r'[_\-/]+', ' ', text) + text = re.sub(r'\s+', ' ', text) + return text.strip() + + +def has_any(text, keywords): + low = normalize(text) + return any(k in low for k in keywords) + + +# Keyword groups. These intentionally allow common UI/text variations while +# still anchoring on the requested customer, health/risk, and next action. +JORDAN_KW = ['jordan rivera', 'jordan'] +ACCOUNT_KW = ['summit retail group', 'summit', 'srg'] +USAGE_DECLINE_KW = [ + 'declin', 'down', 'drop', 'decreas', 'fall', 'low', 'lower', 'slip', + 'slipped', 'usage', 'mau', 'adoption', 'engagement', 'activity', + 'utilization', +] +RED_RISK_KW = [ + 'red', 'at risk', 'atrisk', 'risk', 'churn', 'retention', 'health', + 'unhealthy', 'critical', 'escalat', 'renewal concern', +] +NEXTSTEP_KW = [ + 'next step', 'check in', 'checkin', 'recovery', 'recover', 'plan', + 'schedul', 'owner', 'will', 'follow up', 'followup', 'escalat', + 'meeting', 'reach out', 'contact', 'action', 'mitigat', 'sync', +] + + +def is_jordan_name(text): + return has_any(text, JORDAN_KW) + + +def mentions_account(text): + return has_any(text, ACCOUNT_KW) + + +def mentions_usage_decline(text): + return has_any(text, USAGE_DECLINE_KW) + + +def mentions_red_or_risk(text): + return has_any(text, RED_RISK_KW) + + +def new_records(initial, current, id_key): + init_ids = {item.get(id_key) for item in (initial or []) if item.get(id_key)} + added = [item for item in (current or []) if item.get(id_key) not in init_ids] + if added or init_ids: + return added + return (current or [])[len(initial or []):] + + +def verify_task(): + total_score = 0.0 + + # ===================================================================== + # Component 1 — Notion Risk Note on Summit Retail Group (0.34) + # ===================================================================== + try: + n_init, n_curr = states['notion'] + init_pages = n_init.get('pages', {}) + curr_pages = n_curr.get('pages', {}) + + notion_user = n_curr.get('user', {}) + current_user_is_jordan = ( + notion_user.get('id') == NOTION_USER_ID + and is_jordan_name(notion_user.get('name')) + ) + + summit = curr_pages.get(TARGET_NOTION_ITEM_ID, {}) + summit_props = summit.get('properties', {}) + summit_risk = value_text(summit_props.get('prop-risk')).strip() + summit_owner = value_text(summit_props.get('prop-csm')).strip() + summit_init_risk = ( + value_text( + init_pages.get(TARGET_NOTION_ITEM_ID, {}) + .get('properties', {}) + .get('prop-risk') + ) + ).strip() + summit_owned_by_jordan = is_jordan_name(summit_owner) + + # Other rows that MUST stay blank (negative constraint) + other_ids = ['item-cedar', 'item-river', 'item-blue', 'item-north'] + others_blank = all( + value_text( + curr_pages.get(pid, {}).get('properties', {}).get('prop-risk') + ).strip() == '' + for pid in other_ids + ) + other_csm_unchanged = all( + normalize(curr_pages.get(pid, {}).get('properties', {}).get('prop-csm')) == + normalize(init_pages.get(pid, {}).get('properties', {}).get('prop-csm')) + for pid in other_ids + ) + + # 1a (0.17): Jordan's summit note newly non-empty AND others untouched + if (current_user_is_jordan and summit_owned_by_jordan and summit_init_risk == '' + and summit_risk != '' and others_blank and other_csm_unchanged): + print('PASS: Notion Jordan-owned Summit Risk Note filled, other rows untouched (0.17)') + total_score += 0.17 + else: + print(f'FAIL: Notion 1a — summit_init={summit_init_risk!r} ' + f'summit_now={summit_risk!r} current_user_is_jordan={current_user_is_jordan} ' + f'summit_owner={summit_owner!r} others_blank={others_blank} ' + f'other_csm_unchanged={other_csm_unchanged}') + + # 1b (0.17): note content explains the risk + if summit_risk != '' and mentions_usage_decline(summit_risk) and mentions_red_or_risk(summit_risk): + print('PASS: Notion Risk Note explains declining usage + red/churn risk (0.17)') + total_score += 0.17 + else: + print(f'FAIL: Notion 1b — content does not name decline+red/churn: {summit_risk!r}') + except Exception as e: + print(f'ERROR: Component 1 (Notion) — {e}') + + # ===================================================================== + # Component 2 — Salesforce risk task on account-1 (0.33) + # ===================================================================== + try: + s_init, s_curr = states['salesforce'] + sf_user = s_curr.get('user', {}) + current_user_is_jordan = ( + sf_user.get('userId') == SALESFORCE_USER_ID + and is_jordan_name(f'{sf_user.get("firstName", "")} {sf_user.get("lastName", "")}') + ) + accounts_by_id = {a.get('accountId'): a for a in (s_curr.get('accounts', []) or [])} + target_account = accounts_by_id.get(TARGET_ACCOUNT_ID, {}) + target_account_owned_by_jordan = target_account.get('ownerId') == SALESFORCE_USER_ID + + init_acts = s_init.get('activities', []) or [] + curr_acts = s_curr.get('activities', []) or [] + new_acts = new_records(init_acts, curr_acts, 'activityId') + new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'] + + # 2a (0.13): at least one new task added + if len(new_tasks) >= 1: + print('PASS: Salesforce — at least one new task added (0.13)') + total_score += 0.13 + else: + print(f'FAIL: Salesforce 2a — expected a new task, found {len(new_tasks)} ' + f'(new activities: {[a.get("activityId") for a in new_acts]})') + + # 2b (0.20): the new task is the Summit churn-risk task with correct fields + risk_task = None + for t in new_tasks: + task_text = ' '.join( + value_text(t.get(k)) + for k in ('subject', 'description', 'comments', 'body') + ) + related_to_target = t.get('relatedToId') == TARGET_ACCOUNT_ID + if related_to_target and ( + mentions_red_or_risk(task_text) + or mentions_usage_decline(task_text)): + risk_task = t + break + if risk_task is not None: + status = normalize(risk_task.get('status')) + checks = { + 'current user=Jordan Rivera': current_user_is_jordan, + 'account.ownerId=user-1 (Jordan Rivera)': target_account_owned_by_jordan, + 'relatedToType=account': normalize(risk_task.get('relatedToType')) == 'account', + 'relatedToId=account-1': risk_task.get('relatedToId') == TARGET_ACCOUNT_ID, + 'assignedToId=user-1 (Jordan Rivera)': risk_task.get('assignedToId') == SALESFORCE_USER_ID, + 'status!=Completed': status != 'completed', + } + if all(checks.values()): + print('PASS: Salesforce risk task fields correct ' + f'(subject={risk_task.get("subject")!r}) (0.20)') + total_score += 0.20 + else: + failed = [k for k, v in checks.items() if not v] + print(f'FAIL: Salesforce 2b — task field mismatch: {failed} ' + f'(task={risk_task})') + else: + print('FAIL: Salesforce 2b — no new account-1 task with risk/usage context found') + except Exception as e: + print(f'ERROR: Component 2 (Salesforce) — {e}') + + # ===================================================================== + # Component 3 — Slack heads-up in acct-summit-retail (0.33) + # ===================================================================== + try: + sl_init, sl_curr = states['slack'] + slack_user = sl_curr.get('currentUser', {}) + current_user_is_jordan = ( + slack_user.get('userId') == SLACK_USER_ID + and is_jordan_name(slack_user.get('fullName')) + ) + init_msgs = sl_init.get('messages', {}) or {} + curr_msgs = sl_curr.get('messages', {}) or {} + + summit_init = init_msgs.get(TARGET_SLACK_CHANNEL_ID, []) or [] + summit_curr = curr_msgs.get(TARGET_SLACK_CHANNEL_ID, []) or [] + new_summit = new_records(summit_init, summit_curr, 'messageId') + jordan_messages = [m for m in new_summit if m.get('senderId') == SLACK_USER_ID] + sent_by_jordan = len(jordan_messages) >= 1 + + # negative constraints: acct-northstar and general unchanged + north_unchanged = not new_records( + init_msgs.get('acct-northstar', []) or [], + curr_msgs.get('acct-northstar', []) or [], + 'messageId', + ) + general_unchanged = not new_records( + init_msgs.get('general', []) or [], + curr_msgs.get('general', []) or [], + 'messageId', + ) + + # 3a (0.13): new message in summit channel from Jordan + others untouched + if (current_user_is_jordan and len(new_summit) >= 1 + and sent_by_jordan and north_unchanged and general_unchanged): + print('PASS: Slack — Jordan message in acct-summit-retail, ' + 'northstar+general untouched (0.13)') + total_score += 0.13 + else: + print(f'FAIL: Slack 3a — summit init={len(summit_init)} curr={len(summit_curr)} ' + f'current_user_is_jordan={current_user_is_jordan} sent_by_jordan={sent_by_jordan} ' + f'north_unchanged={north_unchanged} general_unchanged={general_unchanged}') + + # 3b (0.20): the new message names Summit + Red/at-risk + declining usage + next step + matched = None + for m in jordan_messages: + txt = m.get('content') + if (mentions_account(txt) + and mentions_red_or_risk(txt) + and mentions_usage_decline(txt) + and has_any(txt, NEXTSTEP_KW)): + matched = m + break + if matched is not None: + print('PASS: Slack message names Summit, Red/at-risk, declining usage, next step (0.20)') + total_score += 0.20 + else: + print(f'FAIL: Slack 3b — new message(s) do not cover Summit+red+declining+nextstep: ' + f'{[m.get("content") for m in new_summit]}') + except Exception as e: + print(f'ERROR: Component 3 (Slack) — {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/csm_health_risk_002/reward_label.json b/csm_health_risk_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..20cf12dd0c5fbfa65885dc68a581d913df54e863 --- /dev/null +++ b/csm_health_risk_002/reward_label.json @@ -0,0 +1,76 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_health_risk_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 20:20:27", + "label": { + "task_id": "csm_health_risk_002", + "domain": "mock_websites", + "summary": "验证 CSM Jordan Rivera 是否在 Notion、Salesforce 和 Slack 三个系统中正确记录了 Summit Retail Group 账户的流失风险(Red 状态且使用衰退)。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "notion_mock (http://28.7.186.212:8186)", + "salesforce_mock (http://28.7.186.212:8195)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Component 1a — Notion Summit 风险笔记创建", + "weight": 0.17, + "description": "检查 Notion 中 Jordan Rivera 拥有的 Summit Retail Group 行(item-summit)的 Risk Note 从空白变为非空,且其他账户行的 Risk Note 保持空白、CSM 未改动", + "check_logic": "current_user_is_jordan 为真;summit_owned_by_jordan 为真;summit_init_risk == '' 且 summit_risk != '';others_blank 为真(item-cedar/river/blue/north 的 prop-risk 均为空);other_csm_unchanged 为真", + "pass_condition": "当前用户是 Jordan Rivera;item-summit 的 prop-risk 初始为空且当前非空;该行 CSM 属于 Jordan;其余四行账户的 prop-risk 仍为空且 CSM 与初始状态一致" + }, + { + "name": "Component 1b — Notion 风险笔记内容", + "weight": 0.17, + "description": "检查 Summit Retail Group 的 Risk Note 内容是否解释了使用衰退和 Red/流失风险", + "check_logic": "summit_risk != '' 且 mentions_usage_decline(summit_risk) 返回真且 mentions_red_or_risk(summit_risk) 返回真", + "pass_condition": "笔记非空,且文本经 normalize 后同时包含 decline/down/drop 等使用衰退关键词和 red/at risk/churn 等风险关键词" + }, + { + "name": "Component 2a — Salesforce 新增任务", + "weight": 0.13, + "description": "检查 Salesforce 的 activities 中是否至少新增了一条 type 为 'task' 的记录", + "check_logic": "对比 initial 和 current 的 activities 列表(按 activityId 去重),new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'],要求 len(new_tasks) >= 1", + "pass_condition": "至少存在一条新增 activity,其 type 字段归一化后为 'task'" + }, + { + "name": "Component 2b — Salesforce 风险任务字段", + "weight": 0.2, + "description": "检查新增任务是否针对 account-1、字段正确且文本体现健康风险或使用衰退", + "check_logic": "遍历 new_tasks,拼接 subject/description/comments/body 为 task_text;找到 relatedToId == 'account-1' 且 (mentions_red_or_risk(task_text) 或 mentions_usage_decline(task_text)) 的任务;再校验 current_user_is_jordan、target_account_owned_by_jordan、relatedToType 归一化后为 'account'、assignedToId == 'user-1'、status 归一化后 != 'completed'", + "pass_condition": "新增任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、当前用户为 Jordan、账户所有者为 Jordan,且任务文本包含风险或使用衰退关键词" + }, + { + "name": "Component 3a — Slack 频道消息", + "weight": 0.13, + "description": "检查 Jordan Rivera 是否在 acct-summit-retail 频道发送了新消息,且 acct-northstar 和 general 频道未被改动", + "check_logic": "current_user_is_jordan 为真;new_records(summit_init, summit_curr, 'messageId') 非空且其中至少一条 senderId == 'user_1';new_records 对 acct-northstar 和 general 返回空列表(north_unchanged 和 general_unchanged 为真)", + "pass_condition": "当前 Slack 用户为 Jordan;acct-summit-retail 频道有新增消息且由 user_1 发送;acct-northstar 和 general 频道无新增消息" + }, + { + "name": "Component 3b — Slack 消息内容", + "weight": 0.2, + "description": "检查新消息是否提到 Summit、Red/风险、使用衰退,并给出下一步或负责人", + "check_logic": "遍历 jordan_messages,检查 m.get('content') 同时满足 mentions_account(txt)、mentions_red_or_risk(txt)、mentions_usage_decline(txt)、has_any(txt, NEXTSTEP_KW)", + "pass_condition": "消息内容经 normalize 后同时包含 Summit 相关关键词、Red/风险关键词、使用衰退关键词以及 next step/owner/action 等下一步关键词" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各子组件分数直接相加,最终通过 min(total_score, 1.0) 钳制上限为 1.0,再四舍五入保留 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0", + "从任一 mock 服务获取状态失败或 current_state 为空:打印 CRITICAL 并返回 0.0", + "Notion 检查中当前用户非 Jordan、Summit 行未新建 Risk Note、其他行被改动:Component 1 不得分", + "Salesforce 中未新增 task 类型活动,或新增任务字段不匹配 account-1/非 Completed/未分配 Jordan:Component 2 不得分", + "Slack 中 acct-summit-retail 无 Jordan 的新消息,或其他频道被发送消息:Component 3 不得分", + "各组件内部异常被捕获为 ERROR,仅影响该组件得分,不会导致整体提前退出" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后通过 HTTP 请求向 notion_mock、salesforce_mock、slack_mock 三个服务的 /go?sid={sid} 端点拉取 initial_state 与 current_state,任一拉取失败或 current_state 为空即返回 0.0。接着进入 verify_task():Component 1 针对 Notion,检查 item-summit 的 prop-risk 是否由 Jordan 从空白填为有效内容(0.17),并验证内容包含使用衰退与 Red/流失风险语义(0.17),同时要求其余四行账户的 Risk Note 仍为空白且 CSM 未变;Component 2 针对 Salesforce,对比 activities 列表找出新增 task,至少一条新增 task 得 0.13,再验证该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed 且文本含风险/衰退语义得 0.20;Component 3 针对 Slack,检查 acct-summit-retail 频道有 Jordan 发送的新消息且 acct-northstar 与 general 频道无变动得 0.13,再验证消息内容同时提及 Summit、Red/风险、使用衰退及下一步行动得 0.20。所有子项得分累加后,以 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数作为最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: csm_health_risk_001\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock: notion_mock, salesforce_mock, slack_mock)\",所以 domain 是 mock_websites\n3. **summary**: 一句话概括。这个脚本是验证 CSM (Customer Success Manager) Jordan Rivera 是否在 Notion、Salesforce 和 Slack 中正确记录了 Summit Retail Group 这个红标/衰退客户的风险信息。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: 脚本从以下数据源获取状态:\n - `/tmp/task_web_sid` (读取 sid)\n - `http://28.7.186.212:8166` (notion mock)\n - `http://28.7.186.212:8175` (salesforce mock)\n - `http://28.7.186.212:8178` (slack mock)\n 通过 `/go?sid={sid}` 端点获取 initial_state 和 current_state。\n\n6. **scoring_components**:\n - Component 1: Notion Risk Note (0.34 total)\n - 1a (0.17): 检查当前用户是 Jordan Rivera,Summit Retail Group 行 (item-summit) 的 Risk Note (prop-risk) 从空变为非空,且其他行 (item-cedar, item-river, item-blue, item-north) 的 Risk Note 保持空白,且其他行的 CSM 未改变。\n - 1b (0.17): Risk Note 内容提到 usage decline 和 red/churn risk。\n - Component 2: Salesforce risk task (0.33 total)\n - 2a (0.13): 至少添加了一个新的 task 类型活动。\n - 2b (0.20): 新任务关联到 account-1,relatedToType 是 account,assignedToId 是 user-1 (Jordan),状态不是 Completed,且文本提到 health/risk 或 usage decline。\n - Component 3: Slack heads-up (0.33 total)\n - 3a (0.13): 在 acct-summit-retail 频道有 Jordan 发送的新消息,且 acct-northstar 和 general 频道未改变。\n - 3b (0.20): 消息提到 Summit、Red/at-risk、declining usage,并给出 next step/owner。\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后 `round(min(total_score, 1.0), 4)`,所以是相加后钳制到上限 1.0。\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取 mock 状态失败或 current_state 为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件内部异常会被捕获并打印 ERROR,但不会导致提前退出,只是该组件不得分。\n - 注意:如果检查条件不满足,只是不加分,不会提前退出。\n\n10. **scoring_logic_explanation**: 需要详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 然后依次从 notion、salesforce、slack 三个 mock 服务获取 initial_state 和 current_state,通过 /go?sid={sid} 端点,任何失败或 current_state 为空则返回 0.0。\n - 接着计算总分:\n - Component 1 (Notion): 检查 item-summit 的 prop-risk 从空变非空且由 Jordan 拥有,其他行未动 (0.17);再检查内容包含 decline 和 red/risk 关键词 (0.17)。\n - Component 2 (Salesforce): 检查 activities 中新增至少一个 task 类型记录 (0.13);再检查该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、文本包含 risk/usage decline (0.20)。\n - Component 3 (Slack): 检查 acct-summit-retail 频道有 Jordan 发送的新消息且其他频道未变 (0.13);再检查消息内容提到 Summit、Red/at-risk、declining usage 和 next step (0.20)。\n - 最后将各组件得分累加,用 min(total_score, 1.0) 钳制上限,四舍五入到 4 位小数输出。\n\n11. **confidence**: 1.0,因为代码逻辑非常清晰完整。\n\n现在构建 JSON。注意:\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n- 不要输出 Markdown 代码块标记。\n- 不要输出额外解释。\n- 不要输出思考过程。\n- 第一个字符必须是 {,最后一个字符必须是 }。\n\n让我仔细构造每个字段:\n\ntask_id: \"csm_health_risk_001\"\ndomain: \"mock_websites\"\nsummary: \"验证 CSM Jordan Rivera 是否在 Notion、Salesforce 和 Slack 三个系统中正确记录了 Summit Retail Group 账户的流失风险(Red 状态且使用衰退)。\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"notion_mock (http://28.7.186.212:8186)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"slack_mock (http://28.7.186.212:8198)\"]\n\nscoring_components:\n- name: \"Component 1a — Notion Summit 风险笔记创建\"\n weight: 0.17\n description: \"检查 Notion 中 Jordan Rivera 拥有的 Summit Retail Group 行(item-summit)的 Risk Note 从空白变为非空,且其他账户行的 Risk Note 保持空白、CSM 未改动\"\n check_logic: \"current_user_is_jordan 为真;summit_owned_by_jordan 为真;summit_init_risk == '' 且 summit_risk != '';others_blank 为真(item-cedar/river/blue/north 的 prop-risk 均为空);other_csm_unchanged 为真\"\n pass_condition: \"当前用户是 Jordan Rivera;item-summit 的 prop-risk 初始为空且当前非空;该行 CSM 属于 Jordan;其余四行 prop-risk 仍为空且 CSM 与初始状态一致\"\n\n- name: \"Component 1b — Notion 风险笔记内容\"\n weight: 0.17\n description: \"检查 Summit Retail Group 的 Risk Note 内容是否解释了使用衰退和 Red/流失风险\"\n check_logic: \"summit_risk != '' 且 mentions_usage_decline(summit_risk) 返回真且 mentions_red_or_risk(summit_risk) 返回真\"\n pass_condition: \"笔记非空,且文本经 normalize 后同时包含 decline/down/drop 等使用衰退关键词和 red/at risk/churn 等风险关键词\"\n\n- name: \"Component 2a — Salesforce 新增任务\"\n weight: 0.13\n description: \"检查 Salesforce 的 activities 中是否至少新增了一条 type 为 'task' 的记录\"\n check_logic: \"对比 initial 和 current 的 activities 列表(按 activityId 去重),new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'],要求 len(new_tasks) >= 1\"\n pass_condition: \"至少存在一条新增 activity,其 type 字段归一化后为 'task'\"\n\n- name: \"Component 2b — Salesforce 风险任务字段\"\n weight: 0.20\n description: \"检查新增任务是否针对 account-1、字段正确且文本体现健康风险或使用衰退\"\n check_logic: \"遍历 new_tasks,拼接 subject/description/comments/body 为 task_text;找到 relatedToId == 'account-1' 且 (mentions_red_or_risk(task_text) 或 mentions_usage_decline(task_text)) 的任务;再校验 current_user_is_jordan、target_account_owned_by_jordan、relatedToType 归一化后为 'account'、assignedToId == 'user-1'、status 归一化后 != 'completed'\"\n pass_condition: \"新增任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、当前用户为 Jordan、账户所有者为 Jordan,且任务文本包含风险或使用衰退关键词\"\n\n- name: \"Component 3a — Slack 频道消息\"\n weight: 0.13\n description: \"检查 Jordan Rivera 是否在 acct-summit-retail 频道发送了新消息,且 acct-northstar 和 general 频道未被改动\"\n check_logic: \"current_user_is_jordan 为真;new_records(summit_init, summit_curr, 'messageId') 非空且其中至少一条 senderId == 'user_1';new_records 对 acct-northstar 和 general 返回空列表(north_unchanged 和 general_unchanged 为真)\"\n pass_condition: \"当前 Slack 用户为 Jordan;acct-summit-retail 频道有新增消息且由 user_1 发送;acct-northstar 和 general 频道无新增消息\"\n\n- name: \"Component 3b — Slack 消息内容\"\n weight: 0.20\n description: \"检查新消息是否提到 Summit、Red/风险、使用衰退,并给出下一步或负责人\"\n check_logic: \"遍历 jordan_messages,检查 m.get('content') 同时满足 mentions_account(txt)、mentions_red_or_risk(txt)、mentions_usage_decline(txt)、has_any(txt, NEXTSTEP_KW)\"\n pass_condition: \"消息内容经 normalize 后同时包含 Summit 相关关键词、Red/风险关键词、使用衰退关键词以及 next step/owner/action 等下一步关键词\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各子组件分数直接相加,最终通过 min(total_score, 1.0) 钳制上限为 1.0,再四舍五入保留 4 位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\n \"从任一 mock 服务获取状态失败或 current_state 为空:打印 CRITICAL 并返回 0.0\",\n \"Notion 检查中当前用户非 Jordan、Summit 行未新建 Risk Note、其他行被改动:Component 1 不得分\",\n \"Salesforce 中未新增 task 类型活动,或新增任务字段不匹配 account-1/非 Completed/未分配 Jordan:Component 2 不得分\",\n \"Slack 中 acct-summit-retail 无 Jordan 的新消息,或其他频道被发送消息:Component 3 不得分\",\n \"各组件内部异常被捕获为 ERROR,仅影响该组件得分,不会导致整体提前退出\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后通过 HTTP 请求向 notion_mock、salesforce_mock、slack_mock 三个服务的 /go?sid={sid} 端点拉取 initial_state 与 current_state,任一拉取失败或 current_state 为空即返回 0.0。接着进入 verify_task():Component 1 针对 Notion,检查 item-summit 的 prop-risk 是否由 Jordan 从空白填为有效内容(0.17),并验证内容包含使用衰退与 Red/流失风险语义(0.17),同时要求其余四行账户的 Risk Note 仍为空白且 CSM 未变;Component 2 针对 Salesforce,对比 activities 列表找出新增 task,至少一条新增 task 得 0.13,再验证该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed 且文本含风险/衰退语义得 0.20;Component 3 针对 Slack,检查 acct-summit-retail 频道有 Jordan 发送的新消息且 acct-northstar 与 general 频道无变动得 0.13,再验证消息内容同时提及 Summit、Red/风险、使用衰退及下一步行动得 0.20。所有子项得分累加后,以 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数作为最终 REWARD。\"\n\nconfidence: 1.0\n\n检查 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n\n确保所有字符串值都是中文(除了代码标识符和特定名称)。\n\n再检查一下 weight 字段。代码中显式给出了分值:0.17, 0.17, 0.13, 0.20, 0.13, 0.20。总和正好是 1.0。\n\n确认 data_sources 的写法。代码中是通过 MOCKS 字典定义的,端点是 http://28.7.186.212:8166 等。可以写为 notion_mock、salesforce_mock、slack_mock,并注明端点。\n\n确认 failure_modes 是否包含提前退出路径:\n- sid 读取失败:是,sys.exit(0)\n- mock 拉取失败:是,sys.exit(0)\n- 其他是不得分,不是提前退出,但也属于失败路径。\n\n确认 score_aggregation:\"相加后钳制到上限\" 是准确的。\n\n好,我现在可以输出最终的 JSON 了。 {\"task_id\":\"csm_health_risk_001\",\"domain\":\"mock_websites\",\"summary\":\"验证 CSM Jordan Rivera 是否在 Notion、Salesforce 和 Slack 三个系统中正确记录了 Summit Retail Group 账户的流失风险(Red 状态且使用衰退)。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"notion_mock (http://28.7.186.212:8186)\",\"salesforce_mock (http://28.7.186.212:8195)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Component 1a — Notion Summit 风险笔记创建\",\"weight\":0.17,\"description\":\"检查 Notion 中 Jordan Rivera 拥有的 Summit Retail Group 行(item-summit)的 Risk Note 从空白变为非空,且其他账户行的 Risk Note 保持空白、CSM 未改动\",\"check_logic\":\"current_user_is_jordan 为真;summit_owned_by_jordan 为真;summit_init_risk == '' 且 summit_risk != '';others_blank 为真(item-cedar/river/blue/north 的 prop-risk 均为空);other_csm_unchanged 为真\",\"pass_condition\":\"当前用户是 Jordan Rivera;item-summit 的 prop-risk 初始为空且当前非空;该行 CSM 属于 Jordan;其余四行账户的 prop-risk 仍为空且 CSM 与初始状态一致\"},{\"name\":\"Component 1b — Notion 风险笔记内容\",\"weight\":0.17,\"description\":\"检查 Summit Retail Group 的 Risk Note 内容是否解释了使用衰退和 Red/流失风险\",\"check_logic\":\"summit_risk != '' 且 mentions_usage_decline(summit_risk) 返回真且 mentions_red_or_risk(summit_risk) 返回真\",\"pass_condition\":\"笔记非空,且文本经 normalize 后同时包含 decline/down/drop 等使用衰退关键词和 red/at risk/churn 等风险关键词\"},{\"name\":\"Component 2a — Salesforce 新增任务\",\"weight\":0.13,\"description\":\"检查 Salesforce 的 activities 中是否至少新增了一条 type 为 'task' 的记录\",\"check_logic\":\"对比 initial 和 current 的 activities 列表(按 activityId 去重),new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'],要求 len(new_tasks) >= 1\",\"pass_condition\":\"至少存在一条新增 activity,其 type 字段归一化后为 'task'\"},{\"name\":\"Component 2b — Salesforce 风险任务字段\",\"weight\":0.2,\"description\":\"检查新增任务是否针对 account-1、字段正确且文本体现健康风险或使用衰退\",\"check_logic\":\"遍历 new_tasks,拼接 subject/description/comments/body 为 task_text;找到 relatedToId == 'account-1' 且 (mentions_red_or_risk(task_text) 或 mentions_usage_decline(task_text)) 的任务;再校验 current_user_is_jordan、target_account_owned_by_jordan、relatedToType 归一化后为 'account'、assignedToId == 'user-1'、status 归一化后 != 'completed'\",\"pass_condition\":\"新增任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、当前用户为 Jordan、账户所有者为 Jordan,且任务文本包含风险或使用衰退关键词\"},{\"name\":\"Component 3a — Slack 频道消息\",\"weight\":0.13,\"description\":\"检查 Jordan Rivera 是否在 acct-summit-retail 频道发送了新消息,且 acct-northstar 和 general 频道未被改动\",\"check_logic\":\"current_user_is_jordan 为真;new_records(summit_init, summit_curr, 'messageId') 非空且其中至少一条 senderId == 'user_1';new_records 对 acct-northstar 和 general 返回空列表(north_unchanged 和 general_unchanged 为真)\",\"pass_condition\":\"当前 Slack 用户为 Jordan;acct-summit-retail 频道有新增消息且由 user_1 发送;acct-northstar 和 general 频道无新增消息\"},{\"name\":\"Component 3b — Slack 消息内容\",\"weight\":0.2,\"description\":\"检查新消息是否提到 Summit、Red/风险、使用衰退,并给出下一步或负责人\",\"check_logic\":\"遍历 jordan_messages,检查 m.get('content') 同时满足 mentions_account(txt)、mentions_red_or_risk(txt)、mentions_usage_decline(txt)、has_any(txt, NEXTSTEP_KW)\",\"pass_condition\":\"消息内容经 normalize 后同时包含 Summit 相关关键词、Red/风险关键词、使用衰退关键词以及 next step/owner/action 等下一步关键词\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各子组件分数直接相加,最终通过 min(total_score, 1.0) 钳制上限为 1.0,再四舍五入保留 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\"从任一 mock 服务获取状态失败或 current_state 为空:打印 CRITICAL 并返回 0.0\",\"Notion 检查中当前用户非 Jordan、Summit 行未新建 Risk Note、其他行被改动:Component 1 不得分\",\"Salesforce 中未新增 task 类型活动,或新增任务字段不匹配 account-1/非 Completed/未分配 Jordan:Component 2 不得分\",\"Slack 中 acct-summit-retail 无 Jordan 的新消息,或其他频道被发送消息:Component 3 不得分\",\"各组件内部异常被捕获为 ERROR,仅影响该组件得分,不会导致整体提前退出\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后通过 HTTP 请求向 notion_mock、salesforce_mock、slack_mock 三个服务的 /go?sid={sid} 端点拉取 initial_state 与 current_state,任一拉取失败或 current_state 为空即返回 0.0。接着进入 verify_task():Component 1 针对 Notion,检查 item-summit 的 prop-risk 是否由 Jordan 从空白填为有效内容(0.17),并验证内容包含使用衰退与 Red/流失风险语义(0.17),同时要求其余四行账户的 Risk Note 仍为空白且 CSM 未变;Component 2 针对 Salesforce,对比 activities 列表找出新增 task,至少一条新增 task 得 0.13,再验证该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed 且文本含风险/衰退语义得 0.20;Component 3 针对 Slack,检查 acct-summit-retail 频道有 Jordan 发送的新消息且 acct-northstar 与 general 频道无变动得 0.13,再验证消息内容同时提及 Summit、Red/风险、使用衰退及下一步行动得 0.20。所有子项得分累加后,以 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数作为最终 REWARD。\",\"confidence\":1.0}" +} diff --git a/csm_onboarding_checklist_004/_cua_gym_vm_bridge.sh b/csm_onboarding_checklist_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csm_onboarding_checklist_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/csm_onboarding_checklist_004/initial_setup.py b/csm_onboarding_checklist_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..89ffcbb089573f43793de3519d014507faf603aa --- /dev/null +++ b/csm_onboarding_checklist_004/initial_setup.py @@ -0,0 +1,254 @@ +""" +Initial Setup: ce_onboarding_b106 +Task ID: csm_onboarding_checklist_004 +Domain: mock_websites +Mocks: google_docs_mock, google_calendar_mock, gmail_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 team calendar, the shared email inbox, 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 'Onboarding Template'; an empty Google Calendar; Gmail inbox with 1 email(s): "Excited to get started" from sarah.j@techventures.com; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: onboarding checklist doc created (+0.15); checklist has all five steps (+0.3); cal_new_event (+0.1); training on July 1 (+0.1); gmail_new_sent (+0.05); invite emailed to champion (+0.15); invite names the date (+0.05); slack_new_msg (+0.1). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0. +""" +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", + "google_calendar_mock": "http://28.7.184.198:8141", + "gmail_mock": "http://28.7.184.198:8138", + "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-tmpl': { 'id': 'd-tmpl', + 'title': 'Onboarding Template', + 'content': '

tmpl

', + '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': ''}}, + '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}}, + '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': 'Sarah Johnson', + 'email': 'sarah.j@techventures.com', + 'avatar': ''}, + 'to': [ { 'name': 'John Smith', + 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'subject': 'Excited to get started', + 'body': "

Looking forward to onboarding — when's our " + 'training?

', + 'snippet': "When's training?", + 'timestamp': '2026-06-08T08:15:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'folder': 'inbox', + 'attachments': []}], + 'drafts': []}, + '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 TechVentures onboarding ' + 'start?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/csm_onboarding_checklist_004/reward.py b/csm_onboarding_checklist_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..2692c9999c8ad56008d86ae5fea824fcac429152 --- /dev/null +++ b/csm_onboarding_checklist_004/reward.py @@ -0,0 +1,154 @@ +""" +Reward Script: ce_onboarding_b106 +Task ID: csm_onboarding_checklist_004 +Domain: mock_websites +Mocks: google_docs_mock, google_calendar_mock, gmail_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.15] onboarding checklist doc created + - [0.3] checklist has all five steps + - [0.1] cal_new_event + - [0.1] training on July 1 + - [0.05] gmail_new_sent + - [0.15] invite emailed to champion + - [0.05] invite names the date + - [0.1] slack_new_msg +""" +import re +import sys + +import requests + +MOCK_URLS = { + "google_docs_mock": "http://28.7.184.198:8142", + "google_calendar_mock": "http://28.7.184.198:8141", + "gmail_mock": "http://28.7.184.198:8138", + "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 (onboarding checklist doc created) +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 ['techventures onboarding', 'onboarding checklist'])] +if c0_new: + print('PASS: onboarding checklist doc created (0.15)') + total += 0.15 +else: + print('FAIL: onboarding checklist doc created') + +# c1: new google doc body (checklist has all five steps) +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 ['techventures onboarding', 'onboarding checklist'])] +c1_txt = _lc(' '.join(d.get('content','') for d in c1_new)) +if c1_new and all(t in c1_txt for t in ['kickoff', 'account setup', 'admin training', 'data import', 'go-live']): + print('PASS: checklist has all five steps (0.3)') + total += 0.3 +else: + print('FAIL: checklist has all five steps') + +# 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-07-01' +c3_new = globals().get('cal_new_events', []) +if any('2026-07-01' in (e.get('start','') or '') for e in c3_new): + print('PASS: training on July 1 (0.1)') + total += 0.1 +else: + print('FAIL: training on July 1') + +# c4: a new email was sent (folder sent) or saved as draft +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_sent = [e for e in (c4_cur.get('emails') or []) if e.get('id') not in c4_init_ids and e.get('folder') in ('sent', 'drafts')] +c4_sent += [d for d in (c4_cur.get('drafts') or []) if d.get('id') not in {x.get('id') for x in (c4_init.get('drafts') or [])}] +if c4_sent: + print('PASS: new email sent/drafted (0.05)') + total += 0.05 +else: + print('FAIL: no new sent/draft email') + +# c5: sent/draft email addressed to (invite emailed to champion) +c5_init = (STATES['gmail_mock'].get('initial_state') or {}) +c5_cur = cur('gmail_mock') +c5_init_ids = {e.get('id') for e in (c5_init.get('emails') or [])} +c5_pool = [e for e in (c5_cur.get('emails') or []) if e.get('id') not in c5_init_ids and e.get('folder') in ('sent','drafts')] + (c5_cur.get('drafts') or []) +c5_tos = _lc(' '.join(t.get('email','') for e in c5_pool for t in (e.get('to') or []))) +if any(t in c5_tos for t in ['sarah.j@techventures.com']): + print('PASS: invite emailed to champion (0.15)') + total += 0.15 +else: + print('FAIL: invite emailed to champion') + +# c6: sent/draft email text contains (invite names the date) +c6_init = (STATES['gmail_mock'].get('initial_state') or {}) +c6_cur = cur('gmail_mock') +c6_init_ids = {e.get('id') for e in (c6_init.get('emails') or [])} +c6_pool = [e for e in (c6_cur.get('emails') or []) if e.get('id') not in c6_init_ids and e.get('folder') in ('sent','drafts')] + (c6_cur.get('drafts') or []) +c6_txt = _lc(' '.join((e.get('subject','') + ' ' + e.get('body','') + ' ' + e.get('snippet','')) for e in c6_pool)) +if any(t in c6_txt for t in ['july 1', 'training']): + print('PASS: invite names the date (0.05)') + total += 0.05 +else: + print('FAIL: invite names the date') + +# c7: new message by user_1 in #general +c7_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c7_seed = set(SEED.get('slack_mock:general', [])) +c7_new = [m for m in c7_msgs if m.get('messageId') not in c7_seed and m.get('senderId') == 'user_1'] +c7_blob = _lc(' '.join((m.get('content') or '') for m in c7_new)) +if c7_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/csm_onboarding_checklist_004/reward_label.json b/csm_onboarding_checklist_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..abf22fa2b938eb3df000a8d33853b22e866d57ca --- /dev/null +++ b/csm_onboarding_checklist_004/reward_label.json @@ -0,0 +1,88 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/bda2b533-4396-584b-ae98-d4198dd74783/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:29", + "label": { + "task_id": "csm_onboarding_checklist_004", + "domain": "mock_websites", + "summary": "验证新员工入职流程是否完成,包括创建入职清单文档、安排7月1日培训日历事件、发送邀请邮件给负责人以及在Slack发布通知", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_docs_mock", + "google_calendar_mock", + "gmail_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 0", + "weight": 0.15, + "description": "创建入职清单文档", + "check_logic": "对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出新增文档,检查其 title(转小写后)是否包含 'techventures onboarding' 或 'onboarding checklist'", + "pass_condition": "存在新增的 Google Doc,且标题包含指定关键词" + }, + { + "name": "Component 1", + "weight": 0.3, + "description": "清单包含全部五个步骤", + "check_logic": "在 Component 0 筛选出的新文档中,提取 content 转小写后的文本,检查是否同时包含 'kickoff'、'account setup'、'admin training'、'data import'、'go-live'", + "pass_condition": "新文档内容同时包含五个指定关键词" + }, + { + "name": "Component 2", + "weight": 0.1, + "description": "创建新的日历事件", + "check_logic": "对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,通过 event id 判断是否有新增事件", + "pass_condition": "存在新增的日历事件" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "培训安排在7月1日", + "check_logic": "在 Component 2 识别出的新事件中,检查任意事件的 start 字段是否包含 '2026-07-01'", + "pass_condition": "新增事件的 start 字段包含 '2026-07-01'" + }, + { + "name": "Component 4", + "weight": 0.05, + "description": "发送或起草新邮件", + "check_logic": "对比 gmail_mock 的 initial_state 与 current_state,找出 id 不在初始集合中且 folder 为 'sent' 或 'drafts' 的邮件,或 current_state drafts 中新增的草稿", + "pass_condition": "存在新增的已发送或草稿邮件" + }, + { + "name": "Component 5", + "weight": 0.15, + "description": "向负责人发送邀请邮件", + "check_logic": "在 Component 4 的邮件池(sent/drafts 新增邮件 + 所有 current drafts)中,提取所有 to 字段中的 email 地址转小写后,检查是否包含 'sarah.j@techventures.com'", + "pass_condition": "邮件收件人包含 'sarah.j@techventures.com'" + }, + { + "name": "Component 6", + "weight": 0.05, + "description": "邮件中注明日期", + "check_logic": "在 Component 4 的邮件池中,将 subject、body、snippet 拼接转小写,检查是否包含 'july 1' 或 'training'", + "pass_condition": "邮件文本包含 'july 1' 或 'training'" + }, + { + "name": "Component 7", + "weight": 0.1, + "description": "在 Slack #general 频道发送新消息", + "check_logic": "检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中预置的 messageId,筛选 senderId 为 'user_1' 的新消息", + "pass_condition": "存在 senderId 为 'user_1' 且不在初始种子中的新消息" + } + ], + "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_docs_mock、google_calendar_mock、gmail_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出", + "各评分组件检查失败仅导致该组件不得分,不会提前退出" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)拉取 current_state。接着按顺序执行 8 个评分组件:1)检查是否新建了标题含 onboarding 关键词的 Google Doc;2)检查该文档内容是否包含五个指定步骤关键词;3)检查 Google Calendar 是否有新增事件;4)检查新增事件是否安排在 2026-07-01;5)检查 Gmail 是否有新增的 sent/drafts 邮件;6)检查邮件是否发送给 sarah.j@techventures.com;7)检查邮件主题或正文是否提到 july 1 或 training;8)检查 Slack #general 频道是否有 user_1 发送的新消息。每个组件独立判断,通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. 任务 ID: 从 docstring 中提取 `ce_onboarding_b106`,但文件路径中的 UUID 是 `bda2b533-4396-584b-ae98-d4198dd74783`。docstring 中明确写了 `Task ID: bda2b533-4396-584b-ae98-d4198dd74783`,所以 task_id 应该是这个 UUID。等等,docstring 第一行是 `Reward Script: ce_onboarding_b106`,但后面有 `Task ID: bda2b533-4396-584b-ae98-d4198dd74783`。根据要求\"从文件 docstring 中提取的任务 ID\",应该提取 `bda2b533-4396-584b-ae98-d4198dd74783`。\n\n2. Domain: `mock_websites`\n\n3. 数据源: `google_docs_mock`, `google_calendar_mock`, `gmail_mock`, `slack_mock`,以及 `/tmp/task_web_sid`\n\n4. 评分组件:\n - c0: 0.15 - onboarding checklist doc created - 检查新创建的 google doc 标题包含 'techventures onboarding' 或 'onboarding checklist'\n - c1: 0.3 - checklist has all five steps - 检查新 doc 内容包含 'kickoff', 'account setup', 'admin training', 'data import', 'go-live'\n - c2: 0.1 - cal_new_event - 检查 google calendar 有新事件\n - c3: 0.1 - training on July 1 - 检查新事件 start 包含 '2026-07-01'\n - c4: 0.05 - gmail_new_sent - 检查 gmail 有新 sent 或 draft 邮件\n - c5: 0.15 - invite emailed to champion - 检查邮件 to 包含 'sarah.j@techventures.com'\n - c6: 0.05 - invite names the date - 检查邮件 subject/body/snippet 包含 'july 1' 或 'training'\n - c7: 0.1 - slack_new_msg - 检查 slack #general 有新消息,senderId 为 'user_1'\n\n5. 总分计算: 各项相加,最后 `round(min(total, 1.0), 4)`\n\n6. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n7. is_placeholder: false,因为脚本有实际检查逻辑。\n\n8. confidence: 1.0,因为逻辑清晰。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"bda2b533-4396-584b-ae98-d4198dd74783\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证新员工入职流程是否完成,包括创建入职清单文档、安排培训日历事件、发送邀请邮件给负责人以及在Slack发布通知\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google_docs_mock\", \"google_calendar_mock\", \"gmail_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 0\",\n \"weight\": 0.15,\n \"description\": \"创建入职清单文档\",\n \"check_logic\": \"对比 initial_state 与 current_state 中的 documents,找出新增文档,检查其 title(转小写后)是否包含 'techventures onboarding' 或 'onboarding checklist'\",\n \"pass_condition\": \"存在新增的 Google Doc,且标题包含指定关键词\"\n },\n {\n \"name\": \"Component 1\",\n \"weight\": 0.3,\n \"description\": \"清单包含全部五个步骤\",\n \"check_logic\": \"在 Component 0 筛选出的新文档中,提取 content 转小写后的文本,检查是否同时包含 'kickoff'、'account setup'、'admin training'、'data import'、'go-live'\",\n \"pass_condition\": \"新文档内容同时包含五个指定关键词\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.1,\n \"description\": \"创建新的日历事件\",\n \"check_logic\": \"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,通过 event id 判断是否有新增事件\",\n \"pass_condition\": \"存在新增的日历事件\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.1,\n \"description\": \"培训安排在7月1日\",\n \"check_logic\": \"在 Component 2 识别出的新事件中,检查任意事件的 start 字段是否包含 '2026-07-01'\",\n \"pass_condition\": \"新增事件的 start 字段包含 '2026-07-01'\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.05,\n \"description\": \"发送或起草新邮件\",\n \"check_logic\": \"对比 gmail_mock 的 initial_state 与 current_state,找出 id 不在初始集合中且 folder 为 'sent' 或 'drafts' 的邮件,或 current_state drafts 中新增的草稿\",\n \"pass_condition\": \"存在新增的已发送或草稿邮件\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"向负责人发送邀请邮件\",\n \"check_logic\": \"在 Component 4 的邮件池(sent/drafts 新增邮件 + 所有 current drafts)中,提取所有 to 字段中的 email 地址转小写后,检查是否包含 'sarah.j@techventures.com'\",\n \"pass_condition\": \"邮件收件人包含 'sarah.j@techventures.com'\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.05,\n \"description\": \"邮件中注明日期\",\n \"check_logic\": \"在 Component 4 的邮件池中,将 subject、body、snippet 拼接转小写,检查是否包含 'july 1' 或 'training'\",\n \"pass_condition\": \"邮件文本包含 'july 1' 或 'training'\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.1,\n \"description\": \"在 Slack #general 频道发送新消息\",\n \"check_logic\": \"检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中预置的 messageId,筛选 senderId 为 'user_1' 的新消息\",\n \"pass_condition\": \"存在 senderId 为 'user_1' 且不在初始种子中的新消息\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"无法读取 /tmp/task_web_sid 或 sid 为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"任一模 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"各评分组件检查失败仅导致该组件不得分,不会提前退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)拉取 current_state。接着按顺序执行 8 个评分组件:1)检查是否新建了标题含 onboarding 关键词的 Google Doc;2)检查该文档内容是否包含五个指定步骤关键词;3)检查 Google Calendar 是否有新增事件;4)检查新增事件是否安排在 2026-07-01;5)检查 Gmail 是否有新增的 sent/drafts 邮件;6)检查邮件是否发送给 sarah.j@techventures.com;7)检查邮件主题或正文是否提到 july 1 或 training;8)检查 Slack #general 频道是否有 user_1 发送的新消息。每个组件独立判断,通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,没有 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名、代码标识符保留原样\n- weight 填写代码中显式给出的分值\n- is_placeholder: false\n\n确认 task_id:docstring 中明确写了 `Task ID: bda2b533-4396-584b-ae98-d4198dd74783`,所以用这个。\n\n确认 domain:`mock_websites`。\n\n确认 data_sources:包含 `/tmp/task_web_sid` 和四个 mock。\n\n确认 total_max_score:1.0。\n\n确认 score_aggregation:代码中是 `round(min(total, 1.0), 4)`,所以是相加后钳制到上限。\n\n确认 failure_modes:sid 读取失败、mock 拉取失败都会 sys.exit(0) 并打印 REWARD: 0.0。\n\n一切看起来正确。 {\n \"task_id\": \"bda2b533-4396-584b-ae98-d4198dd74783\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证新员工入职流程是否完成,包括创建入职清单文档、安排7月1日培训日历事件、发送邀请邮件给负责人以及在Slack发布通知\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google_docs_mock\", \"google_calendar_mock\", \"gmail_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 0\",\n \"weight\": 0.15,\n \"description\": \"创建入职清单文档\",\n \"check_logic\": \"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出新增文档,检查其 title(转小写后)是否包含 'techventures onboarding' 或 'onboarding checklist'\",\n \"pass_condition\": \"存在新增的 Google Doc,且标题包含指定关键词\"\n },\n {\n \"name\": \"Component 1\",\n \"weight\": 0.3,\n \"description\": \"清单包含全部五个步骤\",\n \"check_logic\": \"在 Component 0 筛选出的新文档中,提取 content 转小写后的文本,检查是否同时包含 'kickoff'、'account setup'、'admin training'、'data import'、'go-live'\",\n \"pass_condition\": \"新文档内容同时包含五个指定关键词\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.1,\n \"description\": \"创建新的日历事件\",\n \"check_logic\": \"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,通过 event id 判断是否有新增事件\",\n \"pass_condition\": \"存在新增的日历事件\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.1,\n \"description\": \"培训安排在7月1日\",\n \"check_logic\": \"在 Component 2 识别出的新事件中,检查任意事件的 start 字段是否包含 '2026-07-01'\",\n \"pass_condition\": \"新增事件的 start 字段包含 '2026-07-01'\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.05,\n \"description\": \"发送或起草新邮件\",\n \"check_logic\": \"对比 gmail_mock 的 initial_state 与 current_state,找出 id 不在初始集合中且 folder 为 'sent' 或 'drafts' 的邮件,或 current_state drafts 中新增的草稿\",\n \"pass_condition\": \"存在新增的已发送或草稿邮件\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"向负责人发送邀请邮件\",\n \"check_logic\": \"在 Component 4 的邮件池(sent/drafts 新增邮件 + 所有 current drafts)中,提取所有 to 字段中的 email 地址转小写后,检查是否包含 'sarah.j@techventures.com'\",\n \"pass_condition\": \"邮件收件人包含 'sarah.j@techventures.com'\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.05,\n \"description\": \"邮件中注明日期\",\n \"check_logic\": \"在 Component 4 的邮件池中,将 subject、body、snippet 拼接转小写,检查是否包含 'july 1' 或 'training'\",\n \"pass_condition\": \"邮件文本包含 'july 1' 或 'training'\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.1,\n \"description\": \"在 Slack #general 频道发送新消息\",\n \"check_logic\": \"检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中预置的 messageId,筛选 senderId 为 'user_1' 的新消息\",\n \"pass_condition\": \"存在 senderId 为 'user_1' 且不在初始种子中的新消息\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"无法读取 /tmp/task_web_sid 或 sid 为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"任一模 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"各评分组件检查失败仅导致该组件不得分,不会提前退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)拉取 current_state。接着按顺序执行 8 个评分组件:1)检查是否新建了标题含 onboarding 关键词的 Google Doc;2)检查该文档内容是否包含五个指定步骤关键词;3)检查 Google Calendar 是否有新增事件;4)检查新增事件是否安排在 2026-07-01;5)检查 Gmail 是否有新增的 sent/drafts 邮件;6)检查邮件是否发送给 sarah.j@techventures.com;7)检查邮件主题或正文是否提到 july 1 或 training;8)检查 Slack #general 频道是否有 user_1 发送的新消息。每个组件独立判断,通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。\",\n \"confidence\": 1.0\n}" +} diff --git a/csm_qbr_renewal_003/_cua_gym_vm_bridge.sh b/csm_qbr_renewal_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csm_qbr_renewal_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/csm_qbr_renewal_003/initial_setup.py b/csm_qbr_renewal_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0471d817156d7818306d263378341d6fac1188ac --- /dev/null +++ b/csm_qbr_renewal_003/initial_setup.py @@ -0,0 +1,760 @@ +# --- 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: CSM renewal QBR prep for Aspen Dynamics +Task ID: csm_qbr_renewal_003 +Domain: mock_websites +Mocks: notion_mock, salesforce_mock, docusign_mock, gmail_mock + +INITIAL STATE (pre-task): + - Notion: Jordan Rivera workspace with a 'Customer Health Tracker' database that + holds an 'Aspen Dynamics' row (Health Yellow, MAU Trend Flat, ARR 90000, usage + notes). NO QBR agenda page exists yet. + - Salesforce: CSM Jordan Rivera (user-1, Customer Success). account-1 'Aspen + Dynamics' (Customer), contact-1 'Daniel Brooks' primary contact, opp-1 + 'Aspen Dynamics - FY27 Renewal' at stage 'Qualification'. Default activities + exist but NO QBR event for Aspen; the runtime "this Friday" 14:00-14:45 + slot is free. + - DocuSign: CSM Jordan Rivera (Northwind Cloud). env_1 DRAFT 'Aspen Dynamics - + FY27 Renewal Agreement' with signer Daniel Brooks (status created). Distractor + env_2 DRAFT for a different customer. + - Gmail: Jordan Rivera (u1). Inbox has unrelated mail; drafts empty; NO sent + email to daniel.brooks@aspendynamics.com. +""" +import os +import shlex +import subprocess +import time +import uuid +from datetime import date, timedelta + +import requests + +# Current mock deployments are reachable directly from the VM. +print('Network mode: direct') + + +def http_post(url, payload): + return requests.post(url, json=payload, timeout=30) + + +def http_get(url): + return requests.get(url, timeout=30) + + +# --- Config --- +NOTION_URL = 'http://28.7.184.198:8166' +SALESFORCE_URL = 'http://28.7.184.198:8175' +DOCUSIGN_URL = 'http://28.7.184.198:8130' +GMAIL_URL = 'http://28.7.184.198:8138' + + +def this_friday(today): + days_until_friday = (4 - today.weekday()) % 7 + return today + timedelta(days=days_until_friday) + + +def fmt_month_day_year(d): + return f'{d.strftime("%b")} {d.day}, {d.year}' + + +TODAY = date.today() +TARGET_QBR_DATE = this_friday(TODAY) +TARGET_QBR_START = f'{TARGET_QBR_DATE.isoformat()}T14:00' +TARGET_QBR_END = f'{TARGET_QBR_DATE.isoformat()}T14:45' +RENEWAL_DATE = TODAY + timedelta(days=45) + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +with open('/tmp/task_qbr_date', 'w') as f: + f.write(TARGET_QBR_DATE.isoformat()) +print(f'Generated sid={sid}') +print(f'Target QBR date={TARGET_QBR_DATE.isoformat()}') + + +# --------------------------------------------------------------------------- +# NOTION STATE — Customer Health Tracker database with Aspen Dynamics row. +# NO QBR agenda page yet. +# --------------------------------------------------------------------------- +def build_notion_state(): + user = { + "id": "user-1", + "name": "Jordan Rivera", + "email": "jordan.rivera@northwindcloud.com", + "avatar": "", + } + workspace = { + "id": "ws-1", + "name": "Northwind Cloud — Customer Success", + "icon": "", + "members": ["user-1"], + } + + # Database properties (column definitions) + db_props = [ + {"id": "prop-name", "name": "Account", "type": "text"}, + {"id": "prop-health", "name": "Health", "type": "select", + "options": ["Green", "Yellow", "Red"]}, + {"id": "prop-mau", "name": "MAU Trend", "type": "select", + "options": ["Up", "Flat", "Down"]}, + {"id": "prop-arr", "name": "ARR", "type": "text"}, + {"id": "prop-notes", "name": "Usage Notes", "type": "text"}, + ] + + # Database rows (each is its own page referenced from items[]) + row_aspen = { + "id": "row-aspen", + "title": "Aspen Dynamics", + "icon": "", + "cover": None, + "parentId": "db-health", + "blockIds": [], + "favorite": False, + "createdDate": "2026-04-02T00:00:00.000Z", + "lastEditedDate": "2026-06-18T00:00:00.000Z", + "properties": { + "prop-name": "Aspen Dynamics", + "prop-health": "Yellow", + "prop-mau": "Flat", + "prop-arr": "90000", + "prop-notes": "Adoption of reporting module up; admin seats underused; " + "one open escalation last quarter (since resolved). Renewal " + f"FY27 due {fmt_month_day_year(RENEWAL_DATE)}; champion is Daniel Brooks " + "(VP Customer Operations).", + }, + } + row_orion = { + "id": "row-orion", + "title": "Orion Retail Group", + "icon": "", + "cover": None, + "parentId": "db-health", + "blockIds": [], + "favorite": False, + "createdDate": "2026-03-11T00:00:00.000Z", + "lastEditedDate": "2026-06-10T00:00:00.000Z", + "properties": { + "prop-name": "Orion Retail Group", + "prop-health": "Green", + "prop-mau": "Up", + "prop-arr": "145000", + "prop-notes": "Strong expansion last quarter; two new teams onboarded.", + }, + } + row_meridian = { + "id": "row-meridian", + "title": "Meridian Logistics", + "icon": "", + "cover": None, + "parentId": "db-health", + "blockIds": [], + "favorite": False, + "createdDate": "2026-02-20T00:00:00.000Z", + "lastEditedDate": "2026-05-29T00:00:00.000Z", + "properties": { + "prop-name": "Meridian Logistics", + "prop-health": "Red", + "prop-mau": "Down", + "prop-arr": "60000", + "prop-notes": "Usage declining; sponsor left in April. At-risk renewal.", + }, + } + + db_health = { + "id": "db-health", + "title": "Customer Health Tracker", + "icon": "", + "cover": None, + "parentId": None, + "type": "database", + "viewType": "table", + "properties": db_props, + "views": [ + {"id": "view-1", "name": "All Accounts", "type": "table", + "filters": [], "sorts": [], "groupBy": None, + "visibleProperties": ["prop-name", "prop-health", "prop-mau", + "prop-arr", "prop-notes"]}, + ], + "items": ["row-aspen", "row-orion", "row-meridian"], + "blockIds": [], + "favorite": True, + "createdDate": "2026-02-01T00:00:00.000Z", + } + + # A plain notes page (distractor / realism) — not a QBR agenda. + block_team_1 = { + "id": "blk-team-1", "type": "heading-2", + "content": "Standing Items", + "properties": {}, "createdDate": "2026-06-01T00:00:00.000Z", + "lastEditedDate": "2026-06-01T00:00:00.000Z", + } + block_team_2 = { + "id": "blk-team-2", "type": "bullet-list", + "content": "Review at-risk accounts weekly; keep ARR figures in sync with Salesforce.", + "properties": {}, "createdDate": "2026-06-01T00:00:00.000Z", + "lastEditedDate": "2026-06-01T00:00:00.000Z", + } + page_team = { + "id": "page-team-notes", + "title": "CS Team Notes", + "icon": "", + "cover": None, + "parentId": None, + "blockIds": ["blk-team-1", "blk-team-2"], + "favorite": False, + "createdDate": "2026-06-01T00:00:00.000Z", + "lastEditedDate": "2026-06-01T00:00:00.000Z", + "properties": {}, + } + + return { + "user": user, + "workspace": workspace, + "pages": { + "db-health": db_health, + "row-aspen": row_aspen, + "row-orion": row_orion, + "row-meridian": row_meridian, + "page-team-notes": page_team, + }, + "blocks": { + "blk-team-1": block_team_1, + "blk-team-2": block_team_2, + }, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"}, + "notifications": [], + "pageOrder": ["db-health", "page-team-notes"], + "focusBlockId": None, + } + + +# --------------------------------------------------------------------------- +# SALESFORCE STATE — Aspen Dynamics renewal opportunity at Qualification. +# --------------------------------------------------------------------------- +def build_salesforce_state(): + jordan = { + "userId": "user-1", + "firstName": "Jordan", + "lastName": "Rivera", + "email": "jordan.rivera@northwindcloud.com", + "phone": "(555) 410-2200", + "title": "Customer Success Manager", + "department": "Customer Success", + "role": "CSM", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + } + users = [ + jordan, + {"userId": "user-2", "firstName": "Priya", "lastName": "Nair", + "email": "priya.nair@northwindcloud.com", "phone": "(555) 410-2201", + "title": "Director, Customer Success", "department": "Customer Success", + "role": "Director", "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"}, + {"userId": "user-3", "firstName": "Marcus", "lastName": "Webb", + "email": "marcus.webb@northwindcloud.com", "phone": "(555) 410-2202", + "title": "Account Executive", "department": "Sales", + "role": "AE", "avatar": "https://i.pravatar.cc/150?u=user-3", + "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning"}, + ] + + accounts = [ + {"accountId": "account-1", "name": "Aspen Dynamics", "type": "Customer", + "industry": "Technology", "revenue": 38000000, "employees": 260, "ownerId": "user-1", + "phone": "(720) 555-0133", "website": "https://www.aspendynamics.example.com", + "billingStreet": "1450 Market St", "billingCity": "Denver", "billingState": "CO", + "billingZip": "80202", "billingCountry": "USA", + "shippingStreet": "1450 Market St", "shippingCity": "Denver", "shippingState": "CO", + "shippingZip": "80202", "shippingCountry": "USA", + "createdDate": "2024-03-15T00:00:00.000Z", "modifiedDate": "2026-06-10T00:00:00.000Z"}, + {"accountId": "account-2", "name": "Orion Retail Group", "type": "Customer", + "industry": "Retail", "revenue": 82000000, "employees": 610, "ownerId": "user-1", + "phone": "(415) 555-0188", "website": "https://www.orionretail.example.com", + "billingStreet": "55 Mission St", "billingCity": "San Francisco", "billingState": "CA", + "billingZip": "94105", "billingCountry": "USA", + "shippingStreet": "55 Mission St", "shippingCity": "San Francisco", "shippingState": "CA", + "shippingZip": "94105", "shippingCountry": "USA", + "createdDate": "2023-09-01T00:00:00.000Z", "modifiedDate": "2026-05-22T00:00:00.000Z"}, + {"accountId": "account-3", "name": "Meridian Logistics", "type": "Customer", + "industry": "Logistics", "revenue": 41000000, "employees": 300, "ownerId": "user-1", + "phone": "(312) 555-0144", "website": "https://www.meridianlogistics.example.com", + "billingStreet": "200 Wacker Dr", "billingCity": "Chicago", "billingState": "IL", + "billingZip": "60606", "billingCountry": "USA", + "shippingStreet": "200 Wacker Dr", "shippingCity": "Chicago", "shippingState": "IL", + "shippingZip": "60606", "shippingCountry": "USA", + "createdDate": "2024-01-12T00:00:00.000Z", "modifiedDate": "2026-04-30T00:00:00.000Z"}, + ] + + contacts = [ + {"contactId": "contact-1", "accountId": "account-1", "firstName": "Daniel", + "lastName": "Brooks", "title": "VP Customer Operations", "department": "Operations", + "email": "daniel.brooks@aspendynamics.com", "phone": "(720) 555-0134", + "ownerId": "user-1"}, + {"contactId": "contact-2", "accountId": "account-2", "firstName": "Lena", + "lastName": "Ortiz", "title": "Director of IT", "department": "IT", + "email": "lena.ortiz@orionretail.example.com", "phone": "(415) 555-0189", + "ownerId": "user-1"}, + {"contactId": "contact-3", "accountId": "account-3", "firstName": "Greg", + "lastName": "Halloran", "title": "Operations Manager", "department": "Operations", + "email": "greg.halloran@meridianlogistics.example.com", "phone": "(312) 555-0145", + "ownerId": "user-1"}, + ] + + opportunities = [ + {"opportunityId": "opp-1", "name": "Aspen Dynamics — FY27 Renewal", + "accountId": "account-1", "contactId": "contact-1", "amount": 90000, + "closeDate": RENEWAL_DATE.isoformat(), "stage": "Qualification", "probability": 30, + "ownerId": "user-1", "type": "Renewal", + "createdDate": "2026-05-15T00:00:00.000Z", "modifiedDate": "2026-06-12T00:00:00.000Z"}, + {"opportunityId": "opp-2", "name": "Orion Retail Group — Expansion", + "accountId": "account-2", "contactId": "contact-2", "amount": 60000, + "closeDate": "2026-09-30", "stage": "Proposal", "probability": 60, + "ownerId": "user-1", "type": "Upsell", + "createdDate": "2026-04-20T00:00:00.000Z", "modifiedDate": "2026-06-05T00:00:00.000Z"}, + {"opportunityId": "opp-3", "name": "Meridian Logistics — FY27 Renewal", + "accountId": "account-3", "contactId": "contact-3", "amount": 60000, + "closeDate": "2026-07-31", "stage": "Negotiation", "probability": 50, + "ownerId": "user-1", "type": "Renewal", + "createdDate": "2026-03-10T00:00:00.000Z", "modifiedDate": "2026-06-08T00:00:00.000Z"}, + ] + + # Default activities for the CSM: none is an Aspen QBR event, and none + # occupies the runtime "this Friday" 14:00-14:45 slot. + activities = [ + {"activityId": "activity-1", "type": "task", + "subject": "Follow up on Orion expansion proposal", + "status": "Open", "priority": "Normal", "dueDate": "2026-06-25", + "relatedToType": "opportunity", "relatedToId": "opp-2", "assignedToId": "user-1"}, + {"activityId": "activity-2", "type": "task", + "subject": "Prepare Meridian recovery plan", + "status": "Open", "priority": "High", "dueDate": "2026-06-29", + "relatedToType": "account", "relatedToId": "account-3", "assignedToId": "user-1"}, + {"activityId": "activity-3", "type": "event", + "subject": "Weekly CS team sync", + "status": "Open", "priority": "Normal", + "startDateTime": f"{TARGET_QBR_DATE.isoformat()}T10:00", + "endDateTime": f"{TARGET_QBR_DATE.isoformat()}T10:30", + "relatedToType": "account", "relatedToId": "account-2", "assignedToId": "user-1"}, + {"activityId": "activity-4", "type": "event", + "subject": "Orion quarterly check-in", + "status": "Open", "priority": "Normal", + "startDateTime": f"{(TARGET_QBR_DATE - timedelta(days=1)).isoformat()}T16:00", + "endDateTime": f"{(TARGET_QBR_DATE - timedelta(days=1)).isoformat()}T16:30", + "relatedToType": "account", "relatedToId": "account-2", "assignedToId": "user-1"}, + ] + + return { + "user": jordan, + "users": users, + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": activities, + "chatterPosts": [], + "files": [], + "following": ["user-2", "user-3"], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# --------------------------------------------------------------------------- +# DOCUSIGN STATE — draft renewal agreement (env_1) + distractor draft (env_2). +# --------------------------------------------------------------------------- +def build_docusign_state(): + user = { + "id": "user_1", + "name": "Jordan Rivera", + "email": "jordan.rivera@northwindcloud.com", + "title": "Customer Success Manager", + "company": "Northwind Cloud", + "avatar": "", + "memberSince": "2024-01-10", + "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120, + "timezone": "America/New_York"}, + } + + env_1 = { + "id": "env_1", + "subject": "Aspen Dynamics — FY27 Renewal Agreement", + "message": "Please review and sign the FY27 renewal agreement for Aspen Dynamics.", + "status": "draft", + "createdAt": "2026-06-20T15:30:00Z", + "sentAt": None, "completedAt": None, "voidedAt": None, "declinedAt": None, + "lastActivityAt": "2026-06-20T15:30:00Z", "expiresAt": None, + "senderId": "user_1", "folderId": None, "templateId": None, + "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2, + "documents": [ + {"id": "doc_1_1", "name": "Aspen Dynamics FY27 Renewal Agreement.pdf", + "pageCount": 6, "order": 1, + "fileUrl": "https://picsum.photos/seed/aspenfy27/800/1100", "fileType": "pdf"}, + ], + "recipients": [ + {"id": "rec_1_1", "name": "Daniel Brooks", "email": "daniel.brooks@aspendynamics.com", + "role": "signer", "routingOrder": 1, "status": "created", + "signedAt": None, "viewedAt": None, "deliveredAt": None, + "declinedAt": None, "declineReason": None}, + ], + "fields": [ + {"id": "fld_1_1", "type": "signature", "recipientId": "rec_1_1", + "documentId": "doc_1_1", "pageNumber": 6, "x": 120, "y": 640, + "width": 200, "height": 44, "value": None, "required": True, + "label": "Signature", "readOnly": False, "fontSize": 12, "fontColor": "#000000"}, + {"id": "fld_1_2", "type": "dateSigned", "recipientId": "rec_1_1", + "documentId": "doc_1_1", "pageNumber": 6, "x": 360, "y": 640, + "width": 120, "height": 24, "value": None, "required": True, + "label": "Date", "readOnly": True, "fontSize": 12, "fontColor": "#000000"}, + ], + "history": [ + {"id": "evt_1_1", "timestamp": "2026-06-20T15:30:00Z", "action": "created", + "actorName": "Jordan Rivera", "actorEmail": "jordan.rivera@northwindcloud.com", + "details": "Envelope created"}, + ], + } + + # Distractor draft for a DIFFERENT customer — must NOT be sent. + env_2 = { + "id": "env_2", + "subject": "Meridian Logistics — FY27 Renewal Agreement", + "message": "Draft renewal agreement for Meridian Logistics (not ready to send).", + "status": "draft", + "createdAt": "2026-06-18T11:05:00Z", + "sentAt": None, "completedAt": None, "voidedAt": None, "declinedAt": None, + "lastActivityAt": "2026-06-18T11:05:00Z", "expiresAt": None, + "senderId": "user_1", "folderId": None, "templateId": None, + "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2, + "documents": [ + {"id": "doc_2_1", "name": "Meridian Logistics FY27 Renewal Agreement.pdf", + "pageCount": 5, "order": 1, + "fileUrl": "https://picsum.photos/seed/meridianfy27/800/1100", "fileType": "pdf"}, + ], + "recipients": [ + {"id": "rec_2_1", "name": "Greg Halloran", + "email": "greg.halloran@meridianlogistics.example.com", + "role": "signer", "routingOrder": 1, "status": "created", + "signedAt": None, "viewedAt": None, "deliveredAt": None, + "declinedAt": None, "declineReason": None}, + ], + "fields": [], + "history": [ + {"id": "evt_2_1", "timestamp": "2026-06-18T11:05:00Z", "action": "created", + "actorName": "Jordan Rivera", "actorEmail": "jordan.rivera@northwindcloud.com", + "details": "Envelope created"}, + ], + } + + return { + "user": user, + "envelopes": [env_1, env_2], + "templates": [], + "folders": [], + "contacts": [ + {"id": "c_1", "name": "Daniel Brooks", "email": "daniel.brooks@aspendynamics.com", + "company": "Aspen Dynamics", "title": "VP Customer Operations"}, + {"id": "c_2", "name": "Greg Halloran", + "email": "greg.halloran@meridianlogistics.example.com", + "company": "Meridian Logistics", "title": "Operations Manager"}, + ], + "auditLog": [ + {"id": "audit_1", "timestamp": "2026-06-20T15:30:00Z", "action": "CREATE_ENVELOPE", + "details": "Created envelope 'Aspen Dynamics — FY27 Renewal Agreement'", + "envelopeId": "env_1"}, + {"id": "audit_2", "timestamp": "2026-06-18T11:05:00Z", "action": "CREATE_ENVELOPE", + "details": "Created envelope 'Meridian Logistics — FY27 Renewal Agreement'", + "envelopeId": "env_2"}, + ], + } + + +# --------------------------------------------------------------------------- +# GMAIL STATE — Jordan Rivera; inbox has unrelated mail; no sent email to Daniel. +# --------------------------------------------------------------------------- +def build_gmail_state(): + user = { + "userId": "u1", + "username": "Jordan Rivera", + "email": "jordan.rivera@northwindcloud.com", + "avatar": "https://i.pravatar.cc/150?u=jordan-rivera", + } + emails = [ + {"id": "email_1", "threadId": "thread_1", + "from": {"name": "Priya Nair", "email": "priya.nair@northwindcloud.com"}, + "to": [{"name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com"}], + "cc": [], "bcc": [], + "subject": "Renewals pipeline review — Friday", + "body": "

Hi Jordan,

Let's go through the Q3 renewals on our Friday sync. " + "Please have the at-risk accounts ready.

Thanks,
Priya

", + "timestamp": "2026-06-22T13:15:00Z", + "read": True, "starred": False, "important": True, + "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": []}, + {"id": "email_2", "threadId": "thread_2", + "from": {"name": "Northwind Cloud Billing", "email": "billing@northwindcloud.com"}, + "to": [{"name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com"}], + "cc": [], "bcc": [], + "subject": "June statement available", + "body": "

Your June account statement is now available in the billing portal.

", + "timestamp": "2026-06-20T09:00:00Z", + "read": False, "starred": False, "important": False, + "labels": ["l4"], "category": "primary", "folder": "inbox", "attachments": []}, + {"id": "email_3", "threadId": "thread_3", + "from": {"name": "Lena Ortiz", "email": "lena.ortiz@orionretail.example.com"}, + "to": [{"name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com"}], + "cc": [], "bcc": [], + "subject": "Re: Orion expansion timeline", + "body": "

Hi Jordan, thanks for the proposal — reviewing internally and will " + "circle back next week.

Best,
Lena

", + "timestamp": "2026-06-19T17:40:00Z", + "read": True, "starred": False, "important": False, + "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": []}, + ] + labels = [ + {"id": "l1", "name": "Work", "color": "#ef4444"}, + {"id": "l2", "name": "Personal", "color": "#3b82f6"}, + {"id": "l3", "name": "Travel", "color": "#22c55e"}, + {"id": "l4", "name": "Finance", "color": "#eab308"}, + ] + return {"user": user, "emails": emails, "labels": labels, "drafts": []} + + +def inject(url, state, label): + resp = http_post(f'{url}/post?sid={sid}', {'action': 'set', 'state': state}) + assert resp.status_code == 200, f'{label} injection failed: {resp.status_code} {resp.text}' + go = http_get(f'{url}/go?sid={sid}').json() + assert go.get('initial_state') is not None, f'{label} initial_state is None after injection' + print(f'{label} state injected and verified.') + + +inject(NOTION_URL, build_notion_state(), 'Notion') +inject(SALESFORCE_URL, build_salesforce_state(), 'Salesforce') +inject(DOCUSIGN_URL, build_docusign_state(), 'DocuSign') +inject(GMAIL_URL, build_gmail_state(), 'Gmail') + + +# --- Launch browser (primary mock = Salesforce) --- +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 = SALESFORCE_URL +launch_gui(f'google-chrome "{SALESFORCE_URL}/?sid={sid}"', delay_sec=2.0) +_open_remaining_mock_tabs(_primary_mock_url) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {SALESFORCE_URL}/?sid={sid}') diff --git a/csm_qbr_renewal_003/reward.py b/csm_qbr_renewal_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb8ba98ea6d06a987b4656ca1591594628cc2de --- /dev/null +++ b/csm_qbr_renewal_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: CSM Renewal QBR prep across Notion, Salesforce, DocuSign, Gmail +Task ID: csm_qbr_renewal_003 +Domain: mock_websites (multi-mock) +Scoring (sums to 1.0): + - Notion (0.25): new Aspen QBR agenda page (0.07) + 4 sections each w/ non-empty content (0.18) + - Salesforce (0.30): new QBR event w/ runtime this-Friday time/relation/assignee (0.20) + opp-1 advanced forward, not closed (0.10) + - DocuSign (0.20): env_1 draft->sent w/ recipient sent + distractor env_2 stays draft (compound) + - Gmail (0.25): new sent email to Daniel (0.12) + body walks agenda & references the QBR time (0.13) +All scoring components are anchored to task-introduced changes: each FAILS on initial_env, PASSES on golden_env. +""" +import re +import sys +from datetime import date, timedelta + +import requests + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid empty') +except Exception as e: + print(f'CRITICAL: cannot read /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +MOCKS = { + 'notion': 'http://28.7.184.198:8166', + 'salesforce': 'http://28.7.184.198:8175', + 'docusign': 'http://28.7.184.198:8130', + 'gmail': 'http://28.7.184.198:8138', +} + +# --- Fetch state from all mocks --- +S = {} +for name, url in MOCKS.items(): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + except Exception as e: + print(f'CRITICAL: cannot fetch {name} state: {e}') + print('REWARD: 0.0') + sys.exit(0) + if data.get('current_state') is None: + print(f'CRITICAL: {name} current_state is None') + print('REWARD: 0.0') + sys.exit(0) + S[name] = data + + +def norm(s): + return re.sub(r'[^a-z0-9 ]', '', (s or '').lower()).strip() + + +SECTIONS = ['business goals', 'usage highlights', 'risks', 'next actions'] +MONTH_NAMES = { + 1: ('january', 'jan'), + 2: ('february', 'feb'), + 3: ('march', 'mar'), + 4: ('april', 'apr'), + 5: ('may', 'may'), + 6: ('june', 'jun'), + 7: ('july', 'jul'), + 8: ('august', 'aug'), + 9: ('september', 'sep'), + 10: ('october', 'oct'), + 11: ('november', 'nov'), + 12: ('december', 'dec'), +} + + +def this_friday(today=None): + today = today or date.today() + days_until_friday = (4 - today.weekday()) % 7 + return today + timedelta(days=days_until_friday) + + +def load_target_qbr_date(): + try: + with open('/tmp/task_qbr_date') as f: + return date.fromisoformat(f.read().strip()) + except Exception: + return this_friday() + + +TARGET_QBR_DATE = load_target_qbr_date() +TARGET_QBR_START = (TARGET_QBR_DATE.year, TARGET_QBR_DATE.month, TARGET_QBR_DATE.day, 14, 0) +TARGET_QBR_END = (TARGET_QBR_DATE.year, TARGET_QBR_DATE.month, TARGET_QBR_DATE.day, 14, 45) + + +def parse_datetime_minute(value): + m = re.search(r'(\d{4})-(\d{1,2})-(\d{1,2})[T ](\d{1,2}):(\d{2})', str(value or '')) + if not m: + return None + return tuple(int(x) for x in m.groups()) + + +def datetime_matches(value, target): + return parse_datetime_minute(value) == target + + +def text_mentions_target_date(text): + ntext = norm(text) + year, month, day = TARGET_QBR_DATE.year, TARGET_QBR_DATE.month, TARGET_QBR_DATE.day + full_month, short_month = MONTH_NAMES[month] + date_phrases = { + 'friday', + f'{year} {month:02d} {day:02d}', + f'{year} {month} {day}', + f'{full_month} {day}', + f'{short_month} {day}', + } + return any(phrase in ntext for phrase in date_phrases) + + +def text_mentions_2pm(text): + ntext = norm(text) + return bool(re.search(r'\b2\s*pm\b', ntext) or '200 pm' in ntext or '1400' in ntext) + + +def verify_task(): + total = 0.0 + + # ===================== NOTION (0.25) ===================== + notion_init = S['notion']['initial_state'] + notion_cur = S['notion']['current_state'] + init_page_ids = set(notion_init.get('pages', {}).keys()) + cur_pages = notion_cur.get('pages', {}) + cur_blocks = notion_cur.get('blocks', {}) + + # Find NEW pages whose title references the Aspen QBR agenda + qbr_page = None + for pid, page in cur_pages.items(): + if pid in init_page_ids: + continue + t = norm(page.get('title')) + if 'aspen' in t and ('qbr' in t or 'quarterly business review' in t): + qbr_page = page + break + + # Component N1: new Aspen QBR agenda page exists (0.07) + try: + if qbr_page is not None: + print(f"PASS: Notion new QBR page '{qbr_page.get('title')}' (0.07)") + total += 0.07 + else: + print('FAIL: No NEW Notion page referencing Aspen + QBR found') + except Exception as e: + print(f'ERROR: Notion N1 — {e}') + + # Component N2: four sections, each a heading with >=1 non-empty content block (0.18, 0.045 each) + try: + section_has_content = {s: False for s in SECTIONS} + section_heading_seen = {s: False for s in SECTIONS} + if qbr_page is not None: + block_ids = qbr_page.get('blockIds', []) or [] + current_section = None + for bid in block_ids: + blk = cur_blocks.get(bid) + if not blk: + continue + btype = (blk.get('type') or '') + content = blk.get('content') or '' + ncontent = norm(content) + if btype.startswith('heading'): + # does this heading start a tracked section? + matched = None + for s in SECTIONS: + if ncontent == s or s in ncontent: + matched = s + break + if matched: + current_section = matched + section_heading_seen[matched] = True + else: + current_section = None + else: + # non-heading content block under the current section + if current_section and content.strip(): + section_has_content[current_section] = True + for s in SECTIONS: + if section_heading_seen[s] and section_has_content[s]: + print(f"PASS: Notion section '{s}' has heading + non-empty content (0.045)") + total += 0.045 + else: + print(f"FAIL: Notion section '{s}' heading_seen={section_heading_seen[s]} has_content={section_has_content[s]}") + except Exception as e: + print(f'ERROR: Notion N2 — {e}') + + # ===================== SALESFORCE (0.30) ===================== + sf_init = S['salesforce']['initial_state'] + sf_cur = S['salesforce']['current_state'] + init_act_ids = {a.get('activityId') for a in sf_init.get('activities', [])} + cur_acts = sf_cur.get('activities', []) + + # Component S1: NEW QBR event w/ correct runtime date/time, type, relation, assignee (0.20) + try: + match = None + for a in cur_acts: + if a.get('activityId') in init_act_ids: + continue + if a.get('type') != 'event': + continue + subj = norm(a.get('subject')) + is_qbr = 'qbr' in subj or 'quarterly business review' in subj + is_aspen = 'aspen' in subj + if (is_qbr and is_aspen + and datetime_matches(a.get('startDateTime'), TARGET_QBR_START) + and datetime_matches(a.get('endDateTime'), TARGET_QBR_END) + and a.get('relatedToType') == 'account' + and a.get('relatedToId') == 'account-1' + and a.get('assignedToId') == 'user-1'): + match = a + break + if match: + print(f"PASS: Salesforce new QBR event correct ({TARGET_QBR_DATE.isoformat()} 14:00-14:45, account-1, user-1) (0.20)") + total += 0.20 + else: + print(f'FAIL: No NEW Salesforce QBR event matching {TARGET_QBR_DATE.isoformat()} 14:00-14:45/relation/assignee') + except Exception as e: + print(f'ERROR: Salesforce S1 — {e}') + + # Component S2: opp-1 advanced FORWARD from Qualification, still open (0.10) + try: + FORWARD_OPEN = {'needs analysis', 'value proposition', 'proposal', 'negotiation'} + opp1 = next((o for o in sf_cur.get('opportunities', []) if o.get('opportunityId') == 'opp-1'), None) + stage = norm(opp1.get('stage')) if opp1 else None + if opp1 and stage in FORWARD_OPEN: + print(f"PASS: opp-1 advanced to '{opp1.get('stage')}' (forward, open) (0.10)") + total += 0.10 + else: + print(f"FAIL: opp-1 stage='{opp1.get('stage') if opp1 else None}' not a forward open stage") + except Exception as e: + print(f'ERROR: Salesforce S2 — {e}') + + # ===================== DOCUSIGN (0.20) ===================== + # Compound: env_1 draft->sent w/ recipient sent/delivered AND distractor env_2 stays draft. + # Anchored to the env_1 change so it FAILS on initial (env_1 still draft). + try: + ds_cur = S['docusign']['current_state'] + envs = {e.get('id'): e for e in ds_cur.get('envelopes', [])} + env1 = envs.get('env_1') + env2 = envs.get('env_2') + env1_is_aspen = bool(env1) and 'aspen' in norm(env1.get('subject')) + env1_recips = env1.get('recipients', []) if env1 else [] + daniel = next((r for r in env1_recips if 'daniel.brooks@aspendynamics.com' in (r.get('email') or '').lower()), None) + env1_ok = ( + env1_is_aspen + and env1.get('status') == 'sent' + and bool(env1.get('sentAt')) + and daniel is not None + and daniel.get('status') in ('sent', 'delivered') + ) + env2_still_draft = bool(env2) and env2.get('status') == 'draft' + if env1_ok and env2_still_draft: + print('PASS: DocuSign env_1 sent w/ Daniel sent/delivered AND env_2 stays draft (0.20)') + total += 0.20 + else: + print(f'FAIL: DocuSign env1_ok={env1_ok} env2_still_draft={env2_still_draft}') + except Exception as e: + print(f'ERROR: DocuSign — {e}') + + # ===================== GMAIL (0.25) ===================== + gm_init = S['gmail']['initial_state'] + gm_cur = S['gmail']['current_state'] + init_email_ids = {m.get('id') for m in gm_init.get('emails', [])} + cur_emails = gm_cur.get('emails', []) + + # Find new sent email addressed to Daniel + new_sent = None + for m in cur_emails: + if m.get('id') in init_email_ids: + continue + if m.get('folder') != 'sent': + continue + tos = m.get('to') or [] + if any('daniel.brooks@aspendynamics.com' in (t.get('email') or '').lower() for t in tos): + new_sent = m + break + + # Component G1: new sent email to Daniel w/ non-empty subject (0.12) + try: + if new_sent and (new_sent.get('subject') or '').strip(): + print(f"PASS: Gmail new sent email to Daniel, subject='{new_sent.get('subject')}' (0.12)") + total += 0.12 + else: + print('FAIL: No new sent email to daniel.brooks@aspendynamics.com with non-empty subject') + except Exception as e: + print(f'ERROR: Gmail G1 — {e}') + + # Component G2: body walks agenda (>=3 of 4 sections) + references runtime QBR date/time (0.13) + try: + if new_sent: + body = (new_sent.get('body') or '') + nbody = norm(body) + sections_hit = sum(1 for s in SECTIONS if s in nbody) + mentions_qbr_date = text_mentions_target_date(body) + mentions_qbr_time = text_mentions_2pm(body) + # award proportionally: agenda walk-through 0.07, date 0.03, 2PM 0.03 + sub = 0.0 + if sections_hit >= 3: + sub += 0.07 + print(f'PASS: Gmail body walks agenda ({sections_hit}/4 sections) (0.07)') + else: + print(f'FAIL: Gmail body mentions only {sections_hit}/4 agenda sections') + if mentions_qbr_date: + sub += 0.03 + print(f'PASS: Gmail body references QBR date {TARGET_QBR_DATE.isoformat()} (0.03)') + else: + print(f'FAIL: Gmail body does not reference QBR date {TARGET_QBR_DATE.isoformat()}') + if mentions_qbr_time: + sub += 0.03 + print('PASS: Gmail body names 2 PM time (0.03)') + else: + print('FAIL: Gmail body does not name 2 PM time') + total += sub + else: + print('FAIL: Gmail G2 — no sent email to evaluate body') + except Exception as e: + print(f'ERROR: Gmail G2 — {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/csm_qbr_renewal_003/reward_label.json b/csm_qbr_renewal_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..0ce5884baa8442bb0b6655c7629e8bd8aa578911 --- /dev/null +++ b/csm_qbr_renewal_003/reward_label.json @@ -0,0 +1,87 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_qbr_renewal_003/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-03 20:22:31", + "label": { + "task_id": "csm_qbr_renewal_003", + "domain": "mock_websites", + "summary": "验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为,包括创建 QBR 议程页面、安排会议事件、推进销售机会、发送 DocuSign 信封以及发送包含议程和会议时间的邮件。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "/tmp/task_qbr_date", + "http://28.7.186.212:8186 (notion)", + "http://28.7.186.212:8195 (salesforce)", + "http://28.7.186.212:8150 (docusign)", + "http://28.7.186.212:8158 (gmail)" + ], + "scoring_components": [ + { + "name": "Notion N1", + "weight": 0.07, + "description": "新建 Aspen QBR 议程页面", + "check_logic": "遍历 current_state.pages,排除 initial_state 中已存在的 pageId,检查是否有页面标题经 norm 处理后同时包含 'aspen' 和 'qbr'(或 'quarterly business review')", + "pass_condition": "存在一个新的 Notion 页面,其标题同时提及 Aspen 和 QBR" + }, + { + "name": "Notion N2", + "weight": 0.18, + "description": "四个指定 section 均包含 heading 和非空内容", + "check_logic": "在 qbr_page 的 blockIds 中顺序遍历 block,识别 heading 类型块是否匹配 SECTIONS(business goals、usage highlights、risks、next actions)之一;匹配后,后续非 heading 块若 content.strip() 非空,则标记该 section 有内容。每个 section 独立计分 0.045。", + "pass_condition": "四个 section 每个都必须出现对应的 heading 且在该 heading 下至少有一个非空的非 heading 内容块" + }, + { + "name": "Salesforce S1", + "weight": 0.2, + "description": "新建 QBR 事件,时间、关联对象和负责人正确", + "check_logic": "遍历 current_state.activities,排除 initial_state 中已有的 activityId,筛选 type='event' 且 subject 经 norm 后包含 'qbr' 和 'aspen' 的新活动;检查 startDateTime 匹配 TARGET_QBR_START(目标日期 14:00)、endDateTime 匹配 TARGET_QBR_END(目标日期 14:45)、relatedToType='account'、relatedToId='account-1'、assignedToId='user-1'。", + "pass_condition": "存在一个新的 Event,主题为 Aspen QBR,开始时间为目标日期 14:00,结束时间为 14:45,关联 account-1,负责人为 user-1" + }, + { + "name": "Salesforce S2", + "weight": 0.1, + "description": "机会 opp-1 向前推进且仍处于开放阶段", + "check_logic": "在 current_state.opportunities 中查找 opportunityId='opp-1',将其 stage 经 norm 后与集合 {'needs analysis', 'value proposition', 'proposal', 'negotiation'} 比对。", + "pass_condition": "opp-1 的阶段为 Needs Analysis、Value Proposition、Proposal 或 Negotiation(即向前推进且未关闭)" + }, + { + "name": "DocuSign", + "weight": 0.2, + "description": "env_1 发送给 Daniel 且 distractor env_2 保持草稿", + "check_logic": "检查 current_state.envelopes 中 id='env_1' 的 envelope:subject 经 norm 后包含 'aspen',status='sent',sentAt 非空,收件人列表中存在 email 包含 'daniel.brooks@aspendynamics.com' 且其 status 为 'sent' 或 'delivered';同时 id='env_2' 的 envelope status 必须为 'draft'。两者同时满足才得分。", + "pass_condition": "env_1 状态为 sent、主题含 Aspen、Daniel 的收件人状态为 sent/delivered,且 env_2 状态仍为 draft" + }, + { + "name": "Gmail G1", + "weight": 0.12, + "description": "新建发送给 Daniel 的邮件且主题非空", + "check_logic": "遍历 current_state.emails,排除 initial_state 中已有的 id,筛选 folder='sent' 且 to 列表中任一收件人 email 包含 'daniel.brooks@aspendynamics.com' 的新邮件,并检查 subject 经 strip 后非空。", + "pass_condition": "存在一封新的 sent 邮件发送给 daniel.brooks@aspendynamics.com,且主题非空" + }, + { + "name": "Gmail G2", + "weight": 0.13, + "description": "邮件正文包含议程、QBR 日期和 2PM 时间", + "check_logic": "对 new_sent.body 进行 norm 处理,统计包含 SECTIONS 中至少 3 个 section 名称(得 0.07);检查正文是否通过 text_mentions_target_date 提及目标 QBR 日期(得 0.03);检查是否通过 text_mentions_2pm 提及 2 PM(得 0.03)。三个子条件分数累加为 sub 后加入 total。", + "pass_condition": "正文至少提及 4 个议程 section 中的 3 个、提及目标 QBR 日期、并提及 2 PM 时间" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限后四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)", + "从任一 mock 服务(notion/salesforce/docusign/gmail)拉取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)", + "任一 mock 返回的 current_state 为 None:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)", + "Notion 未找到新的 Aspen QBR 页面:N1 和 N2 均不得分", + "Salesforce 未找到符合条件的新 QBR Event:S1 不得分", + "opp-1 阶段未前进或已关闭:S2 不得分", + "DocuSign env_1 未发送或 Daniel 状态不对,或 env_2 不再是 draft:DocuSign 组件 0.20 分全部丢失", + "Gmail 未找到发给 Daniel 的新 sent 邮件:G1 和 G2 均不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,并依次从 notion、salesforce、docusign、gmail 四个 mock 服务拉取 initial_state 与 current_state;同时从 /tmp/task_qbr_date 加载目标日期(或默认取本周五)。随后按顺序执行验证:1) Notion 部分查找标题同时包含 Aspen 和 QBR 的新页面(0.07),并检查该页面是否包含 business goals、usage highlights、risks、next actions 四个 section 的 heading 及非空内容(每个 0.045);2) Salesforce 部分查找新的 Event,验证其主题、目标日期 14:00-14:45 的时间、关联 account-1 及负责人 user-1(0.20),并检查 opp-1 的阶段是否推进到开放的前进阶段(0.10);3) DocuSign 部分验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 distractor env_2 必须保持 draft(0.20);4) Gmail 部分查找发给 Daniel 的新 sent 邮件,验证主题非空(0.12),并检查正文是否至少提及 3 个议程 section(0.07)、目标 QBR 日期(0.03)和 2 PM 时间(0.03)。所有子项分数累加,最终通过 min(total, 1.0) 限制上限并四舍五入输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: csm_qbr_renewal_003\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock)\"\n3. **summary**: 一句话概括。这个脚本验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: 脚本从以下 mock 服务获取状态:\n - notion: http://28.7.186.212:8186\n - salesforce: http://28.7.186.212:8195\n - docusign: http://28.7.186.212:8150\n - gmail: http://28.7.186.212:8158\n - /tmp/task_web_sid (读取 sid)\n - /tmp/task_qbr_date (读取目标 QBR 日期)\n\n6. **scoring_components**: 需要详细列出各个组件:\n - Notion N1: 0.07 - 新建 Aspen QBR agenda 页面\n - Notion N2: 0.18 (4 * 0.045) - 四个 section 每个都有 heading 和非空内容\n - Salesforce S1: 0.20 - 新建 QBR event,正确时间/关系/负责人\n - Salesforce S2: 0.10 - opp-1 推进到前进阶段且未关闭\n - DocuSign: 0.20 - env_1 从 draft 变为 sent 且 Daniel 状态为 sent/delivered,env_2 保持 draft\n - Gmail G1: 0.12 - 新建发送给 Daniel 的邮件,主题非空\n - Gmail G2: 0.13 (0.07 + 0.03 + 0.03) - 邮件正文包含至少3个 agenda section、提及 QBR 日期、提及 2PM 时间\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后用 min(total, 1.0) 钳制到上限,并四舍五入到4位小数。\n9. **failure_modes**: \n - 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 无法从任一 mock 服务获取状态 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 任一 mock 返回 current_state 为 None -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出(除了 DocuSign 是复合检查,必须同时满足两个条件)\n\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID\n - 从四个 mock 服务(Notion、Salesforce、DocuSign、Gmail)拉取 initial_state 和 current_state\n - 加载目标 QBR 日期(从 /tmp/task_qbr_date 或计算本周五)\n - Notion 检查:查找标题包含 Aspen 和 QBR 的新页面;检查四个指定 section 是否有 heading 和非空内容块\n - Salesforce 检查:查找新的 QBR event,验证时间、关联账户、负责人;检查 opp-1 阶段是否向前推进且未关闭\n - DocuSign 检查:验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 env_2 保持 draft\n - Gmail 检查:查找发给 Daniel 的新 sent 邮件,验证主题非空;验证正文包含至少3个 agenda section、提及 QBR 日期和 2PM 时间\n - 汇总所有得分,上限 1.0,输出 REWARD\n\n11. **confidence**: 1.0,因为代码逻辑清晰完整。\n\n让我再仔细检查一下各个组件的权重和逻辑:\n\nNotion:\n- N1: 0.07 (代码中 total += 0.07)\n- N2: 每个 section 0.045,共 4 个,总计 0.18 (代码中 total += 0.045 在循环里)\n\nSalesforce:\n- S1: 0.20 (代码中 total += 0.20)\n- S2: 0.10 (代码中 total += 0.10)\n\nDocuSign:\n- 0.20 (代码中 total += 0.20) - 这是一个复合条件,必须同时满足 env1_ok 和 env2_still_draft\n\nGmail:\n- G1: 0.12 (代码中 total += 0.12)\n- G2: 0.13,但内部是细分的:\n - sections_hit >= 3: 0.07\n - mentions_qbr_date: 0.03\n - mentions_qbr_time: 0.03\n 总计 0.13,代码中是 sub += ... 然后 total += sub\n\nTotal: 0.07 + 0.18 + 0.20 + 0.10 + 0.20 + 0.12 + 0.13 = 1.00\n\nScore aggregation: 各组件分数累加,最终 `round(min(total, 1.0), 4)`\n\nFailure modes:\n- /tmp/task_web_sid 读取失败\n- mock 状态拉取失败\n- current_state 为 None\n- 各检查项不满足(不加分)\n\n我需要确保 JSON 格式完全符合要求:\n- 不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- 不要额外解释\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"csm_qbr_renewal_003\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为,包括创建 QBR 议程页面、安排会议事件、推进销售机会、发送 DocuSign 信封以及发送包含议程和会议时间的邮件。\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"/tmp/task_qbr_date\",\n \"http://28.7.186.212:8186 (notion)\",\n \"http://28.7.186.212:8195 (salesforce)\",\n \"http://28.7.186.212:8150 (docusign)\",\n \"http://28.7.186.212:8158 (gmail)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Notion N1\",\n \"weight\": 0.07,\n \"description\": \"新建 Aspen QBR 议程页面\",\n \"check_logic\": \"遍历 current_state.pages,排除 initial_state 中已存在的 pageId,检查是否有页面标题经 norm 处理后同时包含 'aspen' 和 'qbr'(或 'quarterly business review')\",\n \"pass_condition\": \"存在一个新的 Notion 页面,其标题同时提及 Aspen 和 QBR\"\n },\n {\n \"name\": \"Notion N2\",\n \"weight\": 0.18,\n \"description\": \"四个指定 section 均包含 heading 和非空内容\",\n \"check_logic\": \"在 qbr_page 的 blockIds 中顺序遍历 block,识别 heading 类型块是否匹配 SECTIONS(business goals、usage highlights、risks、next actions)之一;匹配后,后续非 heading 块若 content.strip() 非空,则标记该 section 有内容。每个 section 独立计分 0.045。\",\n \"pass_condition\": \"四个 section 每个都必须出现对应的 heading 且在该 heading 下至少有一个非空的非 heading 内容块\"\n },\n {\n \"name\": \"Salesforce S1\",\n \"weight\": 0.20,\n \"description\": \"新建 QBR 事件,时间、关联对象和负责人正确\",\n \"check_logic\": \"遍历 current_state.activities,排除 initial_state 中已有的 activityId,筛选 type='event' 且 subject 经 norm 后包含 'qbr' 和 'aspen' 的新活动;检查 startDateTime 匹配 TARGET_QBR_START(目标日期 14:00)、endDateTime 匹配 TARGET_QBR_END(目标日期 14:45)、relatedToType='account'、relatedToId='account-1'、assignedToId='user-1'。\",\n \"pass_condition\": \"存在一个新的 Event,主题为 Aspen QBR,开始时间为目标日期 14:00,结束时间为 14:45,关联 account-1,负责人为 user-1\"\n },\n {\n \"name\": \"Salesforce S2\",\n \"weight\": 0.10,\n \"description\": \"机会 opp-1 向前推进且仍处于开放阶段\",\n \"check_logic\": \"在 current_state.opportunities 中查找 opportunityId='opp-1',将其 stage 经 norm 后与集合 {'needs analysis', 'value proposition', 'proposal', 'negotiation'} 比对。\",\n \"pass_condition\": \"opp-1 的阶段为 Needs Analysis、Value Proposition、Proposal 或 Negotiation(即向前推进且未关闭)\"\n },\n {\n \"name\": \"DocuSign\",\n \"weight\": 0.20,\n \"description\": \"env_1 发送给 Daniel 且 distractor env_2 保持草稿\",\n \"check_logic\": \"检查 current_state.envelopes 中 id='env_1' 的 envelope:subject 经 norm 后包含 'aspen',status='sent',sentAt 非空,收件人列表中存在 email 包含 'daniel.brooks@aspendynamics.com' 且其 status 为 'sent' 或 'delivered';同时 id='env_2' 的 envelope status 必须为 'draft'。两者同时满足才得分。\",\n \"pass_condition\": \"env_1 状态为 sent、主题含 Aspen、Daniel 的收件人状态为 sent/delivered,且 env_2 状态仍为 draft\"\n },\n {\n \"name\": \"Gmail G1\",\n \"weight\": 0.12,\n \"description\": \"新建发送给 Daniel 的邮件且主题非空\",\n \"check_logic\": \"遍历 current_state.emails,排除 initial_state 中已有的 id,筛选 folder='sent' 且 to 列表中任一收件人 email 包含 'daniel.brooks@aspendynamics.com' 的新邮件,并检查 subject 经 strip 后非空。\",\n \"pass_condition\": \"存在一封新的 sent 邮件发送给 daniel.brooks@aspendynamics.com,且主题非空\"\n },\n {\n \"name\": \"Gmail G2\",\n \"weight\": 0.13,\n \"description\": \"邮件正文包含议程、QBR 日期和 2PM 时间\",\n \"check_logic\": \"对 new_sent.body 进行 norm 处理,统计包含 SECTIONS 中至少 3 个 section 名称(得 0.07);检查正文是否通过 text_mentions_target_date 提及目标 QBR 日期(得 0.03);检查是否通过 text_mentions_2pm 提及 2 PM(得 0.03)。三个子条件分数累加为 sub 后加入 total。\",\n \"pass_condition\": \"正文至少提及 4 个议程 section 中的 3 个、提及目标 QBR 日期、并提及 2 PM 时间\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限后四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\n \"从任一 mock 服务(notion/salesforce/docusign/gmail)拉取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\n \"任一 mock 返回的 current_state 为 None:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\n \"Notion 未找到新的 Aspen QBR 页面:N1 和 N2 均不得分\",\n \"Salesforce 未找到符合条件的新 QBR Event:S1 不得分\",\n \"opp-1 阶段未前进或已关闭:S2 不得分\",\n \"DocuSign env_1 未发送或 Daniel 状态不对,或 env_2 不再是 draft:DocuSign 组件 0.20 分全部丢失\",\n \"Gmail 未找到发给 Daniel 的新 sent 邮件:G1 和 G2 均不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,并依次从 notion、salesforce、docusign、gmail 四个 mock 服务拉取 initial_state 与 current_state;同时从 /tmp/task_qbr_date 加载目标日期(或默认取本周五)。随后按顺序执行验证:1) Notion 部分查找标题同时包含 Aspen 和 QBR 的新页面(0.07),并检查该页面是否包含 business goals、usage highlights、risks、next actions 四个 section 的 heading 及非空内容(每个 0.045);2) Salesforce 部分查找新的 Event,验证其主题、目标日期 14:00-14:45 的时间、关联 account-1 及负责人 user-1(0.20),并检查 opp-1 的阶段是否推进到开放的前进阶段(0.10);3) DocuSign 部分验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 distractor env_2 必须保持 draft(0.20);4) Gmail 部分查找发给 Daniel 的新 sent 邮件,验证主题非空(0.12),并检查正文是否至少提及 3 个议程 section(0.07)、目标 QBR 日期(0.03)和 2 PM 时间(0.03)。所有子项分数累加,最终通过 min(total, 1.0) 限制上限并四舍五入输出。\",\n \"confidence\": 1.0\n}\n```\n\n我需要确保没有使用 Markdown 代码块,且输出严格是 JSON。让我再检查一下 domain,docstring 写的是 \"mock_websites (multi-mock)\",我应该保留为 \"mock_websites\" 还是原样?用户说 \"如 mock_websites / software_engineer / libreoffice_calc\",所以 \"mock_websites\" 应该可以。或者我可以写 \"mock_websites (multi-mock)\"?用户说 \"从 docstring 中提取的领域\",docstring 中明确写了 \"Domain: mock_websites (multi-mock)\"。为了准确,我应该保留原样或至少保留核心。看示例是保留主要标识,我会用 \"mock_websites\" 因为示例里就是这样用的。\n\n再检查 data_sources,用户示例里有 \"slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid\"。我应该列出具体的 URL 或服务名。我会用 \"notion_mock\"、\"salesforce_mock\"、\"docusign_mock\"、\"gmail_mock\" 还是具体 URL?代码里用的是 MOCKS 字典,URL 是具体的 IP:端口。我会写 URL 并标注名称,这样更准确。\n\n再检查 weight 字段。Gmail G2 的 weight 应该是 0.13,虽然内部是 0.07+0.03+0.03,但作为一个组件整体是 0.13。或者我应该拆成三个子组件?用户要求列出组件,我可以把 G2 作为一个组件,weight 0.13,在 check_logic 中说明内部分数。这样比较合理,因为代码里它们是放在一个 try 块里并累加到 sub 再 total += sub。\n\nDocuSign 也是一个整体 0.20 的复合组件。\n\nNotion N2 是 0.18 整体,内部 4 个 0.045。我可以作为一个组件 weight 0.18。\n\n这样组件列表就是:\n- Notion N1: 0.07\n- Notion N2: 0.18\n- Salesforce S1: 0.20\n- Salesforce S2: 0.10\n- DocuSign: 0.20\n- Gmail G1: 0.12\n- Gmail G2: 0.13\n\n总和正好是 1.0。\n\n最后确认 JSON 格式正确,没有 trailing comma,所有字符串正确转义。 {\"task_id\":\"csm_qbr_renewal_003\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为,包括创建 QBR 议程页面、安排会议事件、推进销售机会、发送 DocuSign 信封以及发送包含议程和会议时间的邮件。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"/tmp/task_qbr_date\",\"http://28.7.186.212:8186 (notion)\",\"http://28.7.186.212:8195 (salesforce)\",\"http://28.7.186.212:8150 (docusign)\",\"http://28.7.186.212:8158 (gmail)\"],\"scoring_components\":[{\"name\":\"Notion N1\",\"weight\":0.07,\"description\":\"新建 Aspen QBR 议程页面\",\"check_logic\":\"遍历 current_state.pages,排除 initial_state 中已存在的 pageId,检查是否有页面标题经 norm 处理后同时包含 'aspen' 和 'qbr'(或 'quarterly business review')\",\"pass_condition\":\"存在一个新的 Notion 页面,其标题同时提及 Aspen 和 QBR\"},{\"name\":\"Notion N2\",\"weight\":0.18,\"description\":\"四个指定 section 均包含 heading 和非空内容\",\"check_logic\":\"在 qbr_page 的 blockIds 中顺序遍历 block,识别 heading 类型块是否匹配 SECTIONS(business goals、usage highlights、risks、next actions)之一;匹配后,后续非 heading 块若 content.strip() 非空,则标记该 section 有内容。每个 section 独立计分 0.045。\",\"pass_condition\":\"四个 section 每个都必须出现对应的 heading 且在该 heading 下至少有一个非空的非 heading 内容块\"},{\"name\":\"Salesforce S1\",\"weight\":0.20,\"description\":\"新建 QBR 事件,时间、关联对象和负责人正确\",\"check_logic\":\"遍历 current_state.activities,排除 initial_state 中已有的 activityId,筛选 type='event' 且 subject 经 norm 后包含 'qbr' 和 'aspen' 的新活动;检查 startDateTime 匹配 TARGET_QBR_START(目标日期 14:00)、endDateTime 匹配 TARGET_QBR_END(目标日期 14:45)、relatedToType='account'、relatedToId='account-1'、assignedToId='user-1'。\",\"pass_condition\":\"存在一个新的 Event,主题为 Aspen QBR,开始时间为目标日期 14:00,结束时间为 14:45,关联 account-1,负责人为 user-1\"},{\"name\":\"Salesforce S2\",\"weight\":0.10,\"description\":\"机会 opp-1 向前推进且仍处于开放阶段\",\"check_logic\":\"在 current_state.opportunities 中查找 opportunityId='opp-1',将其 stage 经 norm 后与集合 {'needs analysis', 'value proposition', 'proposal', 'negotiation'} 比对。\",\"pass_condition\":\"opp-1 的阶段为 Needs Analysis、Value Proposition、Proposal 或 Negotiation(即向前推进且未关闭)\"},{\"name\":\"DocuSign\",\"weight\":0.20,\"description\":\"env_1 发送给 Daniel 且 distractor env_2 保持草稿\",\"check_logic\":\"检查 current_state.envelopes 中 id='env_1' 的 envelope:subject 经 norm 后包含 'aspen',status='sent',sentAt 非空,收件人列表中存在 email 包含 'daniel.brooks@aspendynamics.com' 且其 status 为 'sent' 或 'delivered';同时 id='env_2' 的 envelope status 必须为 'draft'。两者同时满足才得分。\",\"pass_condition\":\"env_1 状态为 sent、主题含 Aspen、Daniel 的收件人状态为 sent/delivered,且 env_2 状态仍为 draft\"},{\"name\":\"Gmail G1\",\"weight\":0.12,\"description\":\"新建发送给 Daniel 的邮件且主题非空\",\"check_logic\":\"遍历 current_state.emails,排除 initial_state 中已有的 id,筛选 folder='sent' 且 to 列表中任一收件人 email 包含 'daniel.brooks@aspendynamics.com' 的新邮件,并检查 subject 经 strip 后非空。\",\"pass_condition\":\"存在一封新的 sent 邮件发送给 daniel.brooks@aspendynamics.com,且主题非空\"},{\"name\":\"Gmail G2\",\"weight\":0.13,\"description\":\"邮件正文包含议程、QBR 日期和 2PM 时间\",\"check_logic\":\"对 new_sent.body 进行 norm 处理,统计包含 SECTIONS 中至少 3 个 section 名称(得 0.07);检查正文是否通过 text_mentions_target_date 提及目标 QBR 日期(得 0.03);检查是否通过 text_mentions_2pm 提及 2 PM(得 0.03)。三个子条件分数累加为 sub 后加入 total。\",\"pass_condition\":\"正文至少提及 4 个议程 section 中的 3 个、提及目标 QBR 日期、并提及 2 PM 时间\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限后四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\"从任一 mock 服务(notion/salesforce/docusign/gmail)拉取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\"任一 mock 返回的 current_state 为 None:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\"Notion 未找到新的 Aspen QBR 页面:N1 和 N2 均不得分\",\"Salesforce 未找到符合条件的新 QBR Event:S1 不得分\",\"opp-1 阶段未前进或已关闭:S2 不得分\",\"DocuSign env_1 未发送或 Daniel 状态不对,或 env_2 不再是 draft:DocuSign 组件 0.20 分全部丢失\",\"Gmail 未找到发给 Daniel 的新 sent 邮件:G1 和 G2 均不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,并依次从 notion、salesforce、docusign、gmail 四个 mock 服务拉取 initial_state 与 current_state;同时从 /tmp/task_qbr_date 加载目标日期(或默认取本周五)。随后按顺序执行验证:1) Notion 部分查找标题同时包含 Aspen 和 QBR 的新页面(0.07),并检查该页面是否包含 business goals、usage highlights、risks、next actions 四个 section 的 heading 及非空内容(每个 0.045);2) Salesforce 部分查找新的 Event,验证其主题、目标日期 14:00-14:45 的时间、关联 account-1 及负责人 user-1(0.20),并检查 opp-1 的阶段是否推进到开放的前进阶段(0.10);3) DocuSign 部分验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 distractor env_2 必须保持 draft(0.20);4) Gmail 部分查找发给 Daniel 的新 sent 邮件,验证主题非空(0.12),并检查正文是否至少提及 3 个议程 section(0.07)、目标 QBR 日期(0.03)和 2 PM 时间(0.03)。所有子项分数累加,最终通过 min(total, 1.0) 限制上限并四舍五入输出。\",\"confidence\":1.0}" +} diff --git a/csops_p1_incident_002/_cua_gym_vm_bridge.sh b/csops_p1_incident_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csops_p1_incident_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/csops_p1_incident_002/initial_setup.py b/csops_p1_incident_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7f84b418ce8c6b7dccea1b9ef2c37e0c60f49125 --- /dev/null +++ b/csops_p1_incident_002/initial_setup.py @@ -0,0 +1,583 @@ +# --- 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: P1 incident pipeline — stand up incident record across Slack/Jira/Salesforce/Notion +Task ID: csops_p1_incident_002 +Domain: mock_websites +Mocks: slack_mock, jira_mock, salesforce_mock, notion_mock +""" +import json +import os +import shlex +import subprocess +import time + +import requests + +TASK_ID = 'csops_p1_incident_pipeline_003' + +# --- Mock registry --- +MOCKS = { + 'slack': 'http://28.7.184.198:8178', + 'jira': 'http://28.7.184.198:8153', + 'salesforce': 'http://28.7.184.198:8175', + 'notion': 'http://28.7.184.198:8166', +} +PRIMARY_URL = MOCKS['slack'] + +# --- Session id --- +# Deterministic INITIAL sid. golden_patch.py uses a DISTINCT golden sid so the two +# VMs (which share the remote mock server but no filesystem) stay isolated. Shared +# across all four mocks here. +sid = f'cuagym-{TASK_ID}-initial' +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + +# --- §1.5 Egress proxy helper (MANDATORY) --- +PROXY_CANDIDATES = [ + os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'), + None, +] + + +def resolve_proxy(probe_url): + try: + requests.get(probe_url, timeout=8) + return None + except Exception: + pass + for candidate in PROXY_CANDIDATES: + if not candidate: + continue + try: + requests.get(probe_url, timeout=12, + proxies={'http': candidate, 'https': candidate}) + return candidate + except Exception: + continue + raise RuntimeError('No working route to mock servers; direct and proxy attempts failed') + + +PROXY = resolve_proxy(f'{PRIMARY_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +# ========================================================================== +# SLACK initial state +# ========================================================================== +def build_slack(): + users = [ + {"userId": "user_1", "fullName": "John Smith", "displayName": "John", + "email": "john.smith@acme.com", "avatar": "https://picsum.photos/200/200?random=1", + "title": "Incident Commander", "status": "online", "statusMessage": "", + "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_2", "fullName": "Priya Nair", "displayName": "Priya", + "email": "priya.nair@acme.com", "avatar": "https://picsum.photos/200/200?random=2", + "title": "Customer Success Manager", "status": "online", "statusMessage": "", + "statusEmoji": "", "timeZone": "America/Los_Angeles"}, + {"userId": "user_5", "fullName": "Raj Patel", "displayName": "Raj", + "email": "raj.patel@acme.com", "avatar": "https://picsum.photos/200/200?random=5", + "title": "Platform Engineer", "status": "online", "statusMessage": "", + "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_8", "fullName": "Sarah Lee", "displayName": "Sarah", + "email": "sarah.lee@acme.com", "avatar": "https://picsum.photos/200/200?random=8", + "title": "On-call SRE", "status": "online", "statusMessage": "Firefighting", + "statusEmoji": "🔥", "timeZone": "America/New_York"}, + ] + current_user = dict(users[0]) + + channels = [ + {"channelId": "incidents", "name": "incidents", + "description": "Major incident coordination", "topic": "P1/P2 incident response", + "isPrivate": False, "isStarred": True, "members": ["user_1", "user_2", "user_5", "user_8"], + "createdBy": "user_1", "createdAt": "2025-09-01T09:00:00Z", + "pinnedMessages": [], "unreadCount": 4}, + {"channelId": "general", "name": "general", "description": "Company-wide chat", + "topic": "", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_5", "user_8"], "createdBy": "user_1", + "createdAt": "2025-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "engineering", "name": "engineering", "description": "Engineering team", + "topic": "", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_5", "user_8"], "createdBy": "user_5", + "createdAt": "2025-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ] + + messages = { + "incidents": [ + {"messageId": "msg_p1", "senderId": "user_8", + "content": "\U0001F534 Customer-declared P1: Contoso Bank says production SSO login is completely down since 14:05 UTC and about 4,000 users are locked out of banking operations. Treat this as highest severity.", + "timestamp": "2026-06-24T14:05:00Z", "threadId": "thread_p1", + "reactions": [{"emoji": "eyes", "users": ["user_1", "user_2"]}], + "attachments": [], "isEdited": False}, + {"messageId": "msg_customer_declared", "senderId": "user_2", + "content": "Direct customer statement from Helen Whitaker, Contoso Bank VP of IT: \"We are declaring this a critical severity incident. Our employees cannot access production systems through SSO, customer support is flooded, and executive banking operations are blocked. Please escalate immediately.\" Salesforce case 00010234 is the customer escalation.", + "timestamp": "2026-06-24T14:12:00Z", "threadId": "thread_p1", + "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_t1", "senderId": "user_8", + "content": "14:20 Confirmed SAML assertions rejected after today's auth-service deploy.", + "timestamp": "2026-06-24T14:20:00Z", "threadId": "thread_p1", + "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_t2", "senderId": "user_8", + "content": "14:35 Rolling back the deploy, monitoring.", + "timestamp": "2026-06-24T14:35:00Z", "threadId": "thread_p1", + "reactions": [], "attachments": [], "isEdited": False}, + ], + "general": [ + {"messageId": "msg_g1", "senderId": "user_2", + "content": "Reminder: lunch & learn moved to Thursday.", + "timestamp": "2026-06-23T11:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + "engineering": [ + {"messageId": "msg_e1", "senderId": "user_5", + "content": "Auth-service v2.7.1 deploying to prod this afternoon.", + "timestamp": "2026-06-24T13:30:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + } + + threads = { + "thread_p1": {"threadId": "thread_p1", "parentMessageId": "msg_p1", + "channelId": "incidents", "dmId": None, + "replies": ["msg_customer_declared", "msg_t1", "msg_t2"], + "followers": ["user_1", "user_2", "user_8"]}, + } + + return { + "currentUser": current_user, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", "icon": ""}, + "users": users, + "channels": channels, + "messages": messages, + "threads": threads, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", + "displayDensity": "comfortable", "showAvatars": True, "use24Hour": True}, + "invitations": [], + "notifications": [], + } + + +# ========================================================================== +# JIRA initial state +# ========================================================================== +def build_jira(): + users = [ + {"id": "u1", "name": "Admin User", "email": "admin@acme.com", + "avatar": "https://picsum.photos/100/100?random=u1"}, + {"id": "u_eng", "name": "Raj Patel", "email": "raj.patel@acme.com", + "avatar": "https://picsum.photos/100/100?random=ueng"}, + {"id": "u_eng2", "name": "Elena Rossi", "email": "elena.rossi@acme.com", + "avatar": "https://picsum.photos/100/100?random=ueng2"}, + {"id": "u_pm", "name": "Daniel Okoye", "email": "daniel.okoye@acme.com", + "avatar": "https://picsum.photos/100/100?random=upm"}, + ] + projects = [ + {"id": "p_sup", "key": "SUP", "name": "Support Engineering", "leadId": "u_pm", + "category": "Software", "icon": "https://picsum.photos/64/64?random=psup"}, + ] + sprints = [ + {"id": "s_sup1", "projectId": "p_sup", "name": "SUP Sprint 14", + "goal": "Platform reliability hardening", "startDate": "2026-06-15T12:00:00.000Z", + "endDate": "2026-06-29T12:00:00.000Z", "state": "active"}, + ] + issues = [ + {"id": "i_sup1", "key": "SUP-1", "projectId": "p_sup", + "summary": "Intermittent 502s from EU API gateway", + "description": "Customers in eu-west see sporadic 502 responses during peak hours.", + "type": "Bug", "status": "In Progress", "priority": "High", "storyPoints": 3, + "reporterId": "u_pm", "assigneeId": "u_eng2", "sprintId": "s_sup1", "epicId": None, + "labels": ["reliability"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-06-16T09:00:00.000Z", "updatedAt": "2026-06-20T15:00:00.000Z"}, + {"id": "i_sup2", "key": "SUP-2", "projectId": "p_sup", + "summary": "Add structured logging to auth-service", + "description": "Improve observability ahead of the next auth-service release.", + "type": "Task", "status": "To Do", "priority": "Medium", "storyPoints": 5, + "reporterId": "u_pm", "assigneeId": "u_eng", "sprintId": "s_sup1", "epicId": None, + "labels": ["observability"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-06-17T10:30:00.000Z", "updatedAt": "2026-06-17T10:30:00.000Z"}, + {"id": "i_sup3", "key": "SUP-3", "projectId": "p_sup", + "summary": "Upgrade SAML library to 4.2", + "description": "Routine dependency bump for the SSO integration layer.", + "type": "Task", "status": "Done", "priority": "Low", "storyPoints": 2, + "reporterId": "u_eng2", "assigneeId": "u_eng2", "sprintId": "s_sup1", "epicId": None, + "labels": ["sso"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-06-10T08:00:00.000Z", "updatedAt": "2026-06-12T14:00:00.000Z"}, + ] + return { + "currentUser": dict(users[0]), + "users": users, + "projects": projects, + "sprints": sprints, + "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": [], + } + + +# ========================================================================== +# SALESFORCE initial state +# ========================================================================== +def build_salesforce(): + users = [ + {"userId": "user-1", "firstName": "John", "lastName": "Smith", + "email": "john.smith@acme.com", "phone": "(555) 123-4567", + "title": "Sales Manager", "department": "Sales", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", "timezone": "America/New_York", + "locale": "en-US", "theme": "lightning"}, + {"userId": "user-2", "firstName": "Priya", "lastName": "Nair", + "email": "priya.nair@acme.com", "phone": "(555) 222-8181", + "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM", + "avatar": "https://i.pravatar.cc/150?u=user-2", "timezone": "America/Los_Angeles", + "locale": "en-US", "theme": "lightning"}, + ] + accounts = [ + {"accountId": "account-contoso", "name": "Contoso Bank", "type": "Customer", + "industry": "Financial Services", "revenue": 4200000000, "employees": 18000, + "ownerId": "user-2", "billingStreet": "1 Finance Plaza", "billingCity": "New York", + "billingState": "NY", "billingZip": "10004", "billingCountry": "USA", + "shippingStreet": "1 Finance Plaza", "shippingCity": "New York", + "shippingState": "NY", "shippingZip": "10004", "shippingCountry": "USA"}, + {"accountId": "account-globex", "name": "Globex Corporation", "type": "Customer", + "industry": "Manufacturing", "revenue": 800000000, "employees": 5200, + "ownerId": "user-1", "billingStreet": "500 Industrial Way", "billingCity": "Chicago", + "billingState": "IL", "billingZip": "60601", "billingCountry": "USA", + "shippingStreet": "500 Industrial Way", "shippingCity": "Chicago", + "shippingState": "IL", "shippingZip": "60601", "shippingCountry": "USA"}, + ] + contacts = [ + {"contactId": "contact-contoso", "accountId": "account-contoso", + "firstName": "Helen", "lastName": "Whitaker", "title": "VP of IT", + "department": "IT", "email": "helen.whitaker@contoso.com", + "phone": "(212) 555-7700", "ownerId": "user-2"}, + ] + cases = [ + {"caseId": "case-contoso", "caseNumber": "00010234", + "subject": "SSO login failures", "status": "New", "priority": "High", + "origin": "Phone", "type": "Problem", "accountId": "account-contoso", + "contactId": "contact-contoso", "ownerId": "user-2", "closedDate": None, + "description": "Customer reports users cannot log in via SSO.", + "createdDate": "2026-06-24T14:10:00.000Z", "modifiedDate": "2026-06-24T14:10:00.000Z"}, + {"caseId": "case-globex", "caseNumber": "00010199", + "subject": "Invoice discrepancy on Q2 statement", "status": "Working", + "priority": "Medium", "origin": "Email", "type": "Question", + "accountId": "account-globex", "contactId": None, "ownerId": "user-1", + "closedDate": None, "description": "Billing question about Q2 invoice totals.", + "createdDate": "2026-06-20T09:00:00.000Z", "modifiedDate": "2026-06-21T09:00:00.000Z"}, + ] + return { + "user": dict(users[0]), + "users": users, + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": [], + "cases": cases, + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# ========================================================================== +# NOTION initial state +# ========================================================================== +def build_notion(): + return { + "user": {"id": "user-1", "name": "John Smith", "email": "john.smith@acme.com", "avatar": ""}, + "workspace": {"id": "ws-1", "name": "Acme Corp", "icon": "", "members": ["user-1"]}, + "pages": { + "page-incidents": { + "id": "page-incidents", "title": "Incidents", "icon": "🚨", "cover": None, + "parentId": None, "blockIds": ["blk-inc-intro"], "favorite": True, + "createdDate": "2025-09-01T09:00:00.000Z", + "lastEditedDate": "2026-06-10T12:00:00.000Z", "properties": {}}, + "page-inc-may": { + "id": "page-inc-may", "title": "P2: May Auth Latency Degradation", + "icon": "📄", "cover": None, "parentId": "page-incidents", + "blockIds": ["blk-may-1"], "favorite": False, + "createdDate": "2026-05-12T10:00:00.000Z", + "lastEditedDate": "2026-05-12T18:00:00.000Z", "properties": {}}, + "page-inc-apr": { + "id": "page-inc-apr", "title": "P3: April Billing Sync Delay", + "icon": "📄", "cover": None, "parentId": "page-incidents", + "blockIds": ["blk-apr-1"], "favorite": False, + "createdDate": "2026-04-03T14:00:00.000Z", + "lastEditedDate": "2026-04-04T09:00:00.000Z", "properties": {}}, + }, + "blocks": { + "blk-inc-intro": {"id": "blk-inc-intro", "type": "text", + "content": "Postmortems and live incident records for Acme Corp. Each incident gets its own child page.", + "properties": {}, "createdDate": "2025-09-01T09:00:00.000Z", + "lastEditedDate": "2025-09-01T09:00:00.000Z"}, + "blk-may-1": {"id": "blk-may-1", "type": "text", + "content": "Elevated auth latency for ~40 min after a config change. Resolved by rollback.", + "properties": {}, "createdDate": "2026-05-12T10:00:00.000Z", + "lastEditedDate": "2026-05-12T10:00:00.000Z"}, + "blk-apr-1": {"id": "blk-apr-1", "type": "text", + "content": "Billing sync delayed by 2 hours due to a stuck queue worker.", + "properties": {}, "createdDate": "2026-04-03T14:00:00.000Z", + "lastEditedDate": "2026-04-03T14:00:00.000Z"}, + }, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"}, + "notifications": [], + "pageOrder": ["page-incidents"], + } + + +BUILDERS = { + 'slack': build_slack, + 'jira': build_jira, + 'salesforce': build_salesforce, + 'notion': build_notion, +} + +# --- Inject state into all mocks --- +for name, url in MOCKS.items(): + state = BUILDERS[name]() + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, proxies=PROXIES) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None after injection' + print(f'State injected: {name} sid={sid}') + +print(f'All mocks injected. sid={sid}') + + +# --- Launch browser (primary = slack) --- +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 +chrome_proxy = f'--proxy-server={PROXY}' if PROXY else '' +_primary_mock_url = PRIMARY_URL +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +_open_remaining_mock_tabs(_primary_mock_url) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') diff --git a/csops_p1_incident_002/reward.py b/csops_p1_incident_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..52363d54be105e9abdd86e1ea44cfc6750b94b62 --- /dev/null +++ b/csops_p1_incident_002/reward.py @@ -0,0 +1,511 @@ +# --- 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: Stand up a full P1 incident record across Slack, Jira, Salesforce, Notion +Task ID: csops_p1_incident_002 +Domain: mock_websites (multi-mock: slack, jira, salesforce, notion) +Scoring (only task-introduced changes are scored): + Jira 0.30 — new Bug in SUP / Highest (0.12) + assigned to Raj Patel u_eng (0.08) + + summary+desc identify Contoso customer-declared SSO outage & impact (0.10) + Salesforce 0.25 — case-contoso -> status Escalated (0.13) + priority Critical (0.12) + Notion 0.25 — new child page of page-incidents titled for Contoso (0.09) + + Impact (0.04) + Timeline 3 times (0.04) + Owner (0.04) + Next update time (0.04) + Slack 0.20 — new reply in the customer-declared P1 thread (0.08) + cites Jira key (0.06) + + cites incident record (0.06) +All checks FAIL on initial_env (no changes) and PASS on golden_env. +""" +import os +import re +import sys + +import requests + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid empty') +except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +MOCKS = { + 'slack': 'http://28.7.184.198:8178', + 'jira': 'http://28.7.184.198:8153', + 'salesforce': 'http://28.7.184.198:8175', + 'notion': 'http://28.7.184.198:8166', +} + +# --- Egress proxy helper (§2.5) --- +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"{MOCKS['slack']}/go?sid=conn-probe") +PROXIES = None + +# --- Fetch state from all mocks --- +states = {} +for name, url in MOCKS.items(): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=20, proxies=PROXIES).json() + states[name] = data + except Exception as e: + print(f'CRITICAL: cannot fetch {name}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def parts(name): + d = states.get(name, {}) + return d.get('initial_state') or {}, d.get('current_state') or {} + + +def text_value(value): + if value is None: + return '' + return str(value) + + +def norm_text(value): + text = text_value(value).replace(':', ':') + return re.sub(r'\s+', ' ', text).strip().lower() + + +def canon_option(value): + return re.sub(r'[^a-z0-9]+', ' ', norm_text(value)).strip() + + +def option_in(value, allowed): + current = canon_option(value) + return current in {canon_option(v) for v in allowed} + + +def has_any(text, needles): + low = norm_text(text) + canon = canon_option(text) + return any(norm_text(needle) in low or canon_option(needle) in canon + for needle in needles) + + +def field_blob(record, keys): + return ' '.join(text_value(record.get(k)) for k in keys) + + +def to_24h(hour, minute, meridiem=''): + hour = int(hour) + minute = int(minute or 0) + meridiem = (meridiem or '').replace('.', '').lower() + if meridiem == 'pm' and hour < 12: + hour += 12 + elif meridiem == 'am' and hour == 12: + hour = 0 + if 0 <= hour <= 23 and 0 <= minute <= 59: + return hour, minute + return None + + +def extract_times(value): + text = norm_text(value) + found = set() + for h, m, mer in re.findall(r'\b(\d{1,2})\s*[:.h]\s*(\d{2})\s*(a\.?m\.?|p\.?m\.?|am|pm)?\b', text): + parsed = to_24h(h, m, mer) + if parsed: + found.add(parsed) + for h, m in re.findall(r'\b([01]\d|2[0-3])([0-5]\d)\s*(?:utc|gmt|z)\b', text): + parsed = to_24h(h, m) + if parsed: + found.add(parsed) + for h, mer in re.findall(r'\b(\d{1,2})\s*(a\.?m\.?|p\.?m\.?|am|pm)\b', text): + parsed = to_24h(h, 0, mer) + if parsed: + found.add(parsed) + return found + + +def has_time(value, hour, minute): + return (hour, minute) in extract_times(value) + + +def has_user_count(value): + text = norm_text(value) + return bool(re.search(r'\b(?:about|around|approx(?:imately)?|roughly|~)?\s*' + r'(?:4\s*,?\s*000|4000|4\s*k|four thousand)\+?\b', + text)) + + +def has_contoso(value): + return 'contoso' in norm_text(value) + + +def has_sso_login(value): + return has_any(value, [ + 'sso', 'single sign on', 'single sign-on', 'login', 'log in', + 'sign in', 'signin', 'authentication', 'auth', 'saml' + ]) + + +def has_p1_critical(value): + text = norm_text(value) + return bool(re.search(r'\b(?:p\s*1|sev\s*1|severity\s*1)\b', text)) or has_any(text, [ + 'critical', 'highest', 'top urgency', 'urgent', 'major incident', + 'customer declared', 'customer-declared', 'escalat' + ]) + + +def has_outage_impact(value): + return has_user_count(value) or has_time(value, 14, 5) or has_any(value, [ + 'locked out', 'lockout', 'cannot access', 'can not access', + 'unable to access', 'down', 'outage', 'unavailable', 'blocked', + 'banking operations', 'executive banking' + ]) + + +def has_next_update_label(value): + return has_any(value, [ + 'next update', 'next status', 'next comms', 'next communication', + 'next checkpoint', 'follow up', 'follow-up', 'update again', + 'update by', 'status update', 'next touchpoint', '下一次更新', + '下次更新', '更新时间' + ]) + + +def has_relative_eta(value): + text = norm_text(value) + number_word = (r'\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|' + r'eleven|twelve|couple|few|half') + if re.search(r'\b(?:within|in|after|every)\s+(?:' + number_word + r')\s*' + r'(?:m|min|mins|minutes|h|hr|hrs|hours|days?)\b', text): + return True + return has_any(text, [ + 'later today', 'today', 'tomorrow', 'tonight', 'eod', 'eob', 'cob', + 'end of day', 'close of business', 'next business day', + 'this morning', 'this afternoon', 'this evening' + ]) + + +TIMELINE_TIMES = ((14, 5), (14, 20), (14, 35)) + + +def verify_task(): + total = 0.0 + + # ===================== JIRA (0.30) ===================== + # The new issue is the only task-introduced change. Identify by id-not-in-initial, + # scoped to the Support Engineering (SUP) project. + new_issue = None + try: + ji, jc = parts('jira') + init_ids = {i.get('id') for i in ji.get('issues', [])} + sup_proj_ids = {p.get('id') for p in jc.get('projects', []) if p.get('key') == 'SUP'} + new_issues = [i for i in jc.get('issues', []) + if i.get('id') not in init_ids and i.get('projectId') in sup_proj_ids] + # Prefer the new issue that carries the strongest incident signals. + if new_issues: + def issue_score(cand): + blob = field_blob(cand, ('summary', 'description')) + return sum([ + has_contoso(blob), + has_sso_login(blob), + has_p1_critical(blob), + has_outage_impact(blob), + option_in(cand.get('type'), ('Bug', 'Defect')), + option_in(cand.get('priority'), ('Highest', 'Critical', 'P1')), + ]) + new_issue = max(new_issues, key=issue_score) + except Exception as e: + print(f'ERROR: Jira issue lookup — {e}') + + # Jira component 1: new Bug issue in SUP with priority Highest (0.12) + try: + if (new_issue and option_in(new_issue.get('type'), ('Bug', 'Defect')) + and option_in(new_issue.get('priority'), ('Highest', 'Critical', 'P1', 'Top Urgency'))): + print(f"PASS: Jira new Bug in SUP, priority Highest (key={new_issue.get('key')}) (0.12)") + total += 0.12 + else: + print(f"FAIL: Jira new Bug/Highest — issue={new_issue and (new_issue.get('type'), new_issue.get('priority'))}") + except Exception as e: + print(f'ERROR: Jira C1 — {e}') + + # Jira component 2: assigned to platform engineer Raj Patel (u_eng) (0.08) + try: + if new_issue and new_issue.get('assigneeId') == 'u_eng': + print('PASS: Jira issue assigned to Raj Patel (u_eng) (0.08)') + total += 0.08 + else: + print(f"FAIL: Jira assignee — found {new_issue and new_issue.get('assigneeId')}") + except Exception as e: + print(f'ERROR: Jira C2 — {e}') + + # Jira component 3: summary+description identify Contoso customer-declared SSO outage & impact (0.10) + try: + if new_issue: + blob = field_blob(new_issue, ('summary', 'description')) + has_customer = has_contoso(blob) + has_sso = has_sso_login(blob) + has_impact = has_outage_impact(blob) + has_severity = has_p1_critical(blob) + if has_customer and has_sso and has_impact and has_severity: + print('PASS: Jira summary/description identify Contoso customer-declared SSO outage + impact (0.10)') + total += 0.10 + else: + print(f'FAIL: Jira content — customer={has_customer} sso={has_sso} ' + f'impact={has_impact} severity={has_severity}') + else: + print('FAIL: Jira content — no new issue') + except Exception as e: + print(f'ERROR: Jira C3 — {e}') + + # ===================== SALESFORCE (0.25) ===================== + # Only the contoso case status/priority change is task-introduced. + contoso_case = None + try: + _, sc = parts('salesforce') + for c in sc.get('cases', []): + if c.get('caseId') == 'case-contoso': + contoso_case = c + break + except Exception as e: + print(f'ERROR: SF case lookup — {e}') + + # SF component 1: case-contoso status == Escalated, still Contoso account & owner user-2 (0.13) + try: + if (contoso_case and option_in(contoso_case.get('status'), ('Escalated',)) + and contoso_case.get('accountId') == 'account-contoso' + and contoso_case.get('ownerId') == 'user-2'): + print('PASS: SF case-contoso status Escalated (owner/account intact) (0.13)') + total += 0.13 + else: + print(f"FAIL: SF status — status={contoso_case and contoso_case.get('status')} " + f"owner={contoso_case and contoso_case.get('ownerId')}") + except Exception as e: + print(f'ERROR: SF C1 — {e}') + + # SF component 2: case-contoso priority == Critical (0.12) + try: + if contoso_case and option_in(contoso_case.get('priority'), ('Critical',)): + print('PASS: SF case-contoso priority Critical (0.12)') + total += 0.12 + else: + print(f"FAIL: SF priority — found {contoso_case and contoso_case.get('priority')}") + except Exception as e: + print(f'ERROR: SF C2 — {e}') + + # ===================== NOTION (0.25) ===================== + new_page = None + page_text = '' + try: + ni, nc = parts('notion') + init_page_ids = set((ni.get('pages') or {}).keys()) + cur_pages = nc.get('pages') or {} + cur_blocks = nc.get('blocks') or {} + # new child page of page-incidents + page_candidates = [] + for pid, pg in cur_pages.items(): + if pid not in init_page_ids and pg.get('parentId') == 'page-incidents': + chunks = [pg.get('title', '')] + for bid in pg.get('blockIds', []): + b = cur_blocks.get(bid) or {} + chunks.append(text_value(b.get('content', ''))) + candidate_text = ' '.join(chunks) + score = sum([ + has_contoso(candidate_text), + has_sso_login(candidate_text), + has_p1_critical(candidate_text), + has_user_count(candidate_text), + has_time(candidate_text, 14, 5), + ]) + page_candidates.append((score, pg, norm_text(candidate_text))) + if page_candidates: + _, new_page, page_text = max(page_candidates, key=lambda x: x[0]) + except Exception as e: + print(f'ERROR: Notion page lookup — {e}') + + # Notion component 1: new child page titled for the Contoso SSO outage (0.09) + try: + if new_page: + title = new_page.get('title') or '' + if has_contoso(title) and (has_sso_login(title) or has_any(title, ['outage', 'incident', 'p1', 'critical'])): + print(f"PASS: Notion new child page titled for incident ({new_page.get('title')!r}) (0.09)") + total += 0.09 + else: + print(f'FAIL: Notion title — {new_page.get("title")!r}') + else: + print('FAIL: Notion — no new child page under page-incidents') + except Exception as e: + print(f'ERROR: Notion C1 — {e}') + + # Notion component 2: Impact area (~4,000 users, SSO, since 14:05, customer severity) (0.04) + try: + if new_page: + has_users = has_user_count(page_text) + has_sso = has_sso_login(page_text) + has_onset = has_time(page_text, 14, 5) + has_severity = has_p1_critical(page_text) or has_any(page_text, ['blocked']) + if has_users and has_sso and has_onset and has_severity: + print('PASS: Notion Impact area covered (0.04)') + total += 0.04 + else: + print(f'FAIL: Notion Impact — users={has_users} sso={has_sso} ' + f'onset={has_onset} severity={has_severity}') + else: + print('FAIL: Notion Impact — no page') + except Exception as e: + print(f'ERROR: Notion C2 — {e}') + + # Notion component 3: Timeline area (14:05, 14:20, 14:35) (0.04) + try: + missing_times = [f'{h:02d}:{m:02d}' for h, m in TIMELINE_TIMES + if not has_time(page_text, h, m)] + if new_page and not missing_times: + print('PASS: Notion Timeline covers 14:05/14:20/14:35 (0.04)') + total += 0.04 + else: + print(f'FAIL: Notion Timeline — missing {missing_times or "page"}') + except Exception as e: + print(f'ERROR: Notion C3 — {e}') + + # Notion component 4: Current Owner area (incident owner / Raj Patel as eng lead) (0.04) + try: + has_owner_label = has_any(page_text, ['owner', 'lead', 'commander', '负责人']) + has_owner_name = has_any(page_text, ['raj', 'raj patel', 'priya', 'john smith', 'sarah']) + if new_page and has_owner_label and has_owner_name: + print('PASS: Notion Current Owner area covered (0.04)') + total += 0.04 + else: + print('FAIL: Notion Owner — missing owner/lead reference') + except Exception as e: + print(f'ERROR: Notion C4 — {e}') + + # Notion component 5: Next Update Time with a specific clock time (0.04) + try: + if new_page and has_next_update_label(page_text): + # Accept a distinct clock time or a relative ETA such as "in 30 minutes". + future_times = extract_times(page_text) - set(TIMELINE_TIMES) + if future_times or has_relative_eta(page_text): + pretty_times = [f'{h:02d}:{m:02d}' for h, m in sorted(future_times)] + print(f'PASS: Notion Next Update Time present ({pretty_times or "relative ETA"}) (0.04)') + total += 0.04 + else: + print(f'FAIL: Notion Next Update — no distinct clock time, found {sorted(extract_times(page_text))}') + else: + print('FAIL: Notion Next Update — no next-update label') + except Exception as e: + print(f'ERROR: Notion C5 — {e}') + + # ===================== SLACK (0.20) ===================== + new_reply = None + try: + si, sc = parts('slack') + init_msgs = (si.get('messages') or {}).get('incidents', []) + cur_msgs = (sc.get('messages') or {}).get('incidents', []) + init_ids = {m.get('messageId') for m in init_msgs} + new_msgs = [m for m in cur_msgs if m.get('messageId') not in init_ids] + source_thread_ids = set() + for m in init_msgs: + blob = m.get('content') or '' + has_source_customer = has_contoso(blob) + has_source_p1 = has_p1_critical(blob) + has_source_issue = has_sso_login(blob) + has_source_impact = has_outage_impact(blob) + if has_source_customer and has_source_p1 and has_source_issue and has_source_impact: + if m.get('threadId'): + source_thread_ids.add(m.get('threadId')) + thread_replies = [] + for thread_id in source_thread_ids: + try: + thread_replies.extend((sc.get('threads') or {}).get(thread_id, {}).get('replies', [])) + except Exception: + pass + for m in new_msgs: + if m.get('threadId') in source_thread_ids or m.get('messageId') in thread_replies: + new_reply = m + break + except Exception as e: + print(f'ERROR: Slack lookup — {e}') + + # Slack component 1: new reply posted in the customer-declared P1 thread (0.08) + try: + if new_reply: + print(f"PASS: Slack new reply in customer-declared P1 thread ({new_reply.get('messageId')}) (0.08)") + total += 0.08 + else: + print('FAIL: Slack — no new reply in the customer-declared P1 thread') + except Exception as e: + print(f'ERROR: Slack C1 — {e}') + + reply_text = (new_reply.get('content', '') if new_reply else '') + reply_low = norm_text(reply_text).replace('–', '-').replace('—', '-') + reply_canon = canon_option(reply_text) + + # Slack component 2: reply cites the Jira issue key (0.06) + try: + # accept the actual key of the new jira issue, or a generic SUP- reference + jira_key = (new_issue.get('key') if new_issue else None) or '' + jira_key_canon = canon_option(jira_key) + cites_jira = bool(re.search(r'\bsup\s*[-#]?\s*\d+\b', reply_low)) \ + or bool(re.search(r'\bsup\s+\d+\b', reply_canon)) \ + or (jira_key and norm_text(jira_key) in reply_low) \ + or (jira_key_canon and jira_key_canon in reply_canon) + if new_reply and cites_jira: + print('PASS: Slack reply cites Jira issue key (0.06)') + total += 0.06 + else: + print(f'FAIL: Slack Jira key — reply={reply_text[:80]!r}') + except Exception as e: + print(f'ERROR: Slack C2 — {e}') + + # Slack component 3: reply references the incident record (Notion page title / record) (0.06) + try: + title_low = norm_text(new_page.get('title', '') if new_page else '') + cites_record = has_any(reply_text, [ + 'notion', 'incident summary', 'incident record', 'incident page', + 'incident doc', 'summary page', 'single source of truth', + 'source of truth', 'record' + ]) or (has_contoso(reply_text) and (has_any(reply_text, ['outage', 'incident']) or has_sso_login(reply_text))) \ + or (title_low and title_low in reply_low) + if new_reply and cites_record: + print('PASS: Slack reply references the incident record (0.06)') + total += 0.06 + else: + print(f'FAIL: Slack record ref — reply={reply_text[:80]!r}') + except Exception as e: + print(f'ERROR: Slack C3 — {e}') + + final = round(min(total, 1.0), 4) + print(f'\nScore: {round(total,4)}/1.0') + print(f'REWARD: {final}') + return final + + +verify_task() diff --git a/csops_p1_incident_002/reward_label.json b/csops_p1_incident_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4d7d8cae3a557322660cebb202b0aacdb6e1e9 --- /dev/null +++ b/csops_p1_incident_002/reward_label.json @@ -0,0 +1,127 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csops_p1_incident_pipeline_003/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-03 20:24:55", + "label": { + "task_id": "csops_p1_incident_002", + "domain": "mock_websites", + "summary": "验证在 Slack、Jira、Salesforce、Notion 四个 mock 服务中建立完整的 Contoso SSO P1 事件记录", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "slack_mock (http://28.7.186.212:8198)", + "jira_mock (http://28.7.186.212:8173)", + "salesforce_mock (http://28.7.186.212:8195)", + "notion_mock (http://28.7.186.212:8186)" + ], + "scoring_components": [ + { + "name": "Jira Component 1", + "weight": 0.12, + "description": "在 SUP 项目中新建 Bug 类型 issue,且优先级为 Highest", + "check_logic": "检查 new_issue 存在,且 option_in(type, ('Bug', 'Defect')) 为真,且 option_in(priority, ('Highest', 'Critical', 'P1', 'Top Urgency')) 为真", + "pass_condition": "SUP 项目下存在新 issue,类型为 Bug/Defect,优先级为 Highest/Critical/P1/Top Urgency" + }, + { + "name": "Jira Component 2", + "weight": 0.08, + "description": "新 issue 分配给 Raj Patel (u_eng)", + "check_logic": "检查 new_issue.get('assigneeId') == 'u_eng'", + "pass_condition": "新 issue 的 assigneeId 字段等于 'u_eng'" + }, + { + "name": "Jira Component 3", + "weight": 0.1, + "description": "summary 和 description 中识别出 Contoso 客户声明的 SSO outage 及影响", + "check_logic": "合并 summary 和 description 文本,检查 has_contoso、has_sso_login、has_outage_impact、has_p1_critical 均为真", + "pass_condition": "文本中同时包含 Contoso、SSO/登录相关关键词、outage/影响描述、P1/severity 关键词" + }, + { + "name": "Salesforce Component 1", + "weight": 0.13, + "description": "case-contoso 状态升级为 Escalated,且账户和负责人保持不变", + "check_logic": "检查 case-contoso 存在,option_in(status, ('Escalated',)) 为真,accountId == 'account-contoso',ownerId == 'user-2'", + "pass_condition": "case-contoso 状态为 Escalated,accountId 为 account-contoso,ownerId 为 user-2" + }, + { + "name": "Salesforce Component 2", + "weight": 0.12, + "description": "case-contoso 优先级设为 Critical", + "check_logic": "检查 contoso_case 存在且 option_in(priority, ('Critical',)) 为真", + "pass_condition": "case-contoso 的 priority 为 Critical" + }, + { + "name": "Notion Component 1", + "weight": 0.09, + "description": "在 page-incidents 下新建标题包含 Contoso SSO outage 的子页面", + "check_logic": "检查 new_page 存在,标题中 has_contoso 为真,且 has_sso_login 或包含 outage/incident/p1/critical 关键词", + "pass_condition": "page-incidents 下存在新子页面,标题包含 Contoso 且包含 SSO/登录/outage/incident/P1/critical 相关词" + }, + { + "name": "Notion Component 2", + "weight": 0.04, + "description": "页面内容包含 Impact 区域(约4000用户、SSO、14:05开始、严重程度)", + "check_logic": "检查 page_text 中 has_user_count、has_sso_login、has_time(14,5)、has_p1_critical 或 blocked 均为真", + "pass_condition": "页面文本同时包含约4000用户、SSO/登录、14:05时间、P1/severity/blocked 信息" + }, + { + "name": "Notion Component 3", + "weight": 0.04, + "description": "页面内容包含 Timeline 区域,记录 14:05、14:20、14:35 三个时间点", + "check_logic": "检查 TIMELINE_TIMES = ((14,5),(14,20),(14,35)) 三个时间是否都存在于 page_text 中", + "pass_condition": "页面文本中同时包含 14:05、14:20、14:35 三个时间" + }, + { + "name": "Notion Component 4", + "weight": 0.04, + "description": "页面内容包含 Current Owner 区域(提及负责人/lead 及具体人名)", + "check_logic": "检查 page_text 中 has_any(['owner', 'lead', 'commander', '负责人']) 和 has_any(['raj', 'raj patel', 'priya', 'john smith', 'sarah']) 均为真", + "pass_condition": "页面文本同时包含 owner/lead/commander/负责人 标签和 Raj/Priya/John Smith/Sarah 等人名" + }, + { + "name": "Notion Component 5", + "weight": 0.04, + "description": "页面内容包含 Next Update Time,且包含具体时钟时间或相对时间", + "check_logic": "检查 has_next_update_label(page_text) 为真,且 extract_times 中存在不同于 TIMELINE_TIMES 的未来时间,或 has_relative_eta 为真", + "pass_condition": "页面文本包含 next update 相关标签,并包含一个非 14:05/14:20/14:35 的时钟时间或相对 ETA(如 in 30 minutes、later today 等)" + }, + { + "name": "Slack Component 1", + "weight": 0.08, + "description": "在客户声明的 P1 线程中发布新回复", + "check_logic": "通过比对 initial_state 和 current_state 的 messageId,找出 incidents 频道中属于客户声明 P1 线程(包含 Contoso、P1、SSO、impact)的新回复", + "pass_condition": "存在新消息回复在客户声明的 P1 线程中" + }, + { + "name": "Slack Component 2", + "weight": 0.06, + "description": "Slack 回复中引用 Jira issue key", + "check_logic": "检查回复文本是否匹配正则 \\bsup\\s*[-#]?\\s*\\d+\\b 或包含 new_issue 的实际 key", + "pass_condition": "回复内容包含 SUP-数字 格式的 Jira key 或实际 issue key" + }, + { + "name": "Slack Component 3", + "weight": 0.06, + "description": "Slack 回复中引用 incident record(Notion 页面标题或记录关键词)", + "check_logic": "检查回复文本是否包含 notion/incident summary/record 等关键词,或包含 Contoso 和 outage/incident/SSO,或包含 Notion 页面标题", + "pass_condition": "回复内容包含 incident record 相关关键词、或 Contoso+outage/SSO 组合、或 Notion 页面标题" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空 → 打印 CRITICAL 并返回 0.0 退出", + "从任一 mock 服务(slack/jira/salesforce/notion)拉取状态失败 → 打印 CRITICAL 并返回 0.0 退出", + "Jira 中未找到 SUP 项目下符合 incident 信号的新 issue → Jira 组件全部失败", + "Salesforce 中未找到 case-contoso → Salesforce 组件全部失败", + "Notion 中未找到 page-incidents 下的新子页面 → Notion 组件全部失败", + "Slack 中未找到客户声明 P1 线程的新回复 → Slack 组件全部失败", + "各组件内部异常被捕获后打印 ERROR,该组件不得分,但脚本继续执行后续组件" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,然后向四个 mock 服务(slack、jira、salesforce、notion)分别拉取 initial_state 和 current_state。接着按顺序验证四个领域:1) Jira:识别 SUP 项目中不在初始状态的新 issue,按类型/优先级(0.12)、负责人(0.08)、内容完整性(0.10)评分;2) Salesforce:定位 case-contoso,按状态升级为 Escalated 且账户/负责人不变(0.13)、优先级为 Critical(0.12)评分;3) Notion:查找 page-incidents 下的新子页面,按标题(0.09)、Impact 区域(0.04)、Timeline 三个时间点(0.04)、Owner 区域(0.04)、Next Update Time(0.04)评分;4) Slack:在客户声明的 P1 线程中找新回复,按存在回复(0.08)、引用 Jira key(0.06)、引用 incident record(0.06)评分。各组件通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。任何关键步骤(读 sid、拉 mock 状态)失败会立即退出并返回 0.0。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码并提取关键信息:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: csops_p1_incident_pipeline_003`\n2. **Domain**: `Domain: mock_websites (multi-mock: slack, jira, salesforce, notion)`\n3. **Summary**: 脚本验证在多个 mock 服务(Slack、Jira、Salesforce、Notion)中建立完整的 P1 事件记录的任务行为。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `http://28.7.186.212:8178` (slack mock)\n - `http://28.7.186.212:8153` (jira mock)\n - `http://28.7.186.212:8175` (salesforce mock)\n - `http://28.7.186.212:8166` (notion mock)\n\n6. **Scoring components**:\n - Jira (0.30 total):\n - Component 1: 0.12 - new Bug in SUP with priority Highest\n - Component 2: 0.08 - assigned to Raj Patel (u_eng)\n - Component 3: 0.10 - summary+description identify Contoso customer-declared SSO outage & impact\n - Salesforce (0.25 total):\n - Component 1: 0.13 - case-contoso status Escalated, account/owner intact\n - Component 2: 0.12 - case-contoso priority Critical\n - Notion (0.25 total):\n - Component 1: 0.09 - new child page of page-incidents titled for Contoso SSO outage\n - Component 2: 0.04 - Impact area (~4,000 users, SSO, since 14:05, customer severity)\n - Component 3: 0.04 - Timeline area (14:05, 14:20, 14:35)\n - Component 4: 0.04 - Current Owner area (incident owner / Raj Patel as eng lead)\n - Component 5: 0.04 - Next Update Time with specific clock time or relative ETA\n - Slack (0.20 total):\n - Component 1: 0.08 - new reply in customer-declared P1 thread\n - Component 2: 0.06 - reply cites Jira issue key\n - Component 3: 0.06 - reply references incident record\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后通过 `min(total, 1.0)` 钳制到上限 1.0,并四舍五入到 4 位小数。\n9. **failure_modes**:\n - 读取 sid 失败(/tmp/task_web_sid 不存在或为空)→ CRITICAL, REWARD: 0.0, sys.exit(0)\n - 从任一 mock 服务获取状态失败 → CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败会打印 FAIL 但不退出,只是不加分\n - 任何组件内部的异常会被捕获,打印 ERROR,但不影响其他组件评分\n\n10. **scoring_logic_explanation**: 需要详细说明执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID\n - 配置代理并测试连接\n - 从四个 mock 服务(slack, jira, salesforce, notion)获取 initial_state 和 current_state\n - 分别验证四个领域的任务行为:\n - Jira: 找出 SUP 项目中不在初始状态的新 issue,检查类型、优先级、负责人、内容\n - Salesforce: 查找 case-contoso,检查状态和优先级\n - Notion: 查找 page-incidents 下的新子页面,检查标题、Impact、Timeline、Owner、Next Update\n - Slack: 在客户声明的 P1 线程中查找新回复,检查是否引用 Jira key 和 incident record\n - 各组件分数累加,最终钳制在 1.0 并输出\n\n11. **confidence**: 1.0(代码逻辑清晰完整)\n\n让我确保每个字段都准确对应代码:\n\n- Jira component 1: `option_in(new_issue.get('type'), ('Bug', 'Defect'))` and `option_in(new_issue.get('priority'), ('Highest', 'Critical', 'P1', 'Top Urgency'))` → 0.12\n- Jira component 2: `new_issue.get('assigneeId') == 'u_eng'` → 0.08\n- Jira component 3: `has_contoso(blob) and has_sso_login(blob) and has_outage_impact(blob) and has_p1_critical(blob)` → 0.10\n\n- SF component 1: `option_in(contoso_case.get('status'), ('Escalated',))` and `accountId == 'account-contoso'` and `ownerId == 'user-2'` → 0.13\n- SF component 2: `option_in(contoso_case.get('priority'), ('Critical',))` → 0.12\n\n- Notion component 1: `has_contoso(title) and (has_sso_login(title) or has_any(title, ['outage', 'incident', 'p1', 'critical']))` → 0.09\n- Notion component 2: `has_user_count(page_text) and has_sso_login(page_text) and has_time(page_text, 14, 5) and (has_p1_critical(page_text) or has_any(page_text, ['blocked']))` → 0.04\n- Notion component 3: `not missing_times` for TIMELINE_TIMES = ((14, 5), (14, 20), (14, 35)) → 0.04\n- Notion component 4: `has_owner_label and has_owner_name` → 0.04\n- Notion component 5: `has_next_update_label(page_text)` and (`future_times` or `has_relative_eta(page_text)`) → 0.04\n\n- Slack component 1: `new_reply` exists in customer-declared P1 thread → 0.08\n- Slack component 2: cites Jira key via regex or key match → 0.06\n- Slack component 3: references incident record via keywords or title match → 0.06\n\nScore aggregation: `total` starts at 0.0, each component adds its weight if passed. Final: `round(min(total, 1.0), 4)`.\n\nFailure modes:\n- Cannot read sid\n- Cannot fetch any mock state\n- Jira issue lookup fails (exception caught, no score)\n- No new issue found (components fail)\n- No contoso case found (components fail)\n- No new Notion page found (components fail)\n- No new Slack reply found (components fail)\n\n我需要确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"csops_p1_incident_pipeline_003\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Slack、Jira、Salesforce、Notion 四个 mock 服务中建立完整的 Contoso SSO P1 事件记录\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"slack_mock (http://28.7.186.212:8198)\", \"jira_mock (http://28.7.186.212:8173)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"notion_mock (http://28.7.186.212:8186)\"],\n \"scoring_components\": [\n {\n \"name\": \"Jira Component 1\",\n \"weight\": 0.12,\n \"description\": \"在 SUP 项目中新建 Bug 类型 issue,且优先级为 Highest\",\n \"check_logic\": \"检查 new_issue 存在,且 option_in(type, ('Bug', 'Defect')) 为真,且 option_in(priority, ('Highest', 'Critical', 'P1', 'Top Urgency')) 为真\",\n \"pass_condition\": \"SUP 项目下存在新 issue,类型为 Bug/Defect,优先级为 Highest/Critical/P1/Top Urgency\"\n },\n {\n \"name\": \"Jira Component 2\",\n \"weight\": 0.08,\n \"description\": \"新 issue 分配给 Raj Patel (u_eng)\",\n \"check_logic\": \"检查 new_issue.get('assigneeId') == 'u_eng'\",\n \"pass_condition\": \"新 issue 的 assigneeId 字段等于 'u_eng'\"\n },\n {\n \"name\": \"Jira Component 3\",\n \"weight\": 0.10,\n \"description\": \"summary 和 description 中识别出 Contoso 客户声明的 SSO outage 及影响\",\n \"check_logic\": \"合并 summary 和 description 文本,检查 has_contoso、has_sso_login、has_outage_impact、has_p1_critical 均为真\",\n \"pass_condition\": \"文本中同时包含 Contoso、SSO/登录相关关键词、outage/影响描述、P1/severity 关键词\"\n },\n {\n \"name\": \"Salesforce Component 1\",\n \"weight\": 0.13,\n \"description\": \"case-contoso 状态升级为 Escalated,且账户和负责人保持不变\",\n \"check_logic\": \"检查 case-contoso 存在,option_in(status, ('Escalated',)) 为真,accountId == 'account-contoso',ownerId == 'user-2'\",\n \"pass_condition\": \"case-contoso 状态为 Escalated,accountId 为 account-contoso,ownerId 为 user-2\"\n },\n {\n \"name\": \"Salesforce Component 2\",\n \"weight\": 0.12,\n \"description\": \"case-contoso 优先级设为 Critical\",\n \"check_logic\": \"检查 contoso_case 存在且 option_in(priority, ('Critical',)) 为真\",\n \"pass_condition\": \"case-contoso 的 priority 为 Critical\"\n },\n {\n \"name\": \"Notion Component 1\",\n \"weight\": 0.09,\n \"description\": \"在 page-incidents 下新建标题包含 Contoso SSO outage 的子页面\",\n \"check_logic\": \"检查 new_page 存在,标题中 has_contoso 为真,且 has_sso_login 或包含 outage/incident/p1/critical 关键词\",\n \"pass_condition\": \"page-incidents 下存在新子页面,标题包含 Contoso 且包含 SSO/登录/outage/incident/P1/critical 相关词\"\n },\n {\n \"name\": \"Notion Component 2\",\n \"weight\": 0.04,\n \"description\": \"页面内容包含 Impact 区域(约4000用户、SSO、14:05开始、严重程度)\",\n \"check_logic\": \"检查 page_text 中 has_user_count、has_sso_login、has_time(14,5)、has_p1_critical 或 blocked 均为真\",\n \"pass_condition\": \"页面文本同时包含约4000用户、SSO/登录、14:05时间、P1/severity/blocked 信息\"\n },\n {\n \"name\": \"Notion Component 3\",\n \"weight\": 0.04,\n \"description\": \"页面内容包含 Timeline 区域,记录 14:05、14:20、14:35 三个时间点\",\n \"check_logic\": \"检查 TIMELINE_TIMES = ((14,5),(14,20),(14,35)) 三个时间是否都存在于 page_text 中\",\n \"pass_condition\": \"页面文本中同时包含 14:05、14:20、14:35 三个时间\"\n },\n {\n \"name\": \"Notion Component 4\",\n \"weight\": 0.04,\n \"description\": \"页面内容包含 Current Owner 区域(提及负责人/lead 及具体人名)\",\n \"check_logic\": \"检查 page_text 中 has_any(['owner', 'lead', 'commander', '负责人']) 和 has_any(['raj', 'raj patel', 'priya', 'john smith', 'sarah']) 均为真\",\n \"pass_condition\": \"页面文本同时包含 owner/lead/commander/负责人 标签和 Raj/Priya/John Smith/Sarah 等人名\"\n },\n {\n \"name\": \"Notion Component 5\",\n \"weight\": 0.04,\n \"description\": \"页面内容包含 Next Update Time,且包含具体时钟时间或相对时间\",\n \"check_logic\": \"检查 has_next_update_label(page_text) 为真,且 extract_times 中存在不同于 TIMELINE_TIMES 的未来时间,或 has_relative_eta 为真\",\n \"pass_condition\": \"页面文本包含 next update 相关标签,并包含一个非 14:05/14:20/14:35 的时钟时间或相对 ETA(如 in 30 minutes、later today 等)\"\n },\n {\n \"name\": \"Slack Component 1\",\n \"weight\": 0.08,\n \"description\": \"在客户声明的 P1 线程中发布新回复\",\n \"check_logic\": \"通过比对 initial_state 和 current_state 的 messageId,找出 incidents 频道中属于客户声明 P1 线程(包含 Contoso、P1、SSO、impact)的新回复\",\n \"pass_condition\": \"存在新消息回复在客户声明的 P1 线程中\"\n },\n {\n \"name\": \"Slack Component 2\",\n \"weight\": 0.06,\n \"description\": \"Slack 回复中引用 Jira issue key\",\n \"check_logic\": \"检查回复文本是否匹配正则 \\\\bsup\\\\s*[-#]?\\\\s*\\\\d+\\\\b 或包含 new_issue 的实际 key\",\n \"pass_condition\": \"回复内容包含 SUP-数字 格式的 Jira key 或实际 issue key\"\n },\n {\n \"name\": \"Slack Component 3\",\n \"weight\": 0.06,\n \"description\": \"Slack 回复中引用 incident record(Notion 页面标题或记录关键词)\",\n \"check_logic\": \"检查回复文本是否包含 notion/incident summary/record 等关键词,或包含 Contoso 和 outage/incident/SSO,或包含 Notion 页面标题\",\n \"pass_condition\": \"回复内容包含 incident record 相关关键词、或 Contoso+outage/SSO 组合、或 Notion 页面标题\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空 → 打印 CRITICAL 并返回 0.0 退出\",\n \"从任一 mock 服务(slack/jira/salesforce/notion)拉取状态失败 → 打印 CRITICAL 并返回 0.0 退出\",\n \"Jira 中未找到 SUP 项目下符合 incident 信号的新 issue → Jira 组件全部失败\",\n \"Salesforce 中未找到 case-contoso → Salesforce 组件全部失败\",\n \"Notion 中未找到 page-incidents 下的新子页面 → Notion 组件全部失败\",\n \"Slack 中未找到客户声明 P1 线程的新回复 → Slack 组件全部失败\",\n \"各组件内部异常被捕获后打印 ERROR,该组件不得分,但脚本继续执行后续组件\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,然后向四个 mock 服务(slack、jira、salesforce、notion)分别拉取 initial_state 和 current_state。接着按顺序验证四个领域:1) Jira:识别 SUP 项目中不在初始状态的新 issue,按类型/优先级(0.12)、负责人(0.08)、内容完整性(0.10)评分;2) Salesforce:定位 case-contoso,按状态升级为 Escalated 且账户/负责人不变(0.13)、优先级为 Critical(0.12)评分;3) Notion:查找 page-incidents 下的新子页面,按标题(0.09)、Impact 区域(0.04)、Timeline 三个时间点(0.04)、Owner 区域(0.04)、Next Update Time(0.04)评分;4) Slack:在客户声明的 P1 线程中找新回复,按存在回复(0.08)、引用 Jira key(0.06)、引用 incident record(0.06)评分。各组件通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。任何关键步骤(读 sid、拉 mock 状态)失败会立即退出并返回 0.0。\",\n \"confidence\": 1.0\n}\n```\n\n我需要确保 JSON 是有效的,没有多余的逗号,字符串正确转义。让我再检查一下。\n\n在 `data_sources` 中,我使用了中文括号,应该没问题。\n在 `scoring_logic_explanation` 中,我使用了中文描述,符合要求。\n\n确认 `task_id` 和 `domain` 是从 docstring 中提取的:\n- Task ID: csops_p1_incident_pipeline_003\n- Domain: mock_websites\n\n确认 `is_placeholder` 是 false,因为脚本有完整的验证逻辑。\n\n确认 `total_max_score` 是 1.0。\n\n确认 `score_aggregation` 描述准确。\n\n确认 `failure_modes` 覆盖了所有关键失败路径。\n\n确认 `confidence` 是 1.0。\n\n现在输出纯 JSON,不要 markdown 代码块。 {\"task_id\":\"csops_p1_incident_pipeline_003\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Slack、Jira、Salesforce、Notion 四个 mock 服务中建立完整的 Contoso SSO P1 事件记录\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"slack_mock (http://28.7.186.212:8198)\",\"jira_mock (http://28.7.186.212:8173)\",\"salesforce_mock (http://28.7.186.212:8195)\",\"notion_mock (http://28.7.186.212:8186)\"],\"scoring_components\":[{\"name\":\"Jira Component 1\",\"weight\":0.12,\"description\":\"在 SUP 项目中新建 Bug 类型 issue,且优先级为 Highest\",\"check_logic\":\"检查 new_issue 存在,且 option_in(type, ('Bug', 'Defect')) 为真,且 option_in(priority, ('Highest', 'Critical', 'P1', 'Top Urgency')) 为真\",\"pass_condition\":\"SUP 项目下存在新 issue,类型为 Bug/Defect,优先级为 Highest/Critical/P1/Top Urgency\"},{\"name\":\"Jira Component 2\",\"weight\":0.08,\"description\":\"新 issue 分配给 Raj Patel (u_eng)\",\"check_logic\":\"检查 new_issue.get('assigneeId') == 'u_eng'\",\"pass_condition\":\"新 issue 的 assigneeId 字段等于 'u_eng'\"},{\"name\":\"Jira Component 3\",\"weight\":0.10,\"description\":\"summary 和 description 中识别出 Contoso 客户声明的 SSO outage 及影响\",\"check_logic\":\"合并 summary 和 description 文本,检查 has_contoso、has_sso_login、has_outage_impact、has_p1_critical 均为真\",\"pass_condition\":\"文本中同时包含 Contoso、SSO/登录相关关键词、outage/影响描述、P1/severity 关键词\"},{\"name\":\"Salesforce Component 1\",\"weight\":0.13,\"description\":\"case-contoso 状态升级为 Escalated,且账户和负责人保持不变\",\"check_logic\":\"检查 case-contoso 存在,option_in(status, ('Escalated',)) 为真,accountId == 'account-contoso',ownerId == 'user-2'\",\"pass_condition\":\"case-contoso 状态为 Escalated,accountId 为 account-contoso,ownerId 为 user-2\"},{\"name\":\"Salesforce Component 2\",\"weight\":0.12,\"description\":\"case-contoso 优先级设为 Critical\",\"check_logic\":\"检查 contoso_case 存在且 option_in(priority, ('Critical',)) 为真\",\"pass_condition\":\"case-contoso 的 priority 为 Critical\"},{\"name\":\"Notion Component 1\",\"weight\":0.09,\"description\":\"在 page-incidents 下新建标题包含 Contoso SSO outage 的子页面\",\"check_logic\":\"检查 new_page 存在,标题中 has_contoso 为真,且 has_sso_login 或包含 outage/incident/p1/critical 关键词\",\"pass_condition\":\"page-incidents 下存在新子页面,标题包含 Contoso 且包含 SSO/登录/outage/incident/P1/critical 相关词\"},{\"name\":\"Notion Component 2\",\"weight\":0.04,\"description\":\"页面内容包含 Impact 区域(约4000用户、SSO、14:05开始、严重程度)\",\"check_logic\":\"检查 page_text 中 has_user_count、has_sso_login、has_time(14,5)、has_p1_critical 或 blocked 均为真\",\"pass_condition\":\"页面文本同时包含约4000用户、SSO/登录、14:05时间、P1/severity/blocked 信息\"},{\"name\":\"Notion Component 3\",\"weight\":0.04,\"description\":\"页面内容包含 Timeline 区域,记录 14:05、14:20、14:35 三个时间点\",\"check_logic\":\"检查 TIMELINE_TIMES = ((14,5),(14,20),(14,35)) 三个时间是否都存在于 page_text 中\",\"pass_condition\":\"页面文本中同时包含 14:05、14:20、14:35 三个时间\"},{\"name\":\"Notion Component 4\",\"weight\":0.04,\"description\":\"页面内容包含 Current Owner 区域(提及负责人/lead 及具体人名)\",\"check_logic\":\"检查 page_text 中 has_any(['owner', 'lead', 'commander', '负责人']) 和 has_any(['raj', 'raj patel', 'priya', 'john smith', 'sarah']) 均为真\",\"pass_condition\":\"页面文本同时包含 owner/lead/commander/负责人 标签和 Raj/Priya/John Smith/Sarah 等人名\"},{\"name\":\"Notion Component 5\",\"weight\":0.04,\"description\":\"页面内容包含 Next Update Time,且包含具体时钟时间或相对时间\",\"check_logic\":\"检查 has_next_update_label(page_text) 为真,且 extract_times 中存在不同于 TIMELINE_TIMES 的未来时间,或 has_relative_eta 为真\",\"pass_condition\":\"页面文本包含 next update 相关标签,并包含一个非 14:05/14:20/14:35 的时钟时间或相对 ETA(如 in 30 minutes、later today 等)\"},{\"name\":\"Slack Component 1\",\"weight\":0.08,\"description\":\"在客户声明的 P1 线程中发布新回复\",\"check_logic\":\"通过比对 initial_state 和 current_state 的 messageId,找出 incidents 频道中属于客户声明 P1 线程(包含 Contoso、P1、SSO、impact)的新回复\",\"pass_condition\":\"存在新消息回复在客户声明的 P1 线程中\"},{\"name\":\"Slack Component 2\",\"weight\":0.06,\"description\":\"Slack 回复中引用 Jira issue key\",\"check_logic\":\"检查回复文本是否匹配正则 \\\\bsup\\\\s*[-#]?\\\\s*\\\\d+\\\\b 或包含 new_issue 的实际 key\",\"pass_condition\":\"回复内容包含 SUP-数字 格式的 Jira key 或实际 issue key\"},{\"name\":\"Slack Component 3\",\"weight\":0.06,\"description\":\"Slack 回复中引用 incident record(Notion 页面标题或记录关键词)\",\"check_logic\":\"检查回复文本是否包含 notion/incident summary/record 等关键词,或包含 Contoso 和 outage/incident/SSO,或包含 Notion 页面标题\",\"pass_condition\":\"回复内容包含 incident record 相关关键词、或 Contoso+outage/SSO 组合、或 Notion 页面标题\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空 → 打印 CRITICAL 并返回 0.0 退出\",\"从任一 mock 服务(slack/jira/salesforce/notion)拉取状态失败 → 打印 CRITICAL 并返回 0.0 退出\",\"Jira 中未找到 SUP 项目下符合 incident 信号的新 issue → Jira 组件全部失败\",\"Salesforce 中未找到 case-contoso → Salesforce 组件全部失败\",\"Notion 中未找到 page-incidents 下的新子页面 → Notion 组件全部失败\",\"Slack 中未找到客户声明 P1 线程的新回复 → Slack 组件全部失败\",\"各组件内部异常被捕获后打印 ERROR,该组件不得分,但脚本继续执行后续组件\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,然后向四个 mock 服务(slack、jira、salesforce、notion)分别拉取 initial_state 和 current_state。接着按顺序验证四个领域:1) Jira:识别 SUP 项目中不在初始状态的新 issue,按类型/优先级(0.12)、负责人(0.08)、内容完整性(0.10)评分;2) Salesforce:定位 case-contoso,按状态升级为 Escalated 且账户/负责人不变(0.13)、优先级为 Critical(0.12)评分;3) Notion:查找 page-incidents 下的新子页面,按标题(0.09)、Impact 区域(0.04)、Timeline 三个时间点(0.04)、Owner 区域(0.04)、Next Update Time(0.04)评分;4) Slack:在客户声明的 P1 线程中找新回复,按存在回复(0.08)、引用 Jira key(0.06)、引用 incident record(0.06)评分。各组件通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。任何关键步骤(读 sid、拉 mock 状态)失败会立即退出并返回 0.0。\",\"confidence\":1.0}" +} diff --git a/csops_ticket_queue_005__long/_cua_gym_vm_bridge.sh b/csops_ticket_queue_005__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/csops_ticket_queue_005__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/csops_ticket_queue_005__long/initial_setup.py b/csops_ticket_queue_005__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ba30be011b7fa4bcea03fce69591fdeaaa2dbcae --- /dev/null +++ b/csops_ticket_queue_005__long/initial_setup.py @@ -0,0 +1,712 @@ +""" +Initial Setup: Support ticket triage with hidden SLA rules & ask-before-guess +Task ID: csops_ticket_queue_005__long (output/0707 #10, cluster C / support) +Mocks: Zendesk_mock, slack_mock, gmail_mock, google_sheets_mock + +The agent is a support lead triaging the overnight ticket queue in Zendesk. Set a +priority + route each new ticket per an SLA POLICY -- NOT in the instruction: + + * lever g (hidden rule): priority rules (keyword down/outage/breach -> urgent; + Enterprise tier -> high; else normal) live in the Slack #support-ops PINNED message; + a DM names a VIP account (Globex) whose tickets are ALWAYS urgent. Merge both. + * lever k (PROACTIVE / ask-if-unsure): ticket #1007 gives no customer tier, so it + cannot be prioritized from the ticket + SLA policy alone. The agent should ASK in + #support-ops instead of guessing. We reward the *act of asking* (a #support-ops + message naming the ticket + a question marker); #1007 is NOT in the priority + decision set and has no scored "correct" priority (we can't preset a mid-run reply). + * lever i (bulk + keep-group): 16 tickets. 8 new to triage; 1 ambiguous (ask, not + graded for priority); 3 spam (skip); 2 already triaged + 2 solved/closed (keep). + Triaging a spam/keep/ask ticket, or a wrong priority, lowers decision-set PRECISION. + Denominator = the 8. + +Urgent tickets escalate to Tier 2 (group_id=2). The agent logs a "Triage Log" register +(Ticket, Priority, Escalated) and posts+pins a summary to #support-ops. + +GROUND TRUTH: Zendesk.tickets[*]._tri {branch, priority, escalate, customer, actionable}; +google_sheets._task_adapter holds the answer key + ask_detector + VIP. +Observable results ship ABSENT (Rule 3): new/ask tickets priority null / group 1, register +header-only, no question/reply. + +SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't triage spam/keep/ask" is a +PRECISION denominator; the ask is a positive act-of-asking component (no preset reply). No +negatives. +""" +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}') + + +VIP_ACCOUNT = 'Globex' +# review comment #1: we cannot preset a mid-run reply, so #1007 is a genuinely +# ambiguous ticket the agent should ASK about (not guess). We grade the *act of +# asking*, not a revealed answer — so #1007 has no "correct" priority and is +# excluded from the priority decision set. +ASK_TICKET = 1007 +URGENT_KEYWORDS = ['down', 'outage', 'breach'] +TIER2_GROUP = 2 +# review (2026-07-11, gmail round): a support lead wraps up the overnight triage by emailing a +# one-line summary to the support team. This is the task's Gmail action (real + gradeable). +SUMMARY_TO = 'support-team@northgate.com' +SUMMARY_SUBJECT = 'Overnight triage summary - 2026-04-30' + + +# --------------------------------------------------------------------------- +# Ticket spec: (id, subject, customer, tier, status, kind) +# tier: 'Enterprise'|'Standard'|None (None = 1007, unknown -> ASK, don't guess) +# kind: 'triage'=new to triage (8) / 'ask'=ambiguous, ask instead of guess (1) / +# 'spam'=skip / 'triaged'=already done (keep) / 'closed'=solved/closed (keep) +# priority computed by the SLA rule below (VIP or keyword -> urgent; Enterprise -> high; else normal). +# --------------------------------------------------------------------------- +_TICKET_SPEC = [ + # --- 8 new to triage (deterministically decidable from the SLA policy) --- + (1001, 'Production system is down', 'Acme', 'Standard', 'new', 'triage'), # keyword -> urgent + (1002, 'API returning 500 outage', 'Initech', 'Enterprise', 'new', 'triage'), # keyword -> urgent + (1003, 'Security breach suspected', 'Umbrella','Standard', 'new', 'triage'), # keyword -> urgent + (1004, 'Feature request: dark mode', 'Globex', 'Standard', 'new', 'triage'), # VIP -> urgent + (1005, 'Cannot export report', 'Soylent', 'Enterprise', 'new', 'triage'), # Enterprise -> high + (1006, 'Question about invoice', 'Stark', 'Enterprise', 'new', 'triage'), # Enterprise -> high + (1008, 'How do I reset my password', 'Hooli', 'Standard', 'new', 'triage'), # normal + (1009, 'Typo on marketing page', 'Wonka', 'Standard', 'new', 'triage'), # normal + # --- 1 ambiguous: no customer tier -> ASK in #support-ops, do NOT guess --- + (1007, 'Billing question', 'Wayne', None, 'new', 'ask'), # k: unknown tier -> ask + # --- 3 spam (skip) --- + (1010, 'You won a prize!!!', 'spammer', 'Standard', 'new', 'spam'), + (1011, 'Cheap meds online', 'spammer', 'Standard', 'new', 'spam'), + (1012, 'Re: re: re: FWD winner', 'spammer', 'Standard', 'new', 'spam'), + # --- 2 already triaged (keep) --- + (1013, 'Login loop on mobile', 'Tyrell', 'Enterprise', 'open', 'triaged'), # priority already set + (1014, 'Data sync delay', 'Vandelay','Standard', 'open', 'triaged'), + # --- 2 solved/closed (keep) --- + (1015, 'Old issue resolved', 'Oscorp', 'Standard', 'solved', 'closed'), + (1016, 'Closed ticket', 'Nakatomi','Standard', 'closed', 'closed'), +] + + +def _sla_priority(subject, customer, tier): + s = subject.lower() + if any(k in s for k in URGENT_KEYWORDS): + return 'urgent' + if customer == VIP_ACCOUNT: + return 'urgent' + if tier == 'Enterprise': + return 'high' + return 'normal' + + +def _build_ticket(tid, subject, customer, tier, status, kind): + if kind == 'triage': + priority = _sla_priority(subject, customer, tier) + branch, escalate, actionable = 'triage', (priority == 'urgent'), True + elif kind == 'ask': + # ambiguous — the agent should ask, not guess; no "correct" priority to grade + branch, priority, escalate, actionable = 'ask', None, False, False + elif kind == 'spam': + branch, priority, escalate, actionable = 'skip', None, False, False + elif kind == 'triaged': + branch, priority, escalate, actionable = 'keep', 'high', False, False + else: + branch, priority, escalate, actionable = 'keep', None, False, False + + # injected state: new/ask tickets ship priority null + group 1; keep tickets pre-set. + if kind in ('triage', 'ask'): + inj_priority, inj_group = None, 1 + elif kind == 'triaged': + inj_priority, inj_group = 'high', TIER2_GROUP + else: + inj_priority, inj_group = (None if kind == 'spam' else None), 1 + + tags = ['spam'] if kind == 'spam' else [] + # NOTE (2026-07-15 fix): Zendesk_mock's ViewsPage/TicketDetail/Header all + # render the requester by looking `ticket.requester_id` up in `state.users[]` + # (matching on `id`) and displaying `user.name` — they ignore `customer_name` + # entirely. So we tie requester_id to the ticket id 1:1 and seed a matching + # end-user in _ZENDESK_STATE.users below (name = the ticket's customer), + # otherwise the Requester column and Contact Info panel come up blank. + return { + 'id': tid, 'subject': subject, 'description': subject, + 'status': status, 'priority': inj_priority, + 'requester_id': tid, 'submitter_id': tid, + 'assignee_id': None, 'group_id': inj_group, + 'customer_name': customer, 'customer_tier': tier, 'tags': tags, + 'created_at': '2026-04-30T02:00:00Z', 'updated_at': '2026-04-30T02:00:00Z', + 'is_public': True, 'comment_count': 1, + '_tri': {'branch': branch, 'priority': priority, 'escalate': escalate, + 'customer': customer, 'actionable': actionable}, + } + + +_TICKETS = [_build_ticket(*spec) for spec in _TICKET_SPEC] + + +# --------------------------------------------------------------------------- +# Precompute answer key. +# --------------------------------------------------------------------------- +TRIAGE_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'triage'] +URGENT_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'triage' and t['_tri']['escalate']] +ASK_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'ask'] +SKIP_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'skip'] +KEEP_IDS = [t['id'] for t in _TICKETS if t['_tri']['branch'] == 'keep'] +PRIORITY_BY_ID = {t['id']: t['_tri']['priority'] for t in _TICKETS if t['_tri']['branch'] == 'triage'} +EXPECTED_REGISTER = [ + {'Ticket': t['id'], 'Priority': t['_tri']['priority'], + 'Escalated': 'yes' if t['_tri']['escalate'] else 'no'} + for t in _TICKETS if t['_tri']['branch'] == 'triage' +] + +assert len(TRIAGE_IDS) == 8, TRIAGE_IDS +assert len(ASK_IDS) == 1 and ASK_IDS[0] == ASK_TICKET, ASK_IDS +assert len(SKIP_IDS) == 3 and len(KEEP_IDS) == 4, (SKIP_IDS, KEEP_IDS) +_prios = set(PRIORITY_BY_ID.values()) +assert {'urgent', 'high', 'normal'} <= _prios, _prios +assert ASK_TICKET not in PRIORITY_BY_ID, 'ask ticket must be excluded from the priority decision set' +assert len(URGENT_IDS) >= 2, URGENT_IDS +print(f'Triage: {TRIAGE_IDS}; urgent(escalate): {URGENT_IDS}; ask: {ASK_IDS}; skip: {SKIP_IDS}; keep: {KEEP_IDS}') +print(f'Priorities: {PRIORITY_BY_ID}') + + +# --------------------------------------------------------------------------- +# Zendesk state. +# +# NOTE (review comment #4): the Views page (route /views/:id) renders a ticket +# list by evaluating each view's `conditions` against the tickets. If `views` +# is empty, `currentView` is undefined and the list shows "No tickets in this +# view" even though the dashboard's inline "Unassigned" counter (which does NOT +# use views) still reports 14. So we MUST seed the standard Zendesk views here. +# These 8 defaults mirror Zendesk_mock/src/utils/dataManager.js:createInitialData(). +# The "Unassigned tickets" view (id 2) = {assignee_id is null AND status < solved}, +# which matches our 14 non-solved unassigned tickets (8 triage + 1 ask + 3 spam + +# 2 already-triaged open). +# --------------------------------------------------------------------------- +_ZENDESK_VIEWS = [ + {'id': 1, 'title': 'Your unsolved tickets', 'description': 'Tickets assigned to you that are not yet solved', + 'active': True, 'position': 0, 'type': 'standard', + 'conditions': {'all': [{'field': 'assignee_id', 'operator': 'is', 'value': 'current_user'}, + {'field': 'status', 'operator': 'less_than', 'value': 'solved'}], 'any': []}}, + {'id': 2, 'title': 'Unassigned tickets', 'description': 'Tickets with no assignee', + 'active': True, 'position': 1, 'type': 'standard', + 'conditions': {'all': [{'field': 'assignee_id', 'operator': 'is', 'value': None}, + {'field': 'status', 'operator': 'less_than', 'value': 'solved'}], 'any': []}}, + {'id': 3, 'title': 'All unsolved tickets', 'description': 'All tickets that are not solved or closed', + 'active': True, 'position': 2, 'type': 'standard', + 'conditions': {'all': [{'field': 'status', 'operator': 'less_than', 'value': 'solved'}], 'any': []}}, + {'id': 4, 'title': 'Recently updated tickets', 'description': 'Tickets updated in the last 7 days', + 'active': True, 'position': 3, 'type': 'standard', + 'conditions': {'all': [{'field': 'updated_at', 'operator': 'within', 'value': '7_days'}], 'any': []}}, + {'id': 5, 'title': 'Recently solved tickets', 'description': 'Tickets solved in the last 7 days', + 'active': True, 'position': 4, 'type': 'standard', + 'conditions': {'all': [{'field': 'status', 'operator': 'is', 'value': 'solved'}], 'any': []}}, + {'id': 6, 'title': 'Pending tickets', 'description': 'All pending tickets', + 'active': True, 'position': 5, 'type': 'standard', + 'conditions': {'all': [{'field': 'status', 'operator': 'is', 'value': 'pending'}], 'any': []}}, + {'id': 7, 'title': 'New tickets', 'description': 'All new tickets', + 'active': True, 'position': 6, 'type': 'shared', + 'conditions': {'all': [{'field': 'status', 'operator': 'is', 'value': 'new'}], 'any': []}}, + {'id': 8, 'title': 'Urgent & High priority', 'description': 'Urgent and high priority unsolved tickets', + 'active': True, 'position': 7, 'type': 'personal', + 'conditions': {'all': [{'field': 'status', 'operator': 'less_than', 'value': 'solved'}], + 'any': [{'field': 'priority', 'operator': 'is', 'value': 'urgent'}, + {'field': 'priority', 'operator': 'is', 'value': 'high'}]}}, +] + +# --------------------------------------------------------------------------- +# Requester end-user records — one per ticket, id == ticket.id. +# Zendesk_mock's UI (ViewsPage requester column, TicketDetail Contact Info, +# Header conversations popover) all resolve the requester via +# `state.users.find(u => u.id === ticket.requester_id)`, so if these are absent +# the Requester column shows `—` and the ticket detail's right-hand Contact +# Info panel is blank (which is exactly what the 2026-07-15 review flagged for +# #1007 Wayne). We seed a lightweight end-user for every ticket so each +# customer name shows up in the UI. Nothing here affects reward.py (which +# doesn't read users[]). +# --------------------------------------------------------------------------- +def _initials(name): + parts = [p for p in name.split() if p] + if not parts: + return '??' + if len(parts) == 1: + return parts[0][:2].upper() + return (parts[0][0] + parts[-1][0]).upper() + +_REQUESTER_USERS = [ + {'id': t['id'], 'name': t['customer_name'], + 'email': f"contact{t['id']}@{t['customer_name'].lower().replace(' ', '')}.example.com", + 'role': 'end-user', 'phone': None, 'photo': None, + 'organization_id': None, 'group_id': None, + 'time_zone': 'America/New_York', 'locale': 'en-US', + 'suspended': False, 'verified': True, 'active': True, + 'created_at': '2025-01-01T00:00:00Z', 'updated_at': '2026-04-01T00:00:00Z', + 'last_login_at': '2026-04-29T09:00:00Z', + 'initials': _initials(t['customer_name'])} + for t in _TICKETS +] + +_ZENDESK_STATE = { + 'currentUser': {'id': 1, 'name': 'Nadia Farouk', 'email': 'nadia@northgate.com', + 'role': 'admin', 'group_id': 1}, + 'users': [ + {'id': 1, 'name': 'Nadia Farouk', 'email': 'nadia@northgate.com', 'role': 'admin', 'group_id': 1}, + {'id': 3, 'name': 'Emily Rodriguez', 'email': 'emily@northgate.com', 'role': 'agent', 'group_id': 2}, + *_REQUESTER_USERS, + ], + 'groups': [ + {'id': 1, 'name': 'Tier 1 Support', 'description': 'Frontline', 'default': True}, + {'id': 2, 'name': 'Tier 2 Support', 'description': 'Escalations', 'default': False}, + ], + 'tickets': _TICKETS, + 'comments': {}, 'views': _ZENDESK_VIEWS, 'macros': [], + '_task_adapter': {'source_schema': 'ticket_triage', + 'task_id': 'e7f3a210-5c9d-4a1b-b70e-0707ee556688'}, +} + + +# --------------------------------------------------------------------------- +# Google Sheet — 'Triage Log' register (header only) + answer key. +# --------------------------------------------------------------------------- +REG_HEADERS = ['Ticket', 'Priority', 'Escalated'] +_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_triage', 'title': 'Triage 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': 'Triage 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': 'ticket_triage', + 'task_id': 'e7f3a210-5c9d-4a1b-b70e-0707ee556688', + 'variant': 'eval', + 'target_sheet': 'Triage Log', + 'headers': REG_HEADERS, + 'headers_by_sheet': {'Triage Log': REG_HEADERS}, + 'sheet_names': ['Triage Log'], + 'tier2_group': TIER2_GROUP, + # ---- ANSWER KEY ---- + 'triage_ids': TRIAGE_IDS, + 'urgent_ids': URGENT_IDS, + 'ask_ids': ASK_IDS, + 'skip_ids': SKIP_IDS, + 'keep_ids': KEEP_IDS, + 'priority_by_id': {str(k): v for k, v in PRIORITY_BY_ID.items()}, + 'expected_register': EXPECTED_REGISTER, + # review comment #1: no preset mid-run reply. We only detect that the agent + # RAISED the ambiguous ticket in #support-ops (trigger keyword + a question + # marker). There is no scored "correct answer" for #1007 anymore. + 'ask_ticket': ASK_TICKET, + 'ask_detector': { + 'trigger_keywords': ['1007', 'billing question', 'wayne'], + 'question_markers': ['?', 'tier', 'priority', 'unsure', 'not sure', 'clarify', + 'which', 'confirm', 'what'], + }, + # review (2026-07-11, gmail round): the wrap-up summary email answer key. + 'summary_to': SUMMARY_TO, + 'summary_subject': SUMMARY_SUBJECT, + }, +} + + +# --------------------------------------------------------------------------- +# Gmail — inbound context (a forwarded customer note) + decoy. The agent also SENDS a +# wrap-up triage-summary email here (review 2026-07-11); that outgoing email is graded. +# --------------------------------------------------------------------------- +_GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Nadia Farouk', 'email': 'nadia@northgate.com', + 'avatar': 'https://picsum.photos/200/200?random=19'}, + 'emails': [ + {'id': 'm_note', 'threadId': 'thread_n', + 'from': {'name': 'Globex Support', 'email': 'it@globex.com', 'avatar': ''}, + 'to': [{'name': 'Nadia Farouk', 'email': 'nadia@northgate.com'}], 'cc': [], 'bcc': [], + 'subject': 'FYI — we filed a feature request', + 'body': 'Just a heads up we filed a ticket for dark mode. Thanks!', + 'snippet': 'We filed a ticket for dark mode...', 'timestamp': '2026-04-30T01:00:00Z', + 'read': False, 'starred': False, 'important': False, 'labels': [], + 'category': 'primary', 'folder': 'inbox', 'attachments': []}, + {'id': 'm_decoy1', 'threadId': 'thread_d1', + 'from': {'name': 'Support Newsletter', 'email': 'news@northgate.com', 'avatar': ''}, + 'to': [{'name': 'Nadia Farouk', 'email': 'nadia@northgate.com'}], 'cc': [], 'bcc': [], + 'subject': 'April support tips', 'body': 'Reminders.', 'snippet': 'Reminders...', + 'timestamp': '2026-04-29T15:00:00Z', 'read': True, 'starred': False, + 'important': False, 'labels': [], 'category': 'updates', 'folder': 'inbox', + 'attachments': []}, + ], + 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}], + 'drafts': [], 'settings': {'density': 'default', 'undoSend': 10}, 'today': '2026-04-30', +} + + +# --------------------------------------------------------------------------- +# Slack — #support-ops pinned SLA policy + VIP DM (lever g). +# --------------------------------------------------------------------------- +_POLICY_TEXT = ( + ':pushpin: SUPPORT SLA TRIAGE POLICY (read before triaging)\n' + '1) Only triage tickets in status new; leave already-triaged, solved, or closed tickets.\n' + '2) Skip spam tickets (tagged spam) — do not set a priority.\n' + '3) Priority: if the subject mentions an outage/down/breach -> URGENT; else if the customer ' + 'is on the Enterprise tier -> HIGH; otherwise NORMAL.\n' + '4) Escalate every URGENT ticket to Tier 2 (group 2).' +) +_DM_TEXT = ( + 'Reminder: Globex is our VIP account — treat ALL of their tickets as URGENT regardless of ' + 'the subject. Thanks!' +) + +_SLACK_STATE = { + 'currentUser': {'userId': 'user_1', 'name': 'Nadia Farouk', 'fullName': 'Nadia Farouk', + 'displayName': 'Nadia Farouk'}, + # NOTE (review comment #2): slack_mock renders a message author by looking the + # message's senderId up in users[] (key = `userId`) and displaying `fullName` + # (falling back to `displayName`, else the literal "Unknown User"). It ignores + # `name`/`firstName`/`lastName`. So every user MUST carry `fullName`+`displayName` + # or the channel shows "Unknown User" for the pinned policy / DM / replies. + 'users': [ + {'userId': 'user_1', 'firstName': 'Nadia', 'lastName': 'Farouk', 'name': 'Nadia Farouk', + 'fullName': 'Nadia Farouk', 'displayName': 'Nadia Farouk'}, + {'userId': 'user_2', 'firstName': 'Sam', 'lastName': 'Wren', 'name': 'Sam Wren', + 'fullName': 'Sam Wren', 'displayName': 'Sam Wren'}, + ], + # NOTE: slack_mock's index route hard-redirects to /channel/general (see App.jsx), + # so we MUST seed a channelId='general' channel or the workspace lands on + # "Channel not found". #general is pure watermark (harmless chatter); the task + # (SLA policy + VIP DM + agent's question/summary) all live in #support-ops. + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements and chatter', + 'topic': 'Say hi \U0001F44B', 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', + 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'support_ops', 'name': 'support-ops', 'description': 'Support operations', + 'topic': 'Triage', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', + 'createdAt': '2026-01-01T10:00:00Z', 'pinnedMessages': ['msg_policy'], 'unreadCount': 0}, + ], + 'messages': { + # Harmless watermark chatter — no ask-detector trigger keywords + # (1007/billing/wayne) and no summary keywords, so it cannot leak scoring. + 'general': [ + {'messageId': 'msg_gen_1', 'senderId': 'user_2', + 'content': 'Good morning team! Coffee machine on 4F is back online \u2615', + 'timestamp': '2026-04-29T09:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_gen_2', 'senderId': 'user_1', + 'content': 'Reminder: quarterly all-hands moved to Friday afternoon.', + 'timestamp': '2026-04-29T15:30:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_gen_3', 'senderId': 'user_2', + 'content': 'Office closed Monday for the public holiday \U0001F389', + 'timestamp': '2026-04-30T01:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + 'support_ops': [ + {'messageId': 'msg_policy', 'senderId': 'user_2', 'content': _POLICY_TEXT, + 'timestamp': '2026-04-01T09:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + 'dm_1': [ + {'messageId': 'msg_dm_vip', 'senderId': 'user_2', 'content': _DM_TEXT, + 'timestamp': '2026-04-02T11:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + }, + 'threads': {}, + 'dms': [{'dmId': 'dm_1', 'participants': ['user_1', 'user_2'], 'lastMessage': _DM_TEXT, + 'lastTime': '2026-04-02T11:00:00Z', 'unreadCount': 1}], + 'bookmarkedMessages': [], 'callHistory': [], 'notifications': [], +} + + +# --------------------------------------------------------------------------- +# Inject. +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8107', _ZENDESK_STATE), # Zendesk_mock + ('http://28.7.184.198:8178', _SLACK_STATE), # slack_mock + ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock + ('http://28.7.184.198:8145', _SHEET_STATE), # google_sheets_mock +] + + +for app_url, state in APP_STATES: + resp = requests.post(f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'State injection failed for {app_url}: {resp.text}' + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}') + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/csops_ticket_queue_005__long/reward.py b/csops_ticket_queue_005__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..45f6f3bbb1053822100db3aa9a09dd5772a0bc7d --- /dev/null +++ b/csops_ticket_queue_005__long/reward.py @@ -0,0 +1,376 @@ +""" +Reward Script: Support ticket triage with hidden SLA rules & ask-if-unsure +Task ID: csops_ticket_queue_005__long (output/0707 #10, cluster C / support) +Mocks: Zendesk_mock, slack_mock, gmail_mock, google_sheets_mock + +Scoring — ALL positive. Every component in [0,1]; weights sum to 1.0. NO penalties, NO gate. + + 0.35 priority decision-set precision: + frac(#new tickets set to their CORRECT priority, 8 + #wrongly-prioritized) + (prioritizing a spam/keep/ask ticket, or wrong priority, = false positive) + 0.15 escalation correctness: frac of urgent tickets with group_id == Tier 2 + 0.20 ask-if-unsure (k): a NEW #support-ops question raising the ambiguous ticket #1007 + (trigger keyword + a question marker). Review comment #1: we grade only the ACT of + asking — no preset mid-run reply, and #1007 has no scored "correct" priority. + 0.05 gmail wrap-up summary: a NEW email to the support team with the exact triage-summary + subject (recipient + subject judged, not body). Review 2026-07-11 (gmail round). + 0.15 triage-log F1 over (Ticket, Priority, Escalated) for the 8 + 0.05 slack post 0.05 pinned (gated on post) + +Answer key: google_sheets.initial_state._task_adapter (triage_ids, urgent_ids, ask_ids, +priority_by_id, expected_register, ask_detector, tier2_group, summary_to, summary_subject) ++ Zendesk.tickets[*]._tri. +""" +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 = { + 'zendesk': 'http://28.7.184.198:8107', + 'google_sheets': 'http://28.7.184.198:8145', + 'slack': 'http://28.7.184.198:8178', + 'gmail': 'http://28.7.184.198:8138', +} +_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(slack_state, channel_name): + channels = slack_state.get('channels') if isinstance(slack_state.get('channels'), list) else [] + for ch in channels: + if isinstance(ch, dict) and norm(ch.get('name')) == norm(channel_name): + return ch + return None + + +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_PRIORITY = 0.35 + W_ESCAL = 0.15 + W_ASK = 0.20 + W_SUMMARY = 0.05 + W_LOG = 0.15 + W_POST = 0.05 + W_PIN = 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 {} + + triage_ids = set(int(x) for x in (adapter.get('triage_ids') or [])) + urgent_ids = set(int(x) for x in (adapter.get('urgent_ids') or [])) + ask_ids = set(int(x) for x in (adapter.get('ask_ids') or [])) + priority_by_id = {int(k): norm(v) for k, v in (adapter.get('priority_by_id') or {}).items()} + expected_register = adapter.get('expected_register') if isinstance(adapter.get('expected_register'), list) else [] + tier2 = adapter.get('tier2_group', 2) + # review comment #1: ask_detector (act-of-asking) replaces the old preset-reply user_simulator. + sim = adapter.get('ask_detector') if isinstance(adapter.get('ask_detector'), dict) else {} + # review (gmail round): wrap-up summary email target + subject. + summary_to = norm(adapter.get('summary_to')) + summary_subject = norm(adapter.get('summary_subject')) + target_sheet = adapter.get('target_sheet') or 'Triage Log' + n_tri = len(triage_ids) + if n_tri == 0: + print('DEBUG_ZD_TRIAGE fatal=no_triage_ids total=0.0') + return 0.0 + + # ---- 2) Zendesk: priority diff (only newly-set on triage tickets count) ---- + zd = go('zendesk') + zd_init = zd.get('initial_state', {}) if isinstance(zd.get('initial_state'), dict) else {} + zd_cur = zd.get('current_state', {}) if isinstance(zd.get('current_state'), dict) else {} + + def _tk_map(state): + out = {} + for t in (state.get('tickets') or []): + if isinstance(t, dict): + out[int(t.get('id'))] = t + return out + + init_t = _tk_map(zd_init) + cur_t = _tk_map(zd_cur) + + # a priority was newly set on a ticket if it changed from its injected value + correct_prio = 0 + wrongly_prio = 0 + for tid, t in cur_t.items(): + cur_p = norm(t.get('priority')) + init_p = norm(init_t.get(tid, {}).get('priority')) + if not cur_p or cur_p == init_p: + continue # no new priority set + # newly prioritized ticket + if tid in triage_ids and cur_p == priority_by_id.get(tid): + correct_prio += 1 + else: + wrongly_prio += 1 # spam/keep ticket prioritized, or wrong priority + priority_score = frac(correct_prio, n_tri + wrongly_prio) + s_priority = W_PRIORITY * priority_score + + # ---- 3) escalation correctness: urgent tickets -> Tier 2 group ---- + esc_ok = 0 + for tid in urgent_ids: + if int(cur_t.get(tid, {}).get('group_id', -1)) == int(tier2): + esc_ok += 1 + escal_score = frac(esc_ok, len(urgent_ids)) if urgent_ids else 0.0 + s_escal = W_ESCAL * escal_score + + # ---- 4) ask-if-unsure (k): agent raised the ambiguous ticket in #support-ops ---- + # review comment #1: we grade only the ACT of asking (trigger keyword + a question + # marker in a new #support-ops message). No preset reply, no scored answer for #1007. + 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_ids = {(m.get('messageId') or m.get('id')) + for m in _slack_channel_messages(sinit, 'support-ops') if isinstance(m, dict)} + triggers = [norm(k) for k in (sim.get('trigger_keywords') or [])] + markers = [norm(k) for k in (sim.get('question_markers') or [])] + ask_ok = False + new_msgs = [] + for m in _slack_channel_messages(scur, 'support-ops'): + mid = m.get('messageId') or m.get('id') + if mid in init_ids: + continue + if (_msg_text(m) or '').strip(): + new_msgs.append(m) + txt = norm(_msg_text(m)) + if any(t in txt for t in triggers) and any(k in txt for k in markers): + ask_ok = True + s_ask = W_ASK * (1.0 if ask_ok else 0.0) + + # ---- 5) triage-log F1 over (Ticket, Priority, Escalated) ---- + 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] + tk = _s(row.get(0)) + pr = _s(row.get(1)) + esc = _s(row.get(2)) + if not tk and not pr: + continue + log_rows.append((tk, pr, esc)) + + def _log_key(tk, pr, esc): + tkn = ''.join(ch for ch in str(tk) if ch.isdigit()) + return (tkn, norm(pr), norm(esc)) + + true_log = {_log_key(d['Ticket'], d['Priority'], d['Escalated']) for d in expected_register} + pred_log = {_log_key(*r) for r in log_rows} + log_f1 = f1(true_log, pred_log) + s_log = W_LOG * log_f1 + + # ---- 6) gmail wrap-up summary email (review 2026-07-11) ---- + # A NEW outgoing email addressed to the support team with the exact summary subject. + # We judge recipient + subject (not body contents), matching the instruction. + gm = go('gmail') + gm_cur = gm.get('current_state', {}) if isinstance(gm.get('current_state'), dict) else {} + gm_init = gm.get('initial_state', {}) if isinstance(gm.get('initial_state'), dict) else {} + + def _gm_all(state): + out = [] + for key in ('emails', 'drafts'): + v = state.get(key) + if isinstance(v, list): + out += [m for m in v if isinstance(m, dict)] + return out + + def _gm_recipients(m): + out = set() + for r in (m.get('to') or []): + if isinstance(r, dict): + out.add(norm(r.get('email'))) + else: + out.add(norm(r)) + return out + + gm_init_ids = {m.get('id') for m in _gm_all(gm_init)} + gm_new = [m for m in _gm_all(gm_cur) if m.get('id') not in gm_init_ids] + summary_ok = any(summary_to in _gm_recipients(m) and norm(m.get('subject')) == summary_subject + for m in gm_new) + s_summary = W_SUMMARY * (1.0 if summary_ok else 0.0) + + # ---- 7) slack post + pin ---- + _sops_kw = ('triag', 'escalat', 'ticket', 'tier') + def _is_sops_summary(m): + t = (_msg_text(m) or '').lower() + return any(k in t for k in _sops_kw) and any(c.isdigit() for c in t) + post_ok = any(_is_sops_summary(m) for m in new_msgs) + s_post = W_POST * (1.0 if post_ok else 0.0) + cur_ch = _slack_channel(scur, 'support-ops') + pinned_ids = (cur_ch.get('pinnedMessages') or []) if isinstance(cur_ch, dict) else [] + new_ids = {(m.get('messageId') or m.get('id')) for m in new_msgs} + pin_ok = bool(post_ok and any(pid in new_ids for pid in pinned_ids)) + s_pin = W_PIN * (1.0 if pin_ok else 0.0) + + score = clamp01(s_priority + s_escal + s_ask + s_summary + s_log + s_post + s_pin) + + print( + 'DEBUG_ZD_TRIAGE ' + f'n_tri={n_tri} correct_prio={correct_prio} wrong_prio={wrongly_prio} ' + f'priority={round(priority_score, 4)} esc_ok={esc_ok}/{len(urgent_ids)} ' + f'ask={ask_ok} summary={summary_ok} log_f1={round(log_f1, 4)} post={post_ok} pin={pin_ok} ' + f'w_priority={round(s_priority, 4)} w_escal={round(s_escal, 4)} w_ask={round(s_ask, 4)} ' + f'w_summary={round(s_summary, 4)} w_log={round(s_log, 4)} w_post={round(s_post, 4)} ' + f'w_pin={round(s_pin, 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/hr_it_provisioning_008__long/_cua_gym_vm_bridge.sh b/hr_it_provisioning_008__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/hr_it_provisioning_008__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/hr_it_provisioning_008__long/initial_setup.py b/hr_it_provisioning_008__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7a52026519fca566ede30de62cb5e58a6a9ce959 --- /dev/null +++ b/hr_it_provisioning_008__long/initial_setup.py @@ -0,0 +1,649 @@ +""" +Initial Setup: New-hire provisioning fan-out with cross-source config & stock-substitution +Task ID: hr_it_provisioning_008__long (output/0707 #17, cluster D / onboarding) +Mocks: workday_mock, gmail_mock, google_docs_mock, slack_mock + +The agent is an onboarding coordinator filing IT provisioning tickets for new hires. Each +hire's config is ASSEMBLED across apps -- NOT in the instruction: + + * lever d (cross-source >=4-hop): per hire -> Workday role -> google_docs config matrix + row for that role -> apply the Slack stock-substitution (laptop swap) -> assemble the + config -> Gmail ticket to IT. No single app holds a hire's final config. + * lever g (hidden config): the role->config matrix lives in a google_docs doc; the Slack + #it-onboarding pin overrides one matrix value (a laptop model is out of stock). + * lever i (bulk + keep-group): 7 hires. 5 to provision (active FT); 1 contractor (skip, + no company provisioning); 1 already-provisioned (keep). Ticketing a contractor/keep hire, + or listing a wrong config item, lowers F1 precision. Denominator = the 5. + +Substitution: matrix says Engineer laptop = "MacBook Pro 14"; Slack says the 14 is out of +stock -> use "MacBook Pro 16". A ticket listing the 14 for an Engineer is wrong. + +The agent emails IT one provisioning ticket per hire (body lists laptop + each software + +each access group), then posts a #it-onboarding summary. + +GROUND TRUTH: workday._task_adapter (provision_ids, skip_ids, keep_ids, config_by_hire, +ticket_items, substituted_item). Observable results ship ABSENT (Rule 3): no provisioning +tickets for the 5, no summary. Keep hire's ticket pre-seeded. + +SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't provision contractor/keep" folded +into the ticket-F1 precision + exact-set; substitution enforced by a positive component. No +negatives, no gate. +""" +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}') + + +IT_MAILBOX = 'it-provisioning@northgate.com' +SUBSTITUTE_FROM = 'MacBook Pro 14' +SUBSTITUTE_TO = 'MacBook Pro 16' + +# Role -> config matrix (lives in google_docs). laptop + software[] + access[]. +CONFIG_MATRIX = { + 'Engineer': {'laptop': 'MacBook Pro 14', + 'software': ['VS Code', 'Docker', 'Slack'], + 'access': ['github', 'aws-dev', 'vpn']}, + 'Sales': {'laptop': 'MacBook Air 13', + 'software': ['Salesforce', 'Slack', 'Zoom'], + 'access': ['salesforce', 'gong', 'vpn']}, + 'Designer': {'laptop': 'MacBook Pro 16', + 'software': ['Figma', 'Slack', 'Adobe CC'], + 'access': ['figma', 'design-drive', 'vpn']}, +} + + +# --------------------------------------------------------------------------- +# New-hire spec: (hireId, name, role, employeeType, kind) +# kind: 'provision' / 'skip' (contractor) / 'keep' (already provisioned) +# --------------------------------------------------------------------------- +_HIRE_SPEC = [ + ('h1', 'Alex Wong', 'Engineer', 'Full-Time', 'provision'), + ('h2', 'Bianca Roy', 'Sales', 'Full-Time', 'provision'), + ('h3', 'Carlos Diaz','Engineer', 'Full-Time', 'provision'), + ('h4', 'Dana Kim', 'Designer', 'Full-Time', 'provision'), + ('h5', 'Evan Cole', 'Sales', 'Full-Time', 'provision'), + ('h6', 'Farah Nassar','Engineer','Contractor', 'skip'), # contractor -> no provisioning + ('h7', 'Greg Olsen', 'Designer', 'Full-Time', 'keep'), # already provisioned +] + + +def _apply_config(role): + cfg = CONFIG_MATRIX[role] + laptop = SUBSTITUTE_TO if cfg['laptop'] == SUBSTITUTE_FROM else cfg['laptop'] + return {'laptop': laptop, 'software': list(cfg['software']), 'access': list(cfg['access'])} + + +_HIRES = [] +for (hid, name, role, etype, kind) in _HIRE_SPEC: + _HIRES.append({ + 'id': hid, 'name': name, + 'email': f"{name.split()[0].lower()}.{name.split()[1].lower()}@northgate.com", + 'role': role, 'department': 'Engineering' if role == 'Engineer' else role, + 'title': role, 'employeeType': etype, 'startDate': '2026-05-04', + 'onboardingStatus': 'Complete' if kind == 'keep' else 'Pending', + '_hire': {'kind': kind, 'role': role}, + }) + + +# --------------------------------------------------------------------------- +# Precompute answer key. +# --------------------------------------------------------------------------- +PROVISION_IDS = [h['id'] for h in _HIRES if h['_hire']['kind'] == 'provision'] +SKIP_IDS = [h['id'] for h in _HIRES if h['_hire']['kind'] == 'skip'] +KEEP_IDS = [h['id'] for h in _HIRES if h['_hire']['kind'] == 'keep'] +NAME_BY_ID = {h['id']: h['name'] for h in _HIRES} + +CONFIG_BY_HIRE = {} # name -> {laptop, software[], access[]} (substitution applied) +TICKET_ITEMS = {} # name -> flat list of config-item strings (for F1) +ITEM_PAIRS = [] # (hire_name, item) required pairs +for h in _HIRES: + if h['_hire']['kind'] != 'provision': + continue + cfg = _apply_config(h['role']) + CONFIG_BY_HIRE[h['name']] = cfg + items = [cfg['laptop']] + cfg['software'] + cfg['access'] + TICKET_ITEMS[h['name']] = items + for it in items: + ITEM_PAIRS.append([h['name'], it]) + +ENGINEER_HIRES = [h['name'] for h in _HIRES if h['_hire']['kind'] == 'provision' and h['role'] == 'Engineer'] + +assert len(PROVISION_IDS) == 5 and len(SKIP_IDS) == 1 and len(KEEP_IDS) == 1 +# substitution applied: every Engineer hire's laptop is the 16, not the 14 +for nm in ENGINEER_HIRES: + assert CONFIG_BY_HIRE[nm]['laptop'] == SUBSTITUTE_TO, CONFIG_BY_HIRE[nm] +print(f'Provision: {PROVISION_IDS}; skip(contractor): {SKIP_IDS}; keep: {KEEP_IDS}') +print(f'Engineer hires (laptop -> {SUBSTITUTE_TO}): {ENGINEER_HIRES}; item pairs: {len(ITEM_PAIRS)}') + + +# --------------------------------------------------------------------------- +# Workday state (read-only roster + answer key). +# +# NOTE (2026-07-12 review #3): workday_mock has NO 'newHires' surface — its pages read +# `employees` (Directory), `tasks` (Inbox), etc. Injecting only `newHires` left the roster +# invisible (Home/Inbox empty, no entry point). Fix: also inject the 7 hires as `employees` +# so they render in the DIRECTORY (its detail card shows employeeType Full-Time/Contractor, +# role/title, department, join date — exactly what's needed to decide provision/skip/keep), +# and seed one onboarding `tasks` row per provision hire so the INBOX is a second entry point. +# `newHires` is kept for readability but the answer key travels in `_task_adapter` (unchanged). +# reward reads the roster from `_task_adapter` + grades Gmail/Slack output, so neither the +# `employees` nor `tasks` seeding affects scoring. (zihang workday_mock is identical — no +# roster page to borrow; no mock backend change.) +# --------------------------------------------------------------------------- +_OB_COORD = { + 'id': 'ob1', 'name': 'Sam Ortiz', 'email': 'sam.ortiz@northgate.com', + 'phone': '+1 (415) 555-0100', 'role': 'Onboarding Coordinator', + 'department': 'People', 'departmentId': 'dept_people', + 'avatar': 'https://ui-avatars.com/api/?name=Sam+Ortiz&background=0875E1&color=fff&size=128', + 'managerId': None, 'title': 'Onboarding Coordinator', 'location': 'Remote', + 'joinDate': '2022-06-01', 'employeeType': 'Full-Time', +} + +# The 7 new hires rendered as Directory employees (report to the onboarding coordinator). +# The card shows `title` prominently, so we bake the provisioning status into the title +# (" - Onboarding (provision)" / "- Contractor (no provisioning)" / "- Provisioned") +# so the keep hire (already provisioned) and the contractor are visibly distinguishable in +# the Directory, not only by their absence from the Inbox. Real ui-avatars URLs (the mock has +# no fallback, so an empty avatar renders broken — matches the default employees). +def _hire_status_suffix(kind): + if kind == 'keep': + return 'Provisioned' # already provisioned -> leave as-is + if kind == 'skip': + return 'Contractor (no provisioning)' + return 'Onboarding (provision)' # active FT to provision + + +def _avatar_for(name): + return ('https://ui-avatars.com/api/?name=' + name.replace(' ', '+') + + '&background=0875E1&color=fff&size=128') + + +_HIRE_EMPLOYEES = [] +for h in _HIRES: + kind = h['_hire']['kind'] + _HIRE_EMPLOYEES.append({ + 'id': h['id'], 'name': h['name'], 'email': h['email'], + 'phone': '', 'role': h['role'], 'department': h['department'], + 'departmentId': '', 'avatar': _avatar_for(h['name']), 'managerId': 'ob1', + 'title': f"{h['title']} - {_hire_status_suffix(kind)}", 'location': 'Remote', + 'joinDate': h['startDate'], 'employeeType': h['employeeType'], + 'onboardingStatus': h['onboardingStatus'], + }) + +_WORKDAY_EMPLOYEES = [_OB_COORD] + _HIRE_EMPLOYEES + +# Inbox: one "Onboard new hire" task per PROVISION hire (Pending) — second roster entry point. +# These are informational (reward does NOT read workday tasks); they give the agent a worklist. +_WORKDAY_TASKS = [] +for h in _HIRES: + if h['_hire']['kind'] != 'provision': + continue + _WORKDAY_TASKS.append({ + 'taskId': f'ob_{h["id"]}', 'employeeId': 'ob1', 'type': 'To-Do', + 'subType': 'Onboarding', 'status': 'Pending', + 'description': f'Provision IT for new hire {h["name"]} ({h["role"]}, {h["employeeType"]})', + 'dueDate': h['startDate'], 'createdDate': '2026-04-30', + 'relatedId': h['id'], 'initiator': 'HRIS', 'businessProcess': 'New Hire Provisioning', + 'priority': 'Normal', 'comments': [], + }) + +_WORKDAY_STATE = { + 'currentUser': _OB_COORD, + 'employee': {'id': 'ob1', 'name': 'Sam Ortiz', 'email': 'sam.ortiz@northgate.com', + 'role': 'Onboarding Coordinator', 'department': 'People'}, + 'employees': _WORKDAY_EMPLOYEES, + 'tasks': _WORKDAY_TASKS, + 'newHires': _HIRES, + 'timeOffRequests': [], 'timeEntries': [], 'paystubs': [], + 'performanceReviews': [], 'goals': [], 'notifications': [], + 'clockStatus': {'isClockedIn': False, 'startTime': None}, + '_task_adapter': { + 'source_schema': 'provisioning_fanout', + 'task_id': 'f4a0b765-2d6e-4c8f-ce7d-0707ff22dd55', + 'variant': 'eval', + 'it_mailbox': IT_MAILBOX, + 'provision_ids': PROVISION_IDS, + 'skip_ids': SKIP_IDS, + 'keep_ids': KEEP_IDS, + 'name_by_id': NAME_BY_ID, + 'config_by_hire': CONFIG_BY_HIRE, + 'ticket_items': TICKET_ITEMS, + 'item_pairs': ITEM_PAIRS, + 'engineer_hires': ENGINEER_HIRES, + 'substituted_item': {'from': SUBSTITUTE_FROM, 'to': SUBSTITUTE_TO}, + 'skip_names': [NAME_BY_ID[i] for i in SKIP_IDS], + 'keep_names': [NAME_BY_ID[i] for i in KEEP_IDS], + }, +} + + +# --------------------------------------------------------------------------- +# google_docs — the Provisioning Config Matrix (lever d source / hidden config). +# NOTE (2026-07-12 review #2): google_docs_mock renders each doc card via +# format(new Date(doc.updated), ...) and sorts on doc.created/doc.updated. With the old +# createdAt/modifiedAt field names, doc.updated is undefined -> date-fns throws +# "RangeError: Invalid time value" and (doc-matrix is starred -> rendered on the first +# screen) the WHOLE document list crashes to a blank page. Reproduced live on 8142. Use +# created/updated to match the mock's field contract (same fix as task 11 / doc-1 default). +# --------------------------------------------------------------------------- +def _matrix_html(): + rows = [] + for role, cfg in CONFIG_MATRIX.items(): + rows.append( + f'

{role}

    ' + f'
  • Laptop: {cfg["laptop"]}
  • ' + f'
  • Software: {", ".join(cfg["software"])}
  • ' + f'
  • Access groups: {", ".join(cfg["access"])}
') + return ('

Provisioning Config Matrix

' + '

File an IT provisioning ticket per new hire with the laptop, software, and ' + 'access groups for their role.

' + ''.join(rows)) + + +_DOCS_STATE = { + 'user': {'id': 'user-1', 'name': 'Sam Ortiz', 'email': 'sam.ortiz@northgate.com'}, + 'documents': { + 'doc-matrix': {'id': 'doc-matrix', 'title': 'Provisioning Config Matrix', + 'content': _matrix_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': 'Office Map', + 'content': '

Office Map

Floor plan.

', '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': ''}, +} + + +# --------------------------------------------------------------------------- +# Gmail — provisioning tickets ABSENT for the 5; keep hire's ticket pre-seeded. +# --------------------------------------------------------------------------- +_keep_msgs = [] +for kid in KEEP_IDS: + hire = next(h for h in _HIRES if h['id'] == kid) + _keep_msgs.append({ + 'id': f'm_seed_{kid}', 'threadId': f'thr_seed_{kid}', + 'from': {'name': 'Sam Ortiz', 'email': 'sam.ortiz@northgate.com'}, + 'to': [{'name': 'IT', 'email': IT_MAILBOX}], 'cc': [], 'bcc': [], + 'subject': f'Provisioning ticket - {hire["name"]}', + 'body': 'MacBook Pro 16, Figma, Slack, Adobe CC, figma, design-drive, vpn', + 'snippet': 'provisioning', 'timestamp': '2026-04-20T09:00:00Z', + 'read': True, 'starred': False, 'important': False, 'labels': [], + 'category': 'primary', 'folder': 'sent', 'attachments': []}) + +_GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Sam Ortiz', 'email': 'sam.ortiz@northgate.com', + 'avatar': 'https://picsum.photos/200/200?random=31'}, + 'emails': [ + {'id': 'm_inbox1', 'threadId': 'thread_i1', + 'from': {'name': 'HRIS', 'email': 'hris@northgate.com', 'avatar': ''}, + 'to': [{'name': 'Sam Ortiz', 'email': 'sam.ortiz@northgate.com'}], 'cc': [], 'bcc': [], + 'subject': 'New hires ready to provision', 'body': 'Roster in Workday; matrix in Docs.', + 'snippet': 'Roster in Workday...', 'timestamp': '2026-04-30T07:00:00Z', + 'read': False, 'starred': False, 'important': False, 'labels': [], + 'category': 'primary', 'folder': 'inbox', 'attachments': []}, + ] + _keep_msgs, + 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}], + 'drafts': [], 'settings': {'density': 'default', 'undoSend': 10}, 'today': '2026-04-30', +} + + +# --------------------------------------------------------------------------- +# Slack — #it-onboarding pinned stock-substitution note (lever g/d one hop). +# NOTE (2026-07-12 review #1): slack_mock resolves an author via users[].userId -> fullName +# (else displayName else literal "Unknown User"); the old users only had name/firstName/lastName +# so every message showed "Unknown User". Give every user fullName+displayName. Also add a +# 'general' channel (slack_mock index redirects to /channel/general -> "Channel not found" if +# missing) plus harmless chatter so #it-onboarding looks active and the pinned note sits above +# a real backlog. All filler is pre-seeded in initial_state, so reward's messageId-diff on +# #it-onboarding does NOT count it as the agent's summary post. (Message.jsx byte-identical in +# zihang; setup-side fix, no mock backend change.) +# --------------------------------------------------------------------------- +_PIN_TEXT = ( + ':pushpin: Provision new hires per the "Provisioning Config Matrix" doc (file one IT ticket ' + 'per hire).\n' + f'Stock note this quarter: {SUBSTITUTE_FROM} is OUT OF STOCK — provision the ' + f'{SUBSTITUTE_TO} instead wherever the matrix calls for the {SUBSTITUTE_FROM}. ' + 'Contractors do not receive company provisioning.' +) + + +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', 'Sam', 'Ortiz'), # onboarding coordinator (current user) + _slack_user('user_2', 'Ivy', 'Chen'), # IT lead (posts the pin) + _slack_user('user_3', 'Marcus', 'Bell'), # IT ops + _slack_user('user_4', 'Nina', 'Rao'), # People ops +] + + +def _smsg(mid, sender, content, ts): + return {'messageId': mid, 'senderId': sender, 'content': content, 'timestamp': ts, + 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False} + + +_ITOB_HISTORY = [ + _smsg('msg_pin', 'user_2', _PIN_TEXT, '2026-04-01T09:00:00Z'), + _smsg('msg_o1', 'user_3', 'Provisioning laptops are staged for the new-hire batch starting May 4.', '2026-04-28T10:00:00Z'), + _smsg('msg_o2', 'user_2', 'Reminder: file one IT ticket per hire from the config matrix in Docs.', '2026-04-29T09:30:00Z'), + _smsg('msg_o3', 'user_4', 'HRIS pushed this week\'s roster to Workday — 7 names, one is a contractor.', '2026-04-29T15:00:00Z'), + _smsg('msg_o4', 'user_2', '@Sam can you clear the provisioning tickets today so IT can image the machines?', '2026-04-30T08:15:00Z'), + _smsg('msg_o5', 'user_1', 'On it — going through the roster and the matrix now.', '2026-04-30T08:30:00Z'), +] + +_GENERAL_HISTORY = [ + _smsg('msg_g1', 'user_2', 'Welcome to Northgate :wave:', '2026-04-15T09:00:00Z'), + _smsg('msg_g2', 'user_4', 'All-hands Friday at 10am PT.', '2026-04-27T14:00:00Z'), + _smsg('msg_g3', 'user_3', 'IT help desk hours extended during onboarding week.', '2026-04-29T16:30:00Z'), +] + +_SLACK_STATE = { + 'currentUser': _slack_user('user_1', 'Sam', 'Ortiz'), + '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': 'it_onboarding', 'name': 'it-onboarding', 'description': 'IT onboarding', + 'topic': 'Provisioning', '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, + 'it_onboarding': _ITOB_HISTORY, + }, + 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [], 'notifications': [], +} + + +# --------------------------------------------------------------------------- +# Inject. +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8192', _WORKDAY_STATE), # workday_mock + ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock + ('http://28.7.184.198:8142', _DOCS_STATE), # google_docs_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/hr_it_provisioning_008__long/reward.py b/hr_it_provisioning_008__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..73e1f5e37562474fb33ac237ece41691438017eb --- /dev/null +++ b/hr_it_provisioning_008__long/reward.py @@ -0,0 +1,264 @@ +""" +Reward Script: New-hire provisioning fan-out with cross-source config & stock-substitution +Task ID: hr_it_provisioning_008__long (output/0707 #17, cluster D / onboarding) +Mocks: workday_mock, gmail_mock, google_docs_mock, slack_mock + +Scoring — ALL positive. Every component in [0,1]; weights sum to 1.0. NO penalties, NO gate. + + 0.40 ticket decision-set F1: true={(hire, config-item) pairs for the 5}; pred={items in the + provisioning emails the agent sent}. Ticketing a contractor/keep hire, or a wrong item + (e.g. the stale 14 laptop), = false positive. do-nothing 0. + 0.25 laptop-substitution correctness: frac of Engineer hires whose ticket lists the 16 (not 14) + 0.20 access-group completeness: frac of the 5 whose ticket includes ALL required access groups + 0.10 all-5-ticketed exact-set: the set of hires with a ticket == the 5 + 0.05 slack #it-onboarding summary post + +Answer key: workday.initial_state._task_adapter (item_pairs, ticket_items, config_by_hire, +engineer_hires, substituted_item, skip_names, keep_names, it_mailbox). +""" +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 = { + 'workday': 'http://28.7.184.198:8192', + '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 norm(s): + return (str(s) if s is not None else '').strip().lower() + + +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 _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 _all_gmail(state): + out = [] + for key in ('emails', 'drafts'): + v = state.get(key) + if isinstance(v, list): + out += [m for m in v if isinstance(m, dict)] + return out + + +def _email_text(m): + return f"{m.get('subject', '')} {m.get('body', '')} {m.get('snippet', '')}" + + +def _recipients(m): + out = set() + for r in (m.get('to') or []): + if isinstance(r, dict) and r.get('email'): + out.add(norm(r.get('email'))) + elif isinstance(r, str): + out.add(norm(r)) + return out + + +# =========================================================================== +def reward(go): + W_F1 = 0.40 + W_SUB = 0.25 + W_ACCESS = 0.20 + W_EXACT = 0.10 + W_POST = 0.05 + + # ---- 1) answer key ---- + wd = go('workday') + wd_init = wd.get('initial_state', {}) if isinstance(wd.get('initial_state'), dict) else {} + adapter = wd_init.get('_task_adapter', {}) if isinstance(wd_init.get('_task_adapter'), dict) else {} + item_pairs = adapter.get('item_pairs') if isinstance(adapter.get('item_pairs'), list) else [] + config_by_hire = adapter.get('config_by_hire') if isinstance(adapter.get('config_by_hire'), dict) else {} + engineer_hires = list(adapter.get('engineer_hires') or []) + substituted = adapter.get('substituted_item') if isinstance(adapter.get('substituted_item'), dict) else {} + it_mailbox = norm(adapter.get('it_mailbox')) + skip_names = [norm(n) for n in (adapter.get('skip_names') or [])] + keep_names = [norm(n) for n in (adapter.get('keep_names') or [])] + provision_names = list(config_by_hire.keys()) + n_prov = len(provision_names) + if not item_pairs or n_prov == 0: + print('DEBUG_WD_PROVISION fatal=no_answer_key total=0.0') + return 0.0 + + # ---- 2) gmail: NEW provisioning ticket emails (to IT) ---- + gm = go('gmail') + gm_init = gm.get('initial_state', {}) if isinstance(gm.get('initial_state'), dict) else {} + gm_cur = gm.get('current_state', {}) if isinstance(gm.get('current_state'), dict) else {} + init_ids = {m.get('id') for m in _all_gmail(gm_init)} + new_it_emails = [m for m in _all_gmail(gm_cur) + if m.get('id') not in init_ids and it_mailbox in _recipients(m)] + + all_hire_names = [norm(n) for n in provision_names] + skip_names + keep_names + + def _hire_in(m): + txt = norm(_email_text(m)) + return next((n for n in all_hire_names if n and n in txt), None) + + # ticketed hire set (by name) + per-hire item text + ticketed = {} # hire_name_lower -> concatenated ticket text + for m in new_it_emails: + hn = _hire_in(m) + if not hn: + continue + ticketed.setdefault(hn, '') + ticketed[hn] += ' ' + norm(_email_text(m)) + + # ---- 3) ticket F1 over (hire, item) pairs ---- + true_pairs = {(norm(h), norm(it)) for (h, it) in item_pairs} + pred_pairs = set() + for hn, text in ticketed.items(): + # for a ticketed hire, credit each required item string found in the ticket text; + # also any item from OTHER hires' configs that appears counts as that hire's pred + # (kept simple: check the union of all known items). + for (h, it) in item_pairs: + if norm(it) in text: + pred_pairs.add((hn, norm(it))) + # a wrong laptop (the stale 14) for an engineer registers as a false pred pair + if substituted and norm(substituted.get('from')) in text: + pred_pairs.add((hn, norm(substituted.get('from')))) + ticket_f1 = f1(true_pairs, pred_pairs) + s_f1 = W_F1 * ticket_f1 + + # ---- 4) laptop-substitution correctness (Engineers -> the 16, not the 14) ---- + sub_from = norm(substituted.get('from')) + sub_to = norm(substituted.get('to')) + sub_ok = 0 + for nm in engineer_hires: + text = ticketed.get(norm(nm), '') + if sub_to in text and sub_from not in text: + sub_ok += 1 + sub_score = frac(sub_ok, len(engineer_hires)) if engineer_hires else 0.0 + s_sub = W_SUB * sub_score + + # ---- 5) access-group completeness (all required access groups present) ---- + access_ok = 0 + for nm in provision_names: + text = ticketed.get(norm(nm), '') + req_access = [norm(a) for a in config_by_hire[nm].get('access', [])] + if req_access and all(a in text for a in req_access): + access_ok += 1 + access_score = frac(access_ok, n_prov) + s_access = W_ACCESS * access_score + + # ---- 6) exact-set: ticketed hire set == the 5 provision hires ---- + exact_ok = (set(ticketed.keys()) == {norm(n) for n in provision_names}) + s_exact = W_EXACT * (1.0 if exact_ok else 0.0) + + # ---- 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, 'it-onboarding') if isinstance(m, dict)} + _itob_kw = ('provision', 'onboard', 'hire', 'laptop', 'equipment', 'account', 'stock') + def _is_itob_summary(m): + t = (_msg_text(m) or '').lower() + return any(k in t for k in _itob_kw) + new_msgs = [m for m in _slack_channel_messages(scur, 'it-onboarding') + 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_itob_summary(m) for m in new_msgs) + s_post = W_POST * (1.0 if post_ok else 0.0) + + score = clamp01(s_f1 + s_sub + s_access + s_exact + s_post) + + print( + 'DEBUG_WD_PROVISION ' + f'n_prov={n_prov} ticketed={len(ticketed)} pred_pairs={len(pred_pairs)} ' + f'ticket_f1={round(ticket_f1, 4)} sub_ok={sub_ok}/{len(engineer_hires)} ' + f'access_ok={access_ok}/{n_prov} exact={exact_ok} post={post_ok} ' + f'w_f1={round(s_f1, 4)} w_sub={round(s_sub, 4)} w_access={round(s_access, 4)} ' + f'w_exact={round(s_exact, 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/itops_access_ticket_004/_cua_gym_vm_bridge.sh b/itops_access_ticket_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/itops_access_ticket_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/itops_access_ticket_004/initial_setup.py b/itops_access_ticket_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f347942493b61d7f8fe1fd48e62152b4a07c5db5 --- /dev/null +++ b/itops_access_ticket_004/initial_setup.py @@ -0,0 +1,375 @@ +""" +Initial Setup: prof34_access_ticket_002 +Task: Process two approved access requests (Priya Nair/Tableau, Leo Tran/Salesforce) +across 5 mock apps: slack, jira, google_sheets, google_docs, gmail. +Task ID: itops_access_ticket_004 +Domain: mock_websites +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config: 5 mock URLs from task_config.json context field --- +SLACK_URL = 'http://28.7.184.198:8178' +JIRA_URL = 'http://28.7.184.198:8153' +SHEETS_URL = 'http://28.7.184.198:8145' +DOCS_URL = 'http://28.7.184.198:8142' +GMAIL_URL = 'http://28.7.184.198:8138' + +MOCKS = { + 'slack_mock': SLACK_URL, + 'jira_mock': JIRA_URL, + 'google_sheets_mock': SHEETS_URL, + 'google_docs_mock': DOCS_URL, + 'gmail_mock': GMAIL_URL, +} + +# --- Generate and persist sid --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid={sid}') + +# --------------------------------------------------------------------------- +# SLACK state +# --------------------------------------------------------------------------- +slack_state = { + "currentUser": { + "userId": "user_hd", + "fullName": "IT Help Desk", + "displayName": "IT Help Desk", + "email": "it-helpdesk@northwind.io", + "avatar": "https://picsum.photos/200/200?random=hd", + "title": "Access Request Manager", + "status": "active", + "statusMessage": "Processing access requests", + "statusEmoji": "", + "timeZone": "America/New_York" + }, + "workspace": {"workspaceId": "ws_nw", "workspaceName": "Northwind Corp", "icon": ""}, + "users": [ + {"userId": "user_hd", "fullName": "IT Help Desk", "displayName": "IT Help Desk", + "email": "it-helpdesk@northwind.io", "avatar": "https://picsum.photos/200/200?random=hd", + "title": "Access Request Manager", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_priya", "fullName": "Priya Nair", "displayName": "Priya", + "email": "priya.nair@northwind.io", "avatar": "https://picsum.photos/200/200?random=priya", + "title": "Financial Analyst", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_leo", "fullName": "Leo Tran", "displayName": "Leo", + "email": "leo.tran@northwind.io", "avatar": "https://picsum.photos/200/200?random=leo", + "title": "Account Executive", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_tom", "fullName": "Tom Best", "displayName": "Tom", + "email": "tom.best@northwind.io", "avatar": "https://picsum.photos/200/200?random=tom", + "title": "Engineer", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"} + ], + "channels": [ + {"channelId": "it-access-requests", "name": "it-access-requests", + "description": "Channel for submitting IT access requests", "topic": "Access requests", + "isPrivate": False, "isStarred": False, + "members": ["user_hd", "user_priya", "user_leo", "user_tom"], + "createdBy": "user_hd", "createdAt": "2026-06-01T09:00:00Z", + "pinnedMessages": [], "unreadCount": 3} + ], + "messages": { + "it-access-requests": [ + {"messageId": "msg-req-099", "senderId": "user_tom", + "content": "Access request: App=GitHub, Requester=Tom Best, Manager Approval=PENDING. Awaiting manager sign-off.", + "timestamp": "2026-07-01T08:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg-req-101", "senderId": "user_priya", + "content": "Access request: App=Tableau, Requester=Priya Nair, Manager Approval=Approved by Sara Kim (s.kim@northwind.io). Need analyst access to the Q3 finance dashboards.", + "timestamp": "2026-07-01T09:05:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg-req-102", "senderId": "user_leo", + "content": "Access request: App=Salesforce, Requester=Leo Tran, Manager Approval=Approved by Daniel Okafor (d.okafor@northwind.io). Need edit access to the accounts module for the new sales campaign.", + "timestamp": "2026-07-01T09:20:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False} + ] + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [] +} + +# --------------------------------------------------------------------------- +# JIRA state +# --------------------------------------------------------------------------- +jira_state = { + "currentUser": {"id": "u_hd", "name": "IT Help Desk", "email": "it-helpdesk@northwind.io", "avatar": "https://picsum.photos/100/100?random=hd"}, + "users": [ + {"id": "u_hd", "name": "IT Help Desk", "email": "it-helpdesk@northwind.io", "avatar": "https://picsum.photos/100/100?random=hd"}, + {"id": "u_sara", "name": "Sara Kim", "email": "s.kim@northwind.io", "avatar": "https://picsum.photos/100/100?random=sara"}, + {"id": "u_daniel", "name": "Daniel Okafor", "email": "d.okafor@northwind.io", "avatar": "https://picsum.photos/100/100?random=daniel"} + ], + "projects": [ + {"id": "p_ithd", "key": "ITHD", "name": "IT Help Desk", "leadId": "u_hd", "category": "IT", "icon": "https://picsum.photos/64/64?random=ithd"} + ], + "sprints": [], + "issues": [ + {"id": "i098", "key": "ITHD-098", "projectId": "p_ithd", "summary": "Printer offline on 3rd floor", + "description": "The shared printer on the 3rd floor is offline.", "type": "Bug", "status": "Done", + "priority": "Low", "storyPoints": 1, "reporterId": "u_hd", "assigneeId": "u_hd", "sprintId": None, + "epicId": None, "labels": [], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-06-20T10:00:00.000Z", "updatedAt": "2026-06-21T10:00:00.000Z"}, + {"id": "i100", "key": "ITHD-100", "projectId": "p_ithd", "summary": "VPN access renewal for contractors", + "description": "Contractor VPN credentials need renewal.", "type": "Task", "status": "In Progress", + "priority": "Medium", "storyPoints": 3, "reporterId": "u_hd", "assigneeId": "u_hd", "sprintId": None, + "epicId": None, "labels": [], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-06-28T10:00:00.000Z", "updatedAt": "2026-06-29T10: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": [] +} + +# --------------------------------------------------------------------------- +# GOOGLE SHEETS state +# --------------------------------------------------------------------------- +def cell(value, **style): + c = {"value": value, "formula": str(value)} + if style: + c["style"] = style + return c + +hdr_style = {"bold": True, "bg": "#E8EAED", "align": "center"} +sheets_state = { + "id": "wb_acc_01", + "title": "Access Audit Log", + "activeSheetId": "sh_acc_01", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [ + { + "id": "sh_acc_01", + "name": "Access Log", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": None, + "isHidden": False, + "columnWidths": {"0": 160, "1": 120, "2": 140, "3": 200, "4": 120, "5": 120, "6": 140, "7": 110, "8": 140, "9": 120}, + "data": { + "A1": cell("Request ID", **hdr_style), + "B1": cell("Date", **hdr_style), + "C1": cell("Requester", **hdr_style), + "D1": cell("Email", **hdr_style), + "E1": cell("App", **hdr_style), + "F1": cell("Access Level", **hdr_style), + "G1": cell("Manager", **hdr_style), + "H1": cell("Status", **hdr_style), + "I1": cell("Stage", **hdr_style), + "J1": cell("Jira Ticket", **hdr_style), + # Row 2 + "A2": cell("ACC-2026-0628-001"), "B2": cell("2026-06-28"), "C2": cell("Liam Wong"), + "D2": cell("liam.wong@northwind.io"), "E2": cell("Asana"), "F2": cell("Read-only"), + "G2": cell("Sara Kim"), "H2": cell("Approved"), "I2": cell("Provisioned"), "J2": cell(""), + # Row 3 + "A3": cell("ACC-2026-0629-002"), "B3": cell("2026-06-29"), "C3": cell("Nina Patel"), + "D3": cell("nina.patel@northwind.io"), "E3": cell("Google Sheets"), "F3": cell("Edit"), + "G3": cell("Daniel Okafor"), "H3": cell("Approved"), "I3": cell("Provisioned"), "J3": cell(""), + # Row 4 + "A4": cell("ACC-2026-0630-003"), "B4": cell("2026-06-30"), "C4": cell("Omar Said"), + "D4": cell("omar.said@northwind.io"), "E4": cell("GitHub"), "F4": cell("Read-only"), + "G4": cell("Sara Kim"), "H4": cell("Pending"), "I4": cell("Awaiting"), "J4": cell(""), + # Row 5 + "A5": cell("ACC-2026-0701-001"), "B5": cell("2026-07-01"), "C5": cell("Maya Chen"), + "D5": cell("maya.chen@northwind.io"), "E5": cell("Salesforce"), "F5": cell("Read-only"), + "G5": cell("Daniel Okafor"), "H5": cell("Approved"), "I5": cell("Logged"), "J5": cell("") + } + } + ] +} + +# --------------------------------------------------------------------------- +# GOOGLE DOCS state +# --------------------------------------------------------------------------- +docs_state = { + "currentUser": { + "id": "user_hd", + "name": "IT Help Desk", + "email": "it-helpdesk@northwind.io", + "avatar": "https://picsum.photos/100/100?random=hd" + }, + "users": [ + {"id": "user_hd", "name": "IT Help Desk", "email": "it-helpdesk@northwind.io", "avatar": "https://picsum.photos/100/100?random=hd"} + ], + "documents": { + "doc_acc_01": { + "id": "doc_acc_01", + "title": "Access Request Notes", + "content": ( + "

Access Request Notes

" + "

2026-06-30

" + "
  • Processed 1 access request (Asana/Liam Wong). Manager-approved. Logged in audit tracker.
" + ), + "ownerId": "user_hd", + "starred": False, + "created": "2026-06-15T10:00:00Z", + "updated": "2026-06-30T16: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": "" + } +} + +# --------------------------------------------------------------------------- +# GMAIL state +# --------------------------------------------------------------------------- +gmail_state = { + "user": {"userId": "u_hd", "username": "IT Help Desk", "email": "it-helpdesk@northwind.io", "avatar": "https://picsum.photos/100/100?random=hd"}, + "emails": [ + { + "id": "email_in_1", + "threadId": "thread_in_1", + "from": {"name": "Priya Nair", "email": "priya.nair@northwind.io"}, + "to": [{"name": "IT Help Desk", "email": "it-helpdesk@northwind.io"}], + "subject": "Access request: Tableau analyst access", + "body": "Hi, I need analyst access to the Q3 finance dashboards in Tableau. My manager Sara Kim has approved.", + "timestamp": "2026-07-01T09:05:00Z", + "read": False, + "starred": False, + "important": True, + "labels": ["l1"], + "category": "primary", + "folder": "inbox", + "attachments": [] + }, + { + "id": "email_in_2", + "threadId": "thread_in_2", + "from": {"name": "Leo Tran", "email": "leo.tran@northwind.io"}, + "to": [{"name": "IT Help Desk", "email": "it-helpdesk@northwind.io"}], + "subject": "Access request: Salesforce edit access", + "body": "Hi, I need edit access to the accounts module in Salesforce for the new sales campaign. My manager Daniel Okafor has approved.", + "timestamp": "2026-07-01T09:20:00Z", + "read": False, + "starred": False, + "important": True, + "labels": ["l1"], + "category": "primary", + "folder": "inbox", + "attachments": [] + } + ], + "labels": [ + {"id": "l1", "name": "Work", "color": "#ef4444"}, + {"id": "l2", "name": "Personal", "color": "#3b82f6"}, + {"id": "l3", "name": "Travel", "color": "#22c55e"}, + {"id": "l4", "name": "Finance", "color": "#eab308"} + ], + "drafts": [] +} + +# --- Inject state into each mock --- +states = { + 'slack_mock': slack_state, + 'jira_mock': jira_state, + 'google_sheets_mock': sheets_state, + 'google_docs_mock': docs_state, + 'gmail_mock': gmail_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'Injected state for {name}: HTTP {resp.status_code}') + +# --- Verify --- +for name, url in MOCKS.items(): + 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('Verified: all 5 mocks have initial_state set') + +# --- Launch Chrome for EVERY mock --- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + +for name, url in MOCKS.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.5) + +# --- Wait until all mocks serve injected state AND fully render --- +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + raise RuntimeError(f'Mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 5s') + _t.sleep(5.0) + return + with sync_playwright() as p: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', + timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 100", + timeout=int(render_timeout * 1000)) + html = page.content() + if len(html) < 2000: + raise RuntimeError( + f'[{name}] rendered DOM too small ({len(html)} bytes) — blank/stuck loading') + print(f'[{name}] rendered OK ({len(html)} bytes)') + finally: + page.close() + finally: + browser.close() + +wait_for_mocks_loaded(MOCKS, sid) +print(f'GUI_READY: all {len(MOCKS)} mocks launched and verified (sid={sid})') diff --git a/itops_access_ticket_004/reward.py b/itops_access_ticket_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d899dc3bfd6573fce420bbf84d6edd390c121a --- /dev/null +++ b/itops_access_ticket_004/reward.py @@ -0,0 +1,281 @@ +""" +Reward Script: Access Request Processing (prof34_access_ticket_002) +Task ID: itops_access_ticket_004 +Domain: mock_websites +Mocks: slack, jira, google_sheets, google_docs, gmail +Scoring: + - Jira: 2 new ITHD tickets (ITHD-101 Priya/Tableau/Medium, ITHD-102 Leo/Salesforce/High) -> 0.40 + - Sheets: Access Log rows 6 & 7 populated with the two new audit rows -> 0.25 + - Docs: 'Access Request Notes' has a '2026-07-01' heading + bullet mentioning ITHD-101/102 -> 0.15 + - Gmail: 2 sent confirmation emails (to priya.nair / leo.tran, exact subjects) -> 0.20 + - Slack: read-only gate (0-weight) -> no scoring, just a sanity check +All checks are exact/contains/count checks, so 100% programmatic (0% LLM judge). +""" +import json +import sys +import urllib.request + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + SID = f.read().strip() + if not SID: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +# Mock base URLs (shared host, distinct sid per environment) +BASE = { + 'jira': 'http://28.7.184.198:8153', + 'sheets': 'http://28.7.184.198:8145', + 'docs': 'http://28.7.184.198:8142', + 'gmail': 'http://28.7.184.198:8138', + 'slack': 'http://28.7.184.198:8178', +} + +# --- Fetch state from a mock --- +def fetch(mock): + try: + with urllib.request.urlopen(f'{BASE[mock]}/go?sid={SID}', timeout=15) as r: + return json.load(r) + except Exception as e: + print(f'CRITICAL: Cannot fetch {mock} state: {e}') + return None + + +# --- Helpers --------------------------------------------------------------- + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# --- Per-component checks (one function per sub-objective) ----------------- + +def check_component_1(jira): + """Exactly 2 new ITHD Access Request tickets created: ITHD-101 (Priya Nair / + Tableau / Medium) and ITHD-102 (Leo Tran / Salesforce / High), both type + 'Access Request', assignee 'it-helpdesk', and NO ticket for the distractor + (Tom Best). Pass condition: current_state has exactly ITHD-101 & ITHD-102 as + new (not in initial_state) Access Request issues, and no 'PENDING'/'Tom Best' ticket. + """ + if not jira: + return False, 0.0, 'jira state unavailable' + init = jira.get('initial_state', {}) or {} + cur = jira.get('current_state', {}) or {} + init_issues = {i.get('key') for i in (init.get('issues') or [])} + cur_issues = cur.get('issues') or [] + cur_keys = {i.get('key') for i in cur_issues} + + # New issues = present in current but not in initial + new_keys = sorted(cur_keys - init_issues) + if 'ITHD-101' not in new_keys or 'ITHD-102' not in new_keys: + return False, 0.0, f'expected new ITHD-101 & ITHD-102, found new: {new_keys}' + + by_key = {i.get('key'): i for i in cur_issues} + i101 = by_key.get('ITHD-101') + i102 = by_key.get('ITHD-102') + + def ok(issue, expected_summary_sub, app, priority): + if issue is None: + return False + if issue.get('type') != 'Access Request': + return False + if issue.get('priority') != priority: + return False + # Assignee must be the IT Help Desk user. The user id is 'u_hd' + # (name 'IT Help Desk', email 'it-helpdesk@northwind.io'); accept either + # the id or the literal 'it-helpdesk' for robustness. + aid = issue.get('assigneeId') or issue.get('assignee') + if aid not in ('u_hd', 'it-helpdesk'): + return False + s = (issue.get('summary') or '') + if app not in s: + return False + return True + + c101 = ok(i101, 'Tableau', 'Tableau', 'Medium') + c102 = ok(i102, 'Salesforce', 'Salesforce', 'High') + if not (c101 and c102): + return False, 0.0, f'ITHD-101 ok={c101}, ITHD-102 ok={c102}' + + # Guard: no distractor ticket (Tom Best / PENDING) + for issue in cur_issues: + s = (issue.get('summary') or '') + ' ' + (issue.get('description') or '') + if 'Tom Best' in s and issue.get('key') not in ('ITHD-101', 'ITHD-102'): + return False, 0.0, 'distractor ticket (Tom Best) present' + + return True, 0.4, 'ITHD-101 (Tableau/Medium) & ITHD-102 (Salesforce/High) present, no distractor' + + +def check_component_2(sheets): + """Access Log sheet rows 6 and 7 populated with the exact task values. + Row 6: A=ACC-2026-0701-101, C=Priya Nair, E=Tableau, F=Analyst, G=Sara Kim, + H=Approved, I=Ticket Created, J=ITHD-101. Row 7: A=ACC-2026-0701-102, + C=Leo Tran, E=Salesforce, F=Edit, G=Daniel Okafor, H=Approved, I=Ticket Created, + J=ITHD-102. Pass condition: all 20 cells match; rows 2-5 untouched (not checked + for scoring, only rows 6/7 are the task-introduced change). + """ + if not sheets: + return False, 0.0, 'sheets state unavailable' + cur = sheets.get('current_state', {}) or {} + sh_list = cur.get('sheets') or [] + if not sh_list: + return False, 0.0, 'no sheets in current_state' + data = sh_list[0].get('data') or {} + + def cell(addr): + c = data.get(addr) + if not c: + return None + return c.get('value') + + expected = { + 'A6': 'ACC-2026-0701-101', 'B6': '2026-07-01', 'C6': 'Priya Nair', + 'D6': 'priya.nair@northwind.io', 'E6': 'Tableau', 'F6': 'Analyst', + 'G6': 'Sara Kim', 'H6': 'Approved', 'I6': 'Ticket Created', 'J6': 'ITHD-101', + 'A7': 'ACC-2026-0701-102', 'B7': '2026-07-01', 'C7': 'Leo Tran', + 'D7': 'leo.tran@northwind.io', 'E7': 'Salesforce', 'F7': 'Edit', + 'G7': 'Daniel Okafor', 'H7': 'Approved', 'I7': 'Ticket Created', 'J7': 'ITHD-102', + } + mismatches = [] + for addr, val in expected.items(): + got = cell(addr) + if str(got) != str(val): + mismatches.append(f'{addr}: expected {val!r} got {got!r}') + if mismatches: + return False, 0.0, '; '.join(mismatches[:4]) + return True, 0.25, 'rows 6 & 7 match ground truth exactly' + + +def check_component_3(docs): + """'Access Request Notes' doc updated with a '2026-07-01' heading and a bullet + mentioning both ITHD-101 and ITHD-102. Pass condition: a document titled + 'Access Request Notes' (doc_acc_01) exists whose content contains '2026-07-01', + 'ITHD-101' and 'ITHD-102'. + """ + if not docs: + return False, 0.0, 'docs state unavailable' + cur = docs.get('current_state', {}) or {} + doc_map = cur.get('documents') or {} + # documents may be a list or a dict + if isinstance(doc_map, list): + docs_list = doc_map + else: + docs_list = list(doc_map.values()) + target = None + for doc in docs_list: + if isinstance(doc, dict) and (doc.get('title') == 'Access Request Notes' + or doc.get('id') == 'doc_acc_01'): + target = doc + break + if target is None: + return False, 0.0, 'no "Access Request Notes" document found' + txt = json.dumps(target) + has_date = '2026-07-01' in txt + has_101 = 'ITHD-101' in txt + has_102 = 'ITHD-102' in txt + if has_date and has_101 and has_102: + return True, 0.15, 'Access Request Notes has 2026-07-01 heading + ITHD-101/102 bullet' + return False, 0.0, f'date={has_date}, ITHD-101={has_101}, ITHD-102={has_102}' + + +def check_component_4(gmail): + """Exactly 2 confirmation emails sent: to priya.nair@northwind.io with subject + 'Access request received: Tableau (ITHD-101)' and to leo.tran@northwind.io with + subject 'Access request received: Salesforce (ITHD-102)'. Pass condition: among + current_state emails, exactly 2 have a subject starting with 'Access request + received:' and are addressed to the two requesters (no email to the distractor Tom Best). + """ + if not gmail: + return False, 0.0, 'gmail state unavailable' + cur = gmail.get('current_state', {}) or {} + emails = cur.get('emails') or [] + + def to_emails(e): + tos = e.get('to') or [] + if isinstance(tos, list): + return [t.get('email') if isinstance(t, dict) else t for t in tos] + return [] + + confirmations = [] + for e in emails: + subj = (e.get('subject') or '') + if subj.startswith('Access request received:'): + recips = to_emails(e) + confirmations.append((subj, recips)) + + # Need exactly 2: one to priya, one to leo + priya_ok = any('priya.nair@northwind.io' in recips + and 'Tableau (ITHD-101)' in subj for subj, recips in confirmations) + leo_ok = any('leo.tran@northwind.io' in recips + and 'Salesforce (ITHD-102)' in subj for subj, recips in confirmations) + if priya_ok and leo_ok and len(confirmations) == 2: + return True, 0.2, '2 confirmation emails sent to priya.nair & leo.tran with exact subjects' + return False, 0.0, f'priya_ok={priya_ok}, leo_ok={leo_ok}, count={len(confirmations)}' + + +def check_component_5_slack_gate(slack): + """Slack is read-only — the task requires reading the two request messages but + making no changes. Pass condition (0-weight gate): the #it-access-requests channel + still contains msg-req-101 and msg-req-102 (i.e. the source messages are intact). + This component awards no points; it only confirms the pre-task state is intact. + """ + if not slack: + return False, 0.0, 'slack state unavailable (gate only)' + cur = slack.get('current_state', {}) or {} + # Look for the two request messages anywhere in channels/messages + txt = json.dumps(cur) + has_101 = 'msg-req-101' in txt or 'Tableau' in txt + has_102 = 'msg-req-102' in txt or 'Salesforce' in txt + if has_101 and has_102: + return True, 0.0, 'source request messages intact (read-only gate)' + return False, 0.0, 'source request messages missing' + + +def verify_task(): + """Verify task completion with progressive scoring. Returns float 0.0-1.0.""" + states = {m: fetch(m) for m in BASE} + + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'Jira: 2 new ITHD tickets', 0.4, check_component_1, (states['jira'],)), + (2, 'Sheets: Access Log rows 6 & 7', 0.25, check_component_2, (states['sheets'],)), + (3, 'Docs: 2026-07-01 heading + bullet', 0.15, check_component_3, (states['docs'],)), + (4, 'Gmail: 2 sent confirmation emails', 0.2, check_component_4, (states['gmail'],)), + ]: + _, score, _ = _run_component(idx, name, weight, fn, args) + total_score += score + + # Zero-weight Slack gate (read-only) — does not affect score + _run_component(5, 'Slack: read-only gate', 0.0, check_component_5_slack_gate, + (states['slack'],)) + + 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_ticket_004/reward_label.json b/itops_access_ticket_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..df1a16ac7fe6411750842ee180dfdcab2cf02ab2 --- /dev/null +++ b/itops_access_ticket_004/reward_label.json @@ -0,0 +1,72 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof34_access_ticket_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:31:42", + "label": { + "task_id": "itops_access_ticket_004", + "domain": "mock_websites", + "summary": "验证用户在多个mock服务中完成访问请求处理任务:创建Jira工单、更新Sheets访问日志、记录Docs笔记、发送Gmail确认邮件,并检查Slack只读状态", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "jira_mock", + "google_sheets_mock", + "google_docs_mock", + "gmail_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1: Jira: 2 new ITHD tickets", + "weight": 0.4, + "description": "检查Jira中是否创建了2个新的ITHD访问请求工单ITHD-101和ITHD-102,且没有Tom Best的干扰工单", + "check_logic": "对比initial_state和current_state的issues,确认新增ITHD-101(Tableau/Medium/Access Request/指派给u_hd或it-helpdesk)和ITHD-102(Salesforce/High/Access Request/指派给u_hd或it-helpdesk),并检查不存在包含'Tom Best'的其他工单", + "pass_condition": "current_state中恰好新增ITHD-101和ITHD-102两个工单,类型为Access Request,优先级分别为Medium和High,应用名称分别在summary中,指派给IT Help Desk,且不存在Tom Best的干扰工单" + }, + { + "name": "Component 2: Sheets: Access Log rows 6 & 7", + "weight": 0.25, + "description": "检查Google Sheets的Access Log工作表第6行和第7行是否精确填充了指定的20个单元格值", + "check_logic": "获取第一个sheet的data,逐一比对A6:J6和A7:J7共20个单元格的字符串值是否与预期完全一致", + "pass_condition": "A6-J6和A7-J7所有20个单元格的值与预期完全匹配,包括请求ID、日期、姓名、邮箱、应用、权限、审批人、状态、处理结果和工单号" + }, + { + "name": "Component 3: Docs: 2026-07-01 heading + bullet", + "weight": 0.15, + "description": "检查Google Docs中'Access Request Notes'文档是否包含2026-07-01日期标题和ITHD-101/102的提及", + "check_logic": "在current_state的documents中查找标题为'Access Request Notes'或id为'doc_acc_01'的文档,将其整个内容转为JSON字符串后检查是否包含'2026-07-01'、'ITHD-101'和'ITHD-102'", + "pass_condition": "存在目标文档且其内容中同时包含'2026-07-01'、'ITHD-101'和'ITHD-102'" + }, + { + "name": "Component 4: Gmail: 2 sent confirmation emails", + "weight": 0.2, + "description": "检查Gmail是否恰好发送了2封确认邮件给两位请求者,且主题符合要求", + "check_logic": "遍历current_state的emails,筛选subject以'Access request received:'开头的邮件,检查是否恰好有2封,其中一封发给priya.nair@northwind.io且主题包含'Tableau (ITHD-101)',另一封发给leo.tran@northwind.io且主题包含'Salesforce (ITHD-102)'", + "pass_condition": "恰好存在2封确认邮件,分别发送给priya.nair和leo.tran,主题分别包含指定的Tableau和Salesforce内容" + }, + { + "name": "Component 5: Slack: read-only gate", + "weight": 0.0, + "description": "Slack只读检查门控,确认源请求消息未被修改", + "check_logic": "将slack的current_state转为JSON字符串,检查是否包含'msg-req-101'或'Tableau'以及'msg-req-102'或'Salesforce'", + "pass_condition": "Slack状态中源请求消息仍然完整存在(该组件不影响总分)" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件得分直接相加,最终结果通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数", + "failure_modes": [ + "读取/tmp/task_web_sid失败或SID为空时,打印CRITICAL并直接退出,REWARD为0.0", + "获取任一mock服务状态失败时,打印CRITICAL,对应组件检查返回False/0.0", + "Jira中未找到ITHD-101或ITHD-102、工单属性不匹配、或存在Tom Best干扰工单时,Component 1得0分", + "Sheets中20个单元格任一不匹配时,Component 2得0分", + "Docs中未找到目标文档或缺少任一关键词时,Component 3得0分", + "Gmail中确认邮件数量不为2、收件人或主题不匹配时,Component 4得0分", + "组件检查函数抛出异常时,捕获为FAIL,得0分" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,然后依次从jira、sheets、docs、gmail、slack五个mock服务拉取current_state。接着按顺序执行4个计分组件和1个零权重的Slack门控组件:1)检查Jira新增工单;2)检查Sheets单元格精确值;3)检查Docs文档内容包含关键词;4)检查Gmail确认邮件数量和主题;5)Slack只读sanity check。每个组件通过_run_component执行,输出PASS/FAIL和COMPONENT结构化日志。各计分组件的得分累加得到total_score,最终通过min(total_score, 1.0)限制上限并四舍五入到4位小数输出REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: prof34_access_ticket_002\n - Domain: mock_websites\n - Mocks: slack, jira, google_sheets, google_docs, gmail\n\n2. **数据源**:\n - 从 `/tmp/task_web_sid` 读取 SID\n - 从多个 mock 服务获取状态:\n - jira: http://28.7.186.212:8173\n - sheets: http://28.7.186.212:8165\n - docs: http://28.7.186.212:8162\n - gmail: http://28.7.186.212:8158\n - slack: http://28.7.186.212:8198\n\n3. **评分组件**:\n - Component 1 (Jira): weight 0.4\n - 检查是否创建了 2 个新的 ITHD 工单:ITHD-101 (Priya Nair/Tableau/Medium) 和 ITHD-102 (Leo Tran/Salesforce/High)\n - 类型必须是 'Access Request'\n - 指派给 'u_hd' 或 'it-helpdesk'\n - 不能有 Tom Best 的干扰工单\n - Component 2 (Sheets): weight 0.25\n - 检查 Access Log 的第 6 和第 7 行是否填充了正确的值\n - 精确匹配 20 个单元格\n - Component 3 (Docs): weight 0.15\n - 检查 'Access Request Notes' 文档是否包含 '2026-07-01'、'ITHD-101' 和 'ITHD-102'\n - Component 4 (Gmail): weight 0.2\n - 检查是否发送了 2 封确认邮件\n - 一封给 priya.nair@northwind.io,主题包含 'Access request received: Tableau (ITHD-101)'\n - 一封给 leo.tran@northwind.io,主题包含 'Access request received: Salesforce (ITHD-102)'\n - 确认邮件总数必须恰好为 2\n - Component 5 (Slack): weight 0.0\n - 只读检查,确认源消息仍然存在\n - 不影响总分\n\n4. **分数汇总**:\n - 各组件分数相加\n - 最终分数 = min(total_score, 1.0),保留 4 位小数\n\n5. **失败模式**:\n - 读取 /tmp/task_web_sid 失败或为空 -> 打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 获取 mock 状态失败 -> 打印 CRITICAL,返回 None,组件检查会失败\n - 各组件检查失败 -> 该组件得 0 分\n - 组件函数异常 -> 捕获异常,passed=False, score=0.0\n\n6. **is_placeholder**:\n - 不是占位脚本,有完整的检查逻辑\n\n7. **confidence**:\n - 1.0,因为代码逻辑清晰完整\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"prof34_access_ticket_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证用户在多个mock服务中完成访问请求处理任务:创建Jira工单、更新Sheets访问日志、记录Docs笔记、发送Gmail确认邮件,并检查Slack只读状态\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"jira_mock\", \"google_sheets_mock\", \"google_docs_mock\", \"gmail_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1: Jira: 2 new ITHD tickets\",\n \"weight\": 0.4,\n \"description\": \"检查Jira中是否创建了2个新的ITHD访问请求工单ITHD-101和ITHD-102,且没有Tom Best的干扰工单\",\n \"check_logic\": \"对比initial_state和current_state的issues,确认新增ITHD-101(Tableau/Medium/Access Request/指派给u_hd或it-helpdesk)和ITHD-102(Salesforce/High/Access Request/指派给u_hd或it-helpdesk),并检查不存在包含'Tom Best'的其他工单\",\n \"pass_condition\": \"current_state中恰好新增ITHD-101和ITHD-102两个工单,类型为Access Request,优先级分别为Medium和High,应用名称分别在summary中,指派给IT Help Desk,且不存在Tom Best的干扰工单\"\n },\n {\n \"name\": \"Component 2: Sheets: Access Log rows 6 & 7\",\n \"weight\": 0.25,\n \"description\": \"检查Google Sheets的Access Log工作表第6行和第7行是否精确填充了指定的20个单元格值\",\n \"check_logic\": \"获取第一个sheet的data,逐一比对A6:J6和A7:J7共20个单元格的字符串值是否与预期完全一致\",\n \"pass_condition\": \"A6-J6和A7-J7所有20个单元格的值与预期完全匹配,包括请求ID、日期、姓名、邮箱、应用、权限、审批人、状态、处理结果和工单号\"\n },\n {\n \"name\": \"Component 3: Docs: 2026-07-01 heading + bullet\",\n \"weight\": 0.15,\n \"description\": \"检查Google Docs中'Access Request Notes'文档是否包含2026-07-01日期标题和ITHD-101/102的提及\",\n \"check_logic\": \"在current_state的documents中查找标题为'Access Request Notes'或id为'doc_acc_01'的文档,将其整个内容转为JSON字符串后检查是否包含'2026-07-01'、'ITHD-101'和'ITHD-102'\",\n \"pass_condition\": \"存在目标文档且其内容中同时包含'2026-07-01'、'ITHD-101'和'ITHD-102'\"\n },\n {\n \"name\": \"Component 4: Gmail: 2 sent confirmation emails\",\n \"weight\": 0.2,\n \"description\": \"检查Gmail是否恰好发送了2封确认邮件给两位请求者,且主题符合要求\",\n \"check_logic\": \"遍历current_state的emails,筛选subject以'Access request received:'开头的邮件,检查是否恰好有2封,其中一封发给priya.nair@northwind.io且主题包含'Tableau (ITHD-101)',另一封发给leo.tran@northwind.io且主题包含'Salesforce (ITHD-102)'\",\n \"pass_condition\": \"恰好存在2封确认邮件,分别发送给priya.nair和leo.tran,主题分别包含指定的Tableau和Salesforce内容\"\n },\n {\n \"name\": \"Component 5: Slack: read-only gate\",\n \"weight\": 0.0,\n \"description\": \"Slack只读检查门控,确认源请求消息未被修改\",\n \"check_logic\": \"将slack的current_state转为JSON字符串,检查是否包含'msg-req-101'或'Tableau'以及'msg-req-102'或'Salesforce'\",\n \"pass_condition\": \"Slack状态中源请求消息仍然完整存在(该组件不影响总分)\"\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并直接退出,REWARD为0.0\",\n \"获取任一mock服务状态失败时,打印CRITICAL,对应组件检查返回False/0.0\",\n \"Jira中未找到ITHD-101或ITHD-102、工单属性不匹配、或存在Tom Best干扰工单时,Component 1得0分\",\n \"Sheets中20个单元格任一不匹配时,Component 2得0分\",\n \"Docs中未找到目标文档或缺少任一关键词时,Component 3得0分\",\n \"Gmail中确认邮件数量不为2、收件人或主题不匹配时,Component 4得0分\",\n \"组件检查函数抛出异常时,捕获为FAIL,得0分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID,然后并行(字典推导)从jira、sheets、docs、gmail、slack五个mock服务拉取current_state。接着按顺序执行4个计分组件和1个零权重的Slack门控组件:1)检查Jira新增工单;2)检查Sheets单元格精确值;3)检查Docs文档内容包含关键词;4)检查Gmail确认邮件数量和主题;5)Slack只读 sanity check。每个组件通过_run_component执行,输出PASS/FAIL和COMPONENT结构化日志。各计分组件的得分累加得到total_score,最终通过min(total_score, 1.0)限制上限并四舍五入到4位小数输出REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查是否符合要求:\n- 只输出 JSON 对象,没有 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,task_id、domain、字段名保留原样\n- is_placeholder 为 false\n- weight 填写代码中显式给出的分值\n- 包含所有要求的字段\n\n看起来没问题。 {\"task_id\":\"prof34_access_ticket_002\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在多个mock服务中完成访问请求处理任务:创建Jira工单、更新Sheets访问日志、记录Docs笔记、发送Gmail确认邮件,并检查Slack只读状态\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"jira_mock\",\"google_sheets_mock\",\"google_docs_mock\",\"gmail_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 1: Jira: 2 new ITHD tickets\",\"weight\":0.4,\"description\":\"检查Jira中是否创建了2个新的ITHD访问请求工单ITHD-101和ITHD-102,且没有Tom Best的干扰工单\",\"check_logic\":\"对比initial_state和current_state的issues,确认新增ITHD-101(Tableau/Medium/Access Request/指派给u_hd或it-helpdesk)和ITHD-102(Salesforce/High/Access Request/指派给u_hd或it-helpdesk),并检查不存在包含'Tom Best'的其他工单\",\"pass_condition\":\"current_state中恰好新增ITHD-101和ITHD-102两个工单,类型为Access Request,优先级分别为Medium和High,应用名称分别在summary中,指派给IT Help Desk,且不存在Tom Best的干扰工单\"},{\"name\":\"Component 2: Sheets: Access Log rows 6 & 7\",\"weight\":0.25,\"description\":\"检查Google Sheets的Access Log工作表第6行和第7行是否精确填充了指定的20个单元格值\",\"check_logic\":\"获取第一个sheet的data,逐一比对A6:J6和A7:J7共20个单元格的字符串值是否与预期完全一致\",\"pass_condition\":\"A6-J6和A7-J7所有20个单元格的值与预期完全匹配,包括请求ID、日期、姓名、邮箱、应用、权限、审批人、状态、处理结果和工单号\"},{\"name\":\"Component 3: Docs: 2026-07-01 heading + bullet\",\"weight\":0.15,\"description\":\"检查Google Docs中'Access Request Notes'文档是否包含2026-07-01日期标题和ITHD-101/102的提及\",\"check_logic\":\"在current_state的documents中查找标题为'Access Request Notes'或id为'doc_acc_01'的文档,将其整个内容转为JSON字符串后检查是否包含'2026-07-01'、'ITHD-101'和'ITHD-102'\",\"pass_condition\":\"存在目标文档且其内容中同时包含'2026-07-01'、'ITHD-101'和'ITHD-102'\"},{\"name\":\"Component 4: Gmail: 2 sent confirmation emails\",\"weight\":0.2,\"description\":\"检查Gmail是否恰好发送了2封确认邮件给两位请求者,且主题符合要求\",\"check_logic\":\"遍历current_state的emails,筛选subject以'Access request received:'开头的邮件,检查是否恰好有2封,其中一封发给priya.nair@northwind.io且主题包含'Tableau (ITHD-101)',另一封发给leo.tran@northwind.io且主题包含'Salesforce (ITHD-102)'\",\"pass_condition\":\"恰好存在2封确认邮件,分别发送给priya.nair和leo.tran,主题分别包含指定的Tableau和Salesforce内容\"},{\"name\":\"Component 5: Slack: read-only gate\",\"weight\":0.0,\"description\":\"Slack只读检查门控,确认源请求消息未被修改\",\"check_logic\":\"将slack的current_state转为JSON字符串,检查是否包含'msg-req-101'或'Tableau'以及'msg-req-102'或'Salesforce'\",\"pass_condition\":\"Slack状态中源请求消息仍然完整存在(该组件不影响总分)\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件得分直接相加,最终结果通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或SID为空时,打印CRITICAL并直接退出,REWARD为0.0\",\"获取任一mock服务状态失败时,打印CRITICAL,对应组件检查返回False/0.0\",\"Jira中未找到ITHD-101或ITHD-102、工单属性不匹配、或存在Tom Best干扰工单时,Component 1得0分\",\"Sheets中20个单元格任一不匹配时,Component 2得0分\",\"Docs中未找到目标文档或缺少任一关键词时,Component 3得0分\",\"Gmail中确认邮件数量不为2、收件人或主题不匹配时,Component 4得0分\",\"组件检查函数抛出异常时,捕获为FAIL,得0分\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,然后依次从jira、sheets、docs、gmail、slack五个mock服务拉取current_state。接着按顺序执行4个计分组件和1个零权重的Slack门控组件:1)检查Jira新增工单;2)检查Sheets单元格精确值;3)检查Docs文档内容包含关键词;4)检查Gmail确认邮件数量和主题;5)Slack只读sanity check。每个组件通过_run_component执行,输出PASS/FAIL和COMPONENT结构化日志。各计分组件的得分累加得到total_score,最终通过min(total_score, 1.0)限制上限并四舍五入到4位小数输出REWARD。\",\"confidence\":1.0}" +} diff --git a/itops_field_change_002/_cua_gym_vm_bridge.sh b/itops_field_change_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/itops_field_change_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/itops_field_change_002/initial_setup.py b/itops_field_change_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c928812442aa2421383b9fc76d3c97a189bc1d --- /dev/null +++ b/itops_field_change_002/initial_setup.py @@ -0,0 +1,461 @@ +""" +Initial Setup: Meridian Labs config change — Salesforce picklist + HubSpot help text + + Google Docs runbook + Google Sheets tracker + Slack notification +Task ID: itops_field_change_002 +Domain: mock_websites (multi-mock: salesforce, hubspot, google_docs, google_sheets, slack) + +Creates the PRE-TASK state on initial_env (the SHARED mock backend, keyed by sid): +- Salesforce: 'Lead' object 'Lead Source' picklist has 5 values (no 'Webinar') +- HubSpot: 'Contact' 'Lifecycle Stage' property description = original text +- Google Docs: 'Configuration Change Runbook' has Q2 heading + 2 bullets, NO Q3 heading +- Google Sheets: 'Config Changes' / 'Change Log' has 3 rows (rows 2-4), row 5 empty +- Slack: #sysadmin-updates channel exists, no completion message yet +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# ---------------------------------------------------------------------------- +# Mock registry (task-deployed URLs). Same sid across all 5 mocks. +# ---------------------------------------------------------------------------- +BASE = "http://28.7.184.198" +MOCKS = { + "salesforce": f"{BASE}:8175", + "hubspot": f"{BASE}:8150", + "google_docs": f"{BASE}:8142", + "google_sheets": f"{BASE}:8145", + "slack": f"{BASE}:8178", +} + +TASK_ID = "prof26_field_change_002" + +# The two VMs are isolated, but the mock backend is SHARED (same 28.7.184.198 +# server, keyed by sid). We use a deterministic initial sid and write it to +# /tmp/task_web_sid on the initial_env for reward.py to discover. +SID = f"task_{TASK_ID}" +with open("/tmp/task_web_sid", "w") as f: + f.write(SID) + +print(f"[initial_setup] sid={SID}") + + +def inject(name, state): + url = f"{MOCKS[name]}/post?sid={SID}" + resp = requests.post(url, json={"action": "set", "state": state}, timeout=30) + assert resp.status_code == 200, f"[{name}] set failed: {resp.text}" + print(f"[initial_setup] injected {name}") + + +# ============================================================================ +# 1. SALESFORCE — Lead object 'Lead Source' picklist (5 values, no Webinar) +# ============================================================================ +def build_salesforce(): + user = { + "userId": "user-1", + "firstName": "Alex", + "lastName": "Morgan", + "email": "sysadmin@meridianlabs.io", + "phone": "(555) 123-4567", + "title": "Business Systems Administrator", + "department": "IT Operations", + "role": "System Administrator", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + } + return { + "user": user, + "users": [user], + "leads": [ + { + "leadId": "lead-1", "firstName": "Sarah", "lastName": "Chen", + "company": "Northwind Trading", "title": "VP Engineering", + "email": "sarah.chen@northwind.com", "phone": "(555) 111-2222", + "mobile": "", "status": "New", "source": "Web", "rating": "Hot", + "street": "", "city": "Austin", "state": "TX", "zip": "", "country": "USA", + "industry": "Technology", "employees": 320, "revenue": 24000000, + "website": "", "description": "", "ownerId": "user-1", + "createdDate": "2026-03-01T00:00:00.000Z", + "modifiedDate": "2026-03-01T00:00:00.000Z", + }, + { + "leadId": "lead-2", "firstName": "Marcus", "lastName": "Johnson", + "company": "Bluepeak Analytics", "title": "Director of Ops", + "email": "marcus.j@bluepeak.io", "phone": "(555) 222-3333", + "mobile": "", "status": "Working", "source": "Referral", "rating": "Warm", + "street": "", "city": "Denver", "state": "CO", "zip": "", "country": "USA", + "industry": "Analytics", "employees": 85, "revenue": 5200000, + "website": "", "description": "", "ownerId": "user-1", + "createdDate": "2026-03-05T00:00:00.000Z", + "modifiedDate": "2026-03-05T00:00:00.000Z", + }, + ], + "accounts": [ + {"accountId": "account-1", "name": "Northwind Trading", "type": "Customer", + "industry": "Technology", "revenue": 24000000, "employees": 320, "ownerId": "user-1", + "billingStreet": "", "billingCity": "Austin", "billingState": "TX", + "billingZip": "", "billingCountry": "USA"}, + {"accountId": "account-2", "name": "Bluepeak Analytics", "type": "Prospect", + "industry": "Analytics", "revenue": 5200000, "employees": 85, "ownerId": "user-1", + "billingStreet": "", "billingCity": "Denver", "billingState": "CO", + "billingZip": "", "billingCountry": "USA"}, + ], + "contacts": [ + {"contactId": "contact-1", "accountId": "account-1", "firstName": "Sarah", + "lastName": "Chen", "title": "VP Engineering", "department": "Engineering", + "email": "sarah.chen@northwind.com", "phone": "(555) 111-2222", "ownerId": "user-1"}, + {"contactId": "contact-2", "accountId": "account-2", "firstName": "Marcus", + "lastName": "Johnson", "title": "Director of Ops", "department": "Operations", + "email": "marcus.j@bluepeak.io", "phone": "(555) 222-3333", "ownerId": "user-1"}, + ], + "opportunities": [ + {"opportunityId": "opp-1", "name": "Northwind Platform Expansion", "accountId": "account-1", + "contactId": "contact-1", "amount": 48000, "closeDate": "2026-08-15", + "stage": "Proposal", "probability": 60, "ownerId": "user-1"}, + ], + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": ["user-2"], + "recentlyViewed": [], + "dismissedNotifications": [], + "dashboards": [], + "emailDrafts": [], + "reportSnapshots": [], + "partners": [], + # --- Task-specific configuration: Lead object 'Lead Source' picklist --- + "customObjects": { + "Lead": { + "label": "Lead", + "apiName": "Lead", + "fields": { + "LeadSource": { + "label": "Lead Source", + "apiName": "LeadSource", + "type": "picklist", + "description": "The channel or source through which the lead was acquired.", + "values": [ + {"label": "Web", "value": "Web"}, + {"label": "Referral", "value": "Referral"}, + {"label": "Event", "value": "Event"}, + {"label": "Partner", "value": "Partner"}, + {"label": "Outbound", "value": "Outbound"}, + ], + } + }, + } + }, + } + + +# ============================================================================ +# 2. HUBSPOT — Contact 'Lifecycle Stage' property (original description) +# ============================================================================ +def build_hubspot(): + contacts = [ + { + "id": "c1", "firstName": "Linda", "lastName": "Hess", + "email": "l.hess@meridianlabs.io", "phone": "(555) 300-1001", + "jobTitle": "Sales Operations Manager", "companyId": "comp1", + "lifecycleStage": "mql", "leadStatus": "open_deal", + "owner": "Admin User", "city": "Boston", "state": "MA", "country": "United States", + "createDate": "2024-01-15T10:30:00Z", "lastActivityDate": "2026-06-28T14:00:00Z", + "timeline": [], + }, + { + "id": "c2", "firstName": "Priya", "lastName": "Nair", + "email": "p.nair@meridianlabs.io", "phone": "(555) 300-1002", + "jobTitle": "Marketing Specialist", "companyId": "comp1", + "lifecycleStage": "lead", "leadStatus": "new", + "owner": "Admin User", "city": "Boston", "state": "MA", "country": "United States", + "createDate": "2024-02-15T10:30:00Z", "lastActivityDate": "2026-06-20T14:00:00Z", + "timeline": [], + }, + { + "id": "c3", "firstName": "Diego", "lastName": "Ramirez", + "email": "d.ramirez@meridianlabs.io", "phone": "(555) 300-1003", + "jobTitle": "Account Executive", "companyId": "comp1", + "lifecycleStage": "sql", "leadStatus": "open_deal", + "owner": "Admin User", "city": "Boston", "state": "MA", "country": "United States", + "createDate": "2024-03-15T10:30:00Z", "lastActivityDate": "2026-06-25T14:00:00Z", + "timeline": [], + }, + ] + return { + "contacts": contacts, + "companies": [ + {"id": "comp1", "name": "Meridian Labs", "domain": "meridianlabs.io", + "industry": "Technology", "phone": "(555) 300-1000", "city": "Boston", "state": "MA", + "country": "United States", "numberOfEmployees": 240, "annualRevenue": 38000000, + "lifecycleStage": "customer", "owner": "Admin User", + "description": "B2B SaaS analytics platform", "createDate": "2024-01-10T09:00:00Z"} + ], + "deals": [], + "tickets": [], + "tasks": [], + "notes": [], + "templates": [], + "meetings": [], + "forms": [], + "dealStages": { + "appointment_scheduled": {"id": "appointment_scheduled", "label": "Appointment Scheduled", "probability": 20, "color": "#E5F4FF", "order": 1}, + "qualified_to_buy": {"id": "qualified_to_buy", "label": "Qualified to Buy", "probability": 40, "color": "#FFF0E6", "order": 2}, + "presentation_scheduled": {"id": "presentation_scheduled", "label": "Presentation Scheduled", "probability": 60, "color": "#FFF8E6", "order": 3}, + "decision_maker_bought_in": {"id": "decision_maker_bought_in", "label": "Decision Maker Bought-In", "probability": 80, "color": "#E8F5E9", "order": 4}, + "contract_sent": {"id": "contract_sent", "label": "Contract Sent", "probability": 90, "color": "#E6FFFA", "order": 5}, + "closed_won": {"id": "closed_won", "label": "Closed Won", "probability": 100, "color": "#E6FFEC", "order": 6}, + "closed_lost": {"id": "closed_lost", "label": "Closed Lost", "probability": 0, "color": "#FFE6E6", "order": 7}, + }, + "ticketStatuses": { + "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1}, + "waiting_on_contact": {"id": "waiting_on_contact", "label": "Waiting on Contact", "color": "#FFF8E6", "order": 2}, + "waiting_on_us": {"id": "waiting_on_us", "label": "Waiting on Us", "color": "#FFF0E6", "order": 3}, + "in_progress": {"id": "in_progress", "label": "In Progress", "color": "#E6FFFA", "order": 4}, + "closed": {"id": "closed", "label": "Closed", "color": "#E6FFEC", "order": 5}, + }, + "appState": { + "sidebarOpen": True, + "currentUser": {"name": "Business Systems Administrator", "email": "sysadmin@meridianlabs.io", "avatar": None}, + }, + # --- Task-specific: Contact object 'Lifecycle Stage' property --- + "properties": { + "contacts": { + "lifecycle_stage": { + "label": "Lifecycle Stage", + "apiName": "lifecycle_stage", + "type": "enumeration", + "description": "Indicates the stage of the contact in the marketing/sales funnel.", + } + } + }, + } + + +# ============================================================================ +# 3. GOOGLE DOCS — 'Configuration Change Runbook' (Q2 heading, no Q3) +# ============================================================================ +def build_docs(): + return { + "currentUser": { + "id": "user-1", + "name": "Business Systems Administrator", + "email": "sysadmin@meridianlabs.io", + "avatar": "https://picsum.photos/100/100?random=sysadmin", + }, + "users": [ + {"id": "user-1", "name": "Business Systems Administrator", "email": "sysadmin@meridianlabs.io", "avatar": "https://picsum.photos/100/100?random=sysadmin"}, + {"id": "user-2", "name": "Linda Hess", "email": "l.hess@meridianlabs.io", "avatar": "https://picsum.photos/100/100?random=linda"}, + ], + "documents": { + "doc_run_01": { + "id": "doc_run_01", + "title": "Configuration Change Runbook", + "content": ( + "

Configuration Change Runbook

" + "

This runbook records all approved configuration changes at Meridian Labs.

" + "

Q2 2026 Changes

" + "
    " + "
  • CHG-2026-0415: Added "Demo Requested" to Salesforce Lead Status picklist. Requested by Marketing (Priya Nair). Verified by sysadmin.
  • " + "
  • CHG-2026-0520: Updated HubSpot "Deal Stage" help text to clarify won/lost criteria. Requested by Sales Ops (Linda Hess). Verified by sysadmin.
  • " + "
" + ), + "ownerId": "user-1", + "starred": False, + "created": "2026-01-10T10:00:00Z", + "updated": "2026-05-20T14:30:00Z", + "sharedWith": [ + {"userId": "user-2", "permission": "editor"} + ], + "linkSharing": {"enabled": True, "permission": "viewer"}, + } + }, + "comments": [], + "ui": { + "currentDocId": "doc_run_01", + "sidebarOpen": False, + "sidebarTab": "comments", + "shareDialogOpen": False, + "findReplaceOpen": False, + "viewMode": "editing", + "zoom": 100, + "documentListView": "grid", + "searchQuery": "", + }, + } + + +# ============================================================================ +# 4. GOOGLE SHEETS — 'Config Changes' / 'Change Log' (3 rows, row 5 empty) +# ============================================================================ +def build_sheets(): + def cell(value, bold=False, bg=None, align=None): + style = {} + if bold: + style["bold"] = True + if bg: + style["bg"] = bg + if align: + style["align"] = align + return { + "value": value, + "formula": value, + "style": style or None, + } + + headers = ["Change ID", "Date", "System", "Object", "Change Summary", "Requested By", "Status"] + data = { + "A1": cell("Change ID", bold=True, bg="#E8EAED", align="center"), + "B1": cell("Date", bold=True, bg="#E8EAED", align="center"), + "C1": cell("System", bold=True, bg="#E8EAED", align="center"), + "D1": cell("Object", bold=True, bg="#E8EAED", align="center"), + "E1": cell("Change Summary", bold=True, bg="#E8EAED", align="center"), + "F1": cell("Requested By", bold=True, bg="#E8EAED", align="center"), + "G1": cell("Status", bold=True, bg="#E8EAED", align="center"), + # Row 2 + "A2": cell("CHG-2026-0626"), + "B2": cell("2026-06-26"), + "C2": cell("Salesforce"), + "D2": cell("Opportunity Stage"), + "E2": cell("Renamed stage Negotiation -> Negotiation/Review"), + "F2": cell("Sara Kim"), + "G2": cell("Completed"), + # Row 3 + "A3": cell("CHG-2026-0628"), + "B3": cell("2026-06-28"), + "C3": cell("HubSpot"), + "D3": cell("Deal Stage"), + "E3": cell("Added new deal stage Demo Scheduled"), + "F3": cell("Daniel Okafor"), + "G3": cell("Completed"), + # Row 4 + "A4": cell("CHG-2026-0630"), + "B4": cell("2026-06-30"), + "C4": cell("Salesforce"), + "D4": cell("Account Type"), + "E4": cell("Added SMB segment value"), + "F4": cell("Linda Hess"), + "G4": cell("Completed"), + # Row 5 is the next available empty row (deliberately absent) + } + return { + "id": "wb_cfg_01", + "title": "Config Changes", + "activeSheetId": "sh_chg_01", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [ + { + "id": "sh_chg_01", + "name": "Change Log", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": "#1A73E8", + "isHidden": False, + "columnWidths": {"0": 150, "1": 120, "2": 130, "3": 200, "4": 320, "5": 130, "6": 110}, + "data": data, + } + ], + } + + +# ============================================================================ +# 5. SLACK — #sysadmin-updates channel exists (prior unrelated content) +# ============================================================================ +def build_slack(): + return { + "currentUser": { + "userId": "user_1", + "fullName": "Business Systems Administrator", + "displayName": "sysadmin", + "email": "sysadmin@meridianlabs.io", + "avatar": "https://picsum.photos/200/200?random=sysadmin", + "status": "active", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York", + }, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Meridian Labs", "icon": ""}, + "users": [ + {"userId": "user_1", "fullName": "Business Systems Administrator", "displayName": "sysadmin", "email": "sysadmin@meridianlabs.io", "avatar": "https://picsum.photos/200/200?random=sysadmin", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_2", "fullName": "Linda Hess", "displayName": "l.hess", "email": "l.hess@meridianlabs.io", "avatar": "https://picsum.photos/200/200?random=linda", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_3", "fullName": "Priya Nair", "displayName": "p.nair", "email": "p.nair@meridianlabs.io", "avatar": "https://picsum.photos/200/200?random=priya", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + ], + "channels": [ + {"channelId": "general", "name": "general", "description": "Company-wide announcements", "topic": "", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1", "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "sysadmin-updates", "name": "sysadmin-updates", "description": "System and configuration change notifications", "topic": "Config change log", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1", "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "general": [ + {"messageId": "msg_gen_1", "senderId": "user_2", "content": "Reminder: please log all config changes in the runbook.", "timestamp": "2026-06-29T09:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False} + ], + "sysadmin-updates": [ + {"messageId": "msg_su_1", "senderId": "user_2", "content": "CHG-2026-0630 has been completed and logged. SMB segment added to Salesforce Account Type.", "timestamp": "2026-06-30T16:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False} + ], + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + + +# ---------------------------------------------------------------------------- +# Inject all 5 mocks +# ---------------------------------------------------------------------------- +inject("salesforce", build_salesforce()) +inject("hubspot", build_hubspot()) +inject("google_docs", build_docs()) +inject("google_sheets", build_sheets()) +inject("slack", build_slack()) + +# ---------------------------------------------------------------------------- +# Verify initial_state is set on every mock +# ---------------------------------------------------------------------------- +for name, url in MOCKS.items(): + go = requests.get(f"{url}/go?sid={SID}", timeout=10).json() + assert go["initial_state"] is not None, f"[{name}] initial_state is None" +print("[initial_setup] all 5 initial_states verified") + + +# ---------------------------------------------------------------------------- +# Launch Chrome for EVERY mock (the agent needs all of them open) +# ---------------------------------------------------------------------------- +def launch_gui(command, delay_sec=0.5): + 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.3) + +print(f"GUI_READY: launched {len(MOCKS)} mock windows (sid={SID})") diff --git a/itops_field_change_002/reward.py b/itops_field_change_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..8a7c25247353e5762e7ca7ed1132b9aa20b6d6cd --- /dev/null +++ b/itops_field_change_002/reward.py @@ -0,0 +1,190 @@ +""" +Reward Script: Meridian Labs configuration change (Salesforce + HubSpot + Sheets + Slack) +Task ID: itops_field_change_002 +Domain: mock_websites +Scoring: 4 independent components, 0.25 each (total 1.0). + C1 Salesforce Lead Source picklist gains 'Webinar' (programmatic) + C2 HubSpot Lifecycle Stage description appended (programmatic) + C3 Google Sheets Change Log row 5 exact values (programmatic) + C4 Slack #sysadmin-updates exactly one new message w/ CHG id + @l.hess (LLM judge for text) +""" +import json +import sys + +import requests + +# --- Mock base URLs (from task_config.json) --- +SF_URL = "http://28.7.184.198:8175" # salesforce_mock +HS_URL = "http://28.7.184.198:8150" # hubspot_mock +SHEETS_URL = "http://28.7.184.198:8145" # google_sheets_mock +SLACK_URL = "http://28.7.184.198:8178" # slack_mock + +MOCKS = { + "salesforce": SF_URL, + "hubspot": HS_URL, + "sheets": SHEETS_URL, + "slack": SLACK_URL, +} + + +def _fetch_states(url): + """Fetch initial/current state from a mock's /go endpoint. Returns (initial, current).""" + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + resp = requests.get(f'{url}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + return data.get('initial_state', {}), data.get('current_state', {}) + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# --- Per-component checks (one function per sub-objective) --- + +def check_component_1(initial, current): + """Salesforce Lead 'Lead Source' picklist (customObjects.Lead.fields.LeadSource.values) + gains a 6th value 'Webinar' appended last, keeping the first 5 unchanged. + Pass condition: values == ['Web','Referral','Event','Partner','Outbound','Webinar']. + """ + try: + vals = current['customObjects']['Lead']['fields']['LeadSource']['values'] + labels = [v.get('value') or v.get('label') for v in vals] + except Exception as e: + return False, 0.0, f'cannot locate picklist: {e}' + expected = ['Web', 'Referral', 'Event', 'Partner', 'Outbound', 'Webinar'] + if labels == expected: + return True, 0.25, f'picklist values exactly {labels}' + return False, 0.0, f'expected {expected}, found {labels}' + + +def check_component_2(initial, current): + """HubSpot Contact 'Lifecycle Stage' property description + (properties.contacts.lifecycle_stage.description) is appended with the + Webinar/MQL sentence. + Pass condition: description == 'Indicates the stage of the contact in the + marketing/sales funnel. Webinar-attended contacts should be set to MQL.' + """ + expected = ('Indicates the stage of the contact in the marketing/sales funnel. ' + 'Webinar-attended contacts should be set to MQL.') + try: + desc = current['properties']['contacts']['lifecycle_stage']['description'] + except Exception as e: + return False, 0.0, f'cannot locate description: {e}' + if desc == expected: + return True, 0.25, 'description matches expected text exactly' + return False, 0.0, f'expected exactly the appended text; found: {desc!r}' + + +def check_component_3(initial, current): + """Google Sheets 'Change Log' sheet row 5 populated with exact values. + Pass condition: A5..G5 == [CHG-2026-0701, 2026-07-01, Salesforce + HubSpot, + 'Lead Source picklist / Lifecycle Stage property', 'Added Webinar to Salesforce + Lead Source; updated HubSpot Lifecycle Stage help text', Linda Hess, Completed]. + """ + expected = { + 'A5': 'CHG-2026-0701', + 'B5': '2026-07-01', + 'C5': 'Salesforce + HubSpot', + 'D5': 'Lead Source picklist / Lifecycle Stage property', + 'E5': 'Added Webinar to Salesforce Lead Source; updated HubSpot Lifecycle Stage help text', + 'F5': 'Linda Hess', + 'G5': 'Completed', + } + try: + sheet = next(s for s in current['sheets'] if s['id'] == 'sh_chg_01') + data = sheet['data'] + except Exception as e: + return False, 0.0, f'cannot locate Change Log sheet: {e}' + mismatches = [] + for cell, exp in expected.items(): + got = data.get(cell, {}).get('value') + if got != exp: + mismatches.append(f'{cell}: expected {exp!r} got {got!r}') + if not mismatches: + return True, 0.25, 'row 5 all 7 cells match exactly' + return False, 0.0, '; '.join(mismatches) + + +def check_component_4(initial, current): + """Slack #sysadmin-updates has exactly one message containing CHG-2026-0701 and the + @l.hess mention, and that message also conveys the full change-completion notice. + Pass condition: exactly one message in #sysadmin-updates contains 'CHG-2026-0701', + and that message also contains '@l.hess', 'Webinar', 'Lifecycle Stage', 'MQL', + 'Config Changes', 'Configuration Change Runbook', and 'Verified by sysadmin'. + """ + curr_msgs = current.get('messages', {}).get('sysadmin-updates', []) + chg_msgs = [m for m in curr_msgs if 'CHG-2026-0701' in m.get('content', '')] + if len(chg_msgs) != 1: + return False, 0.0, (f'expected exactly 1 message with CHG-2026-0701, ' + f'found {len(chg_msgs)}') + content = chg_msgs[0].get('content', '') + required = [ + ('@l.hess', '@l.hess mention'), + ('Webinar', 'Salesforce Lead Source value'), + ('Lifecycle Stage', 'HubSpot property'), + ('MQL', 'Webinar-attended -> MQL note'), + ('Config Changes', 'tracker reference'), + ('Configuration Change Runbook', 'runbook reference'), + ('Verified by sysadmin', 'verification note'), + ] + missing = [label for token, label in required if token not in content] + if not missing: + return True, 0.25, 'new Slack message contains all required elements' + return False, 0.0, f'missing elements: {missing}' + + +def verify_task(): + """Fetch state from all 4 mocks and verify the 4 required changes.""" + states = {} + for name, url in MOCKS.items(): + try: + initial, current = _fetch_states(url) + except Exception as e: + print(f'ERROR: Cannot fetch {name} state: {e}') + print('REWARD: 0.0') + sys.exit(0) + states[name] = (initial, current) + + total_score = 0.0 + sf_i, sf_c = states['salesforce'] + hs_i, hs_c = states['hubspot'] + sheets_i, sheets_c = states['sheets'] + slack_i, slack_c = states['slack'] + + for idx, name, weight, fn, args in [ + (1, 'Salesforce Lead Source picklist +Webinar', 0.25, check_component_1, (sf_i, sf_c)), + (2, 'HubSpot Lifecycle Stage help text', 0.25, check_component_2, (hs_i, hs_c)), + (3, 'Google Sheets Change Log row 5', 0.25, check_component_3, (sheets_i, sheets_c)), + (4, 'Slack #sysadmin-updates new message', 0.25, check_component_4, (slack_i, slack_c)), + ]: + _, score, _ = _run_component(idx, name, weight, fn, args) + total_score += score + + final_score = round(min(total_score, 1.0), 4) + print(f'\nScore: {total_score}/1.0') + print(f'REWARD: {final_score}') + return final_score + + +verify_task() diff --git a/itops_field_change_002/reward_label.json b/itops_field_change_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..1d0f407fc93e2fa8ff9e0ef5261b5de9c0b93362 --- /dev/null +++ b/itops_field_change_002/reward_label.json @@ -0,0 +1,73 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof26_field_change_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:31:04", + "label": { + "task_id": "itops_field_change_002", + "domain": "mock_websites", + "summary": "验证 Meridian Labs 配置变更任务在 Salesforce、HubSpot、Google Docs、Google Sheets 和 Slack 五个系统中的预期修改是否全部完成", + "is_placeholder": false, + "data_sources": [ + "salesforce_mock (http://28.7.186.212:8195)", + "hubspot_mock (http://28.7.186.212:8170)", + "google_docs_mock (http://28.7.186.212:8162)", + "google_sheets_mock (http://28.7.186.212:8165)", + "slack_mock (http://28.7.186.212:8198)", + "/tmp/task_web_sid" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.2, + "description": "检查 Salesforce Lead 的 Lead Source 下拉列表是否在最后追加了 'Webinar',且前 5 项保持不变", + "check_logic": "从 current['customObjects']['Lead']['fields']['LeadSource']['values'] 提取各选项的 value 或 label,组成列表后检查是否严格等于 ['Web','Referral','Event','Partner','Outbound','Webinar']", + "pass_condition": "labels 严格等于预期列表,顺序与内容完全一致" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "检查 HubSpot Contact 的 Lifecycle Stage 属性描述是否追加了特定的 Webinar/MQL 句子", + "check_logic": "从 current['properties']['contacts']['lifecycle_stage']['description'] 读取描述文本,检查是否严格等于 'Indicates the stage of the contact in the marketing/sales funnel. Webinar-attended contacts should be set to MQL.'", + "pass_condition": "description 与预期文本完全匹配" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "检查 Google Docs 'Configuration Change Runbook' 是否包含 Q3 2026 Changes 标题和 CHG-2026-0701 相关 bullet", + "check_logic": "从 current['documents']['doc_run_01']['content'] 读取文档内容,检查是否同时包含 'Q3 2026 Changes'、'CHG-2026-0701'、'Webinar'、'Lifecycle Stage'、'MQL'、'Linda Hess' 六个必需元素", + "pass_condition": "内容中同时包含所有 6 个必需元素,缺一不可" + }, + { + "name": "Component 4", + "weight": 0.2, + "description": "检查 Google Sheets 'Change Log' 工作表第 5 行(A5 到 G5)是否为精确预期值", + "check_logic": "在 current['sheets'] 中查找 id 为 'sh_chg_01' 的工作表,依次比对 A5、B5、C5、D5、E5、F5、G5 的 value 是否分别严格匹配 7 个预期字符串", + "pass_condition": "A5..G5 全部 7 个单元格的值与预期完全一致,无任何差异" + }, + { + "name": "Component 5", + "weight": 0.2, + "description": "检查 Slack #sysadmin-updates 频道是否恰好有一条包含 CHG-2026-0701 的新消息,且该消息包含所有必需元素", + "check_logic": "从 current['messages']['sysadmin-updates'] 获取消息列表,筛选包含 'CHG-2026-0701' 的消息,检查数量是否恰好为 1;若是,再检查该消息内容是否同时包含 '@l.hess'、'Webinar'、'Lifecycle Stage'、'MQL'、'Config Changes'、'Configuration Change Runbook'、'Verified by sysadmin'", + "pass_condition": "恰好有 1 条消息包含 CHG-2026-0701,且该消息内容同时包含所有 7 个必需元素" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加得到 total_score,最终通过 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败会导致 _fetch_states 抛出异常", + "任一 mock 服务状态拉取失败会打印 ERROR、输出 REWARD: 0.0 并调用 sys.exit(0) 提前退出", + "Salesforce picklist 值不匹配返回 0.0", + "HubSpot description 与预期文本不完全匹配返回 0.0", + "Google Docs 缺少任一必需元素返回 0.0", + "Google Sheets 任一单元格值不匹配返回 0.0", + "Slack 中包含 CHG-2026-0701 的消息数量不为 1 返回 0.0", + "Slack 消息缺少任一必需元素返回 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 5 个 mock 服务发送 GET /go?sid={sid} 请求拉取 initial_state 和 current_state。若任一 mock 拉取失败,脚本立即输出 REWARD: 0.0 并退出。成功获取状态后,脚本按顺序执行 5 个独立组件检查:Component 1 验证 Salesforce Lead Source 下拉列表追加 'Webinar';Component 2 验证 HubSpot Lifecycle Stage 描述追加特定文本;Component 3 验证 Google Docs 内容包含 6 个必需关键词;Component 4 验证 Google Sheets Change Log 第 5 行 7 个单元格的精确值;Component 5 验证 Slack #sysadmin-updates 恰好有一条包含 CHG-2026-0701 且包含 7 个必需元素的消息。每个组件权重为 0.2,通过则获得 0.2 分,失败则得 0.0 分。各组件得分累加后,最终分数通过 min(total_score, 1.0) 钳制到 1.0 上限,并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外内容。\n\n让我仔细阅读代码:\n\n1. **Task ID**: prof26_field_change_002(从 docstring 中明确提取)\n2. **Domain**: mock_websites(从 docstring 中明确提取)\n3. **Summary**: 验证 Meridian Labs 配置变更任务,涉及 Salesforce、HubSpot、Google Docs、Google Sheets 和 Slack 五个系统的状态变更。\n4. **is_placeholder**: false(脚本有实际的检查逻辑,不是占位脚本)\n5. **data_sources**: \n - salesforce_mock (http://28.7.186.212:8195)\n - hubspot_mock (http://28.7.186.212:8170)\n - google_docs_mock (http://28.7.186.212:8162)\n - google_sheets_mock (http://28.7.186.212:8165)\n - slack_mock (http://28.7.186.212:8198)\n - /tmp/task_web_sid(读取 session ID)\n\n6. **Scoring components**:\n - Component 1: Salesforce Lead Source picklist 增加 'Webinar',权重 0.2\n - Component 2: HubSpot Lifecycle Stage description 追加特定文本,权重 0.2\n - Component 3: Google Docs 包含 Q3 2026 Changes 标题和 CHG-2026-0701 相关 bullet,权重 0.2\n - Component 4: Google Sheets Change Log 第5行精确值,权重 0.2\n - Component 5: Slack #sysadmin-updates 恰好一条新消息包含 CHG id 和 @l.hess 等,权重 0.2\n\n7. **Score aggregation**: 各组件分数相加,最终钳制到 1.0(min(total_score, 1.0))\n\n8. **Failure modes**:\n - 读取 /tmp/task_web_sid 失败(虽然代码里没有显式 try-catch 这个,但 _fetch_states 会失败)\n - 任何 mock 状态拉取失败(会打印 ERROR 和 REWARD: 0.0,然后 sys.exit(0))\n - 各组件检查失败返回 0.0\n\n9. **Scoring logic explanation**: 按执行顺序:\n - 从 /tmp/task_web_sid 读取 session ID\n - 依次向 5 个 mock 服务发送 GET /go?sid={sid} 请求获取 initial_state 和 current_state\n - 如果任一 mock 拉取失败,打印 ERROR,输出 REWARD: 0.0 并退出\n - 分别执行 5 个组件检查,每个权重 0.2\n - 各组件分数累加得到 total_score\n - 最终分数为 min(total_score, 1.0) 并四舍五入到 4 位小数\n\n10. **Confidence**: 1.0(代码清晰完整)\n\n让我详细构建每个组件:\n\nComponent 1:\n- name: Component 1\n- weight: 0.2\n- description: 检查 Salesforce Lead 的 Lead Source 下拉列表是否在最后追加了 'Webinar',且前 5 项保持不变\n- check_logic: 从 current['customObjects']['Lead']['fields']['LeadSource']['values'] 提取 value 或 label,检查是否严格等于 ['Web', 'Referral', 'Event', 'Partner', 'Outbound', 'Webinar']\n- pass_condition: labels 严格等于预期列表\n\nComponent 2:\n- name: Component 2\n- weight: 0.2\n- description: 检查 HubSpot Contact 的 Lifecycle Stage 属性描述是否追加了特定 Webinar/MQL 句子\n- check_logic: 从 current['properties']['contacts']['lifecycle_stage']['description'] 读取描述,检查是否严格等于 'Indicates the stage of the contact in the marketing/sales funnel. Webinar-attended contacts should be set to MQL.'\n- pass_condition: description 与预期文本完全匹配\n\nComponent 3:\n- name: Component 3\n- weight: 0.2\n- description: 检查 Google Docs 'Configuration Change Runbook' 是否包含 Q3 2026 Changes 标题和 CHG-2026-0701 相关 bullet\n- check_logic: 从 current['documents']['doc_run_01']['content'] 读取内容,检查是否同时包含 'Q3 2026 Changes'、'CHG-2026-0701'、'Webinar'、'Lifecycle Stage'、'MQL'、'Linda Hess'\n- pass_condition: 内容中同时包含所有 6 个必需元素\n\nComponent 4:\n- name: Component 4\n- weight: 0.2\n- description: 检查 Google Sheets 'Change Log' 工作表第 5 行(A5..G5)是否为精确预期值\n- check_logic: 在 current['sheets'] 中查找 id 为 'sh_chg_01' 的工作表,检查 A5 到 G5 的 value 是否分别严格匹配 7 个预期字符串\n- pass_condition: A5..G5 全部 7 个单元格的值与预期完全一致\n\nComponent 5:\n- name: Component 5\n- weight: 0.2\n- description: 检查 Slack #sysadmin-updates 频道是否恰好有一条包含 CHG-2026-0701 的新消息,且该消息包含所有必需元素\n- check_logic: 从 current['messages']['sysadmin-updates'] 获取消息,筛选包含 'CHG-2026-0701' 的消息,检查数量是否恰好为 1;若是,再检查该消息内容是否同时包含 '@l.hess'、'Webinar'、'Lifecycle Stage'、'MQL'、'Config Changes'、'Configuration Change Runbook'、'Verified by sysadmin'\n- pass_condition: 恰好有 1 条消息包含 CHG-2026-0701,且该消息包含所有 7 个必需元素\n\nFailure modes:\n- 从 /tmp/task_web_sid 读取 session ID 失败(会导致 _fetch_states 异常)\n- 任一 mock 服务状态拉取失败(会触发 sys.exit(0) 并返回 0.0)\n- Salesforce picklist 值不匹配(返回 0.0)\n- HubSpot description 不匹配(返回 0.0)\n- Google Docs 缺少必需元素(返回 0.0)\n- Google Sheets 单元格值不匹配(返回 0.0)\n- Slack 消息数量不为 1 或缺少必需元素(返回 0.0)\n\n注意:用户要求不要输出 Markdown 代码块标记,不要输出额外解释,不要输出思考过程,不要输出 thinking 标签。输出的第一个字符必须是 {,最后一个字符必须是 }。\n\n我需要确保 JSON 格式正确,所有字符串值使用中文(task_id、domain、字段名、代码标识符保留原样)。\n\n让我再检查一下 docstring 中的信息:\n- Task ID: prof26_field_change_002\n- Domain: mock_websites\n- 5 independent components, 0.2 each (total 1.0)\n\n确认 is_placeholder 为 false。\n\n确认 score_aggregation: 各组件分数相加,最终通过 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数。\n\n确认 confidence: 1.0\n\n现在构建 JSON。 {\"task_id\":\"prof26_field_change_002\",\"domain\":\"mock_websites\",\"summary\":\"验证 Meridian Labs 配置变更任务在 Salesforce、HubSpot、Google Docs、Google Sheets 和 Slack 五个系统中的预期修改是否全部完成\",\"is_placeholder\":false,\"data_sources\":[\"salesforce_mock (http://28.7.186.212:8195)\",\"hubspot_mock (http://28.7.186.212:8170)\",\"google_docs_mock (http://28.7.186.212:8162)\",\"google_sheets_mock (http://28.7.186.212:8165)\",\"slack_mock (http://28.7.186.212:8198)\",\"/tmp/task_web_sid\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.2,\"description\":\"检查 Salesforce Lead 的 Lead Source 下拉列表是否在最后追加了 'Webinar',且前 5 项保持不变\",\"check_logic\":\"从 current['customObjects']['Lead']['fields']['LeadSource']['values'] 提取各选项的 value 或 label,组成列表后检查是否严格等于 ['Web','Referral','Event','Partner','Outbound','Webinar']\",\"pass_condition\":\"labels 严格等于预期列表,顺序与内容完全一致\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"检查 HubSpot Contact 的 Lifecycle Stage 属性描述是否追加了特定的 Webinar/MQL 句子\",\"check_logic\":\"从 current['properties']['contacts']['lifecycle_stage']['description'] 读取描述文本,检查是否严格等于 'Indicates the stage of the contact in the marketing/sales funnel. Webinar-attended contacts should be set to MQL.'\",\"pass_condition\":\"description 与预期文本完全匹配\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"检查 Google Docs 'Configuration Change Runbook' 是否包含 Q3 2026 Changes 标题和 CHG-2026-0701 相关 bullet\",\"check_logic\":\"从 current['documents']['doc_run_01']['content'] 读取文档内容,检查是否同时包含 'Q3 2026 Changes'、'CHG-2026-0701'、'Webinar'、'Lifecycle Stage'、'MQL'、'Linda Hess' 六个必需元素\",\"pass_condition\":\"内容中同时包含所有 6 个必需元素,缺一不可\"},{\"name\":\"Component 4\",\"weight\":0.2,\"description\":\"检查 Google Sheets 'Change Log' 工作表第 5 行(A5 到 G5)是否为精确预期值\",\"check_logic\":\"在 current['sheets'] 中查找 id 为 'sh_chg_01' 的工作表,依次比对 A5、B5、C5、D5、E5、F5、G5 的 value 是否分别严格匹配 7 个预期字符串\",\"pass_condition\":\"A5..G5 全部 7 个单元格的值与预期完全一致,无任何差异\"},{\"name\":\"Component 5\",\"weight\":0.2,\"description\":\"检查 Slack #sysadmin-updates 频道是否恰好有一条包含 CHG-2026-0701 的新消息,且该消息包含所有必需元素\",\"check_logic\":\"从 current['messages']['sysadmin-updates'] 获取消息列表,筛选包含 'CHG-2026-0701' 的消息,检查数量是否恰好为 1;若是,再检查该消息内容是否同时包含 '@l.hess'、'Webinar'、'Lifecycle Stage'、'MQL'、'Config Changes'、'Configuration Change Runbook'、'Verified by sysadmin'\",\"pass_condition\":\"恰好有 1 条消息包含 CHG-2026-0701,且该消息内容同时包含所有 7 个必需元素\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加得到 total_score,最终通过 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败会导致 _fetch_states 抛出异常\",\"任一 mock 服务状态拉取失败会打印 ERROR、输出 REWARD: 0.0 并调用 sys.exit(0) 提前退出\",\"Salesforce picklist 值不匹配返回 0.0\",\"HubSpot description 与预期文本不完全匹配返回 0.0\",\"Google Docs 缺少任一必需元素返回 0.0\",\"Google Sheets 任一单元格值不匹配返回 0.0\",\"Slack 中包含 CHG-2026-0701 的消息数量不为 1 返回 0.0\",\"Slack 消息缺少任一必需元素返回 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 5 个 mock 服务发送 GET /go?sid={sid} 请求拉取 initial_state 和 current_state。若任一 mock 拉取失败,脚本立即输出 REWARD: 0.0 并退出。成功获取状态后,脚本按顺序执行 5 个独立组件检查:Component 1 验证 Salesforce Lead Source 下拉列表追加 'Webinar';Component 2 验证 HubSpot Lifecycle Stage 描述追加特定文本;Component 3 验证 Google Docs 内容包含 6 个必需关键词;Component 4 验证 Google Sheets Change Log 第 5 行 7 个单元格的精确值;Component 5 验证 Slack #sysadmin-updates 恰好有一条包含 CHG-2026-0701 且包含 7 个必需元素的消息。每个组件权重为 0.2,通过则获得 0.2 分,失败则得 0.0 分。各组件得分累加后,最终分数通过 min(total_score, 1.0) 钳制到 1.0 上限,并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/metadata/build_summary.json b/metadata/build_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..5b90a5c387faffd764eacfeb1f4ee65ce8549b8b --- /dev/null +++ b/metadata/build_summary.json @@ -0,0 +1,28 @@ +{ + "source_repo": "SamuelGuo/OSworker_cache", + "source_revision": "b6753bc357a756301f3429a95b38362da6035030", + "included_source_file_count": 532, + "included_source_bytes": 318780313, + "omitted_files": [ + { + "path": "images/Ubuntu_openpyxl.qcow2", + "size": 27445690368, + "sha256": "ec20b56ed19d2fe2cca0f11d8fb3564cfd2926996a4a984ad12ace5af73acb5d", + "reason": "Referenced externally instead of mirrored." + } + ], + "task_count": 100, + "demo_task_count": 33, + "demo_subtask_count": 212, + "demo_step_count": 3989, + "parquet_files": { + "data/demonstrations/test-00000-of-00001.parquet": { + "size": 3455916, + "sha256": "6b2ddb25c297cd2a3ec66a74ab3df68d0c70c398239a21fb7561a676bad33f62" + }, + "data/tasks/test-00000-of-00001.parquet": { + "size": 169218, + "sha256": "7db119f00d20e823ed1469107ed39d2b8234729568a9a414123b5c7a179712bb" + } + } +} diff --git a/metadata/source_cache_manifest.json b/metadata/source_cache_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f575d28c2843fba1178c9298dae55d63a20b23 --- /dev/null +++ b/metadata/source_cache_manifest.json @@ -0,0 +1,3737 @@ +{ + "source_repo": "SamuelGuo/OSworker_cache", + "source_revision": "b6753bc357a756301f3429a95b38362da6035030", + "files": [ + { + "path": ".MOCK_HOST.applied", + "size": 3953, + "lfs_oid": null, + "omitted": false, + "sha256": "15d5842bc5e561a9bff96526c3170f2bc66a9999fc8d200f58d40a22f11e37eb" + }, + { + "path": ".gitattributes", + "size": 2693, + "lfs_oid": null, + "omitted": false, + "sha256": "48c7b75bdf0117cec193ad02a44cb65e572035d7560d0acac4a8240eb90238e5" + }, + { + "path": ".mock_endpoint_remap.lock", + "size": 0, + "lfs_oid": null, + "omitted": false, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "path": "_setup_nonzero_stderr.txt", + "size": 17722378, + "lfs_oid": null, + "omitted": false, + "sha256": "63373dc46422100785433dde46a11b169fd52d4e6a59661b7cae3af791764f58" + }, + { + "path": "_setup_nonzero_stdout.txt", + "size": 12520608, + "lfs_oid": null, + "omitted": false, + "sha256": "cd4fadd833dc12b839656697338986a11ffe20c9e88d55d5e941832a65bfaac4" + }, + { + "path": "ae_contract_signature_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ae_contract_signature_001/initial_setup.py", + "size": 27116, + "lfs_oid": null, + "omitted": false, + "sha256": "2ca8af445f833dc07b3451fd558bddb39ea41b7bebf4b122c24217f36f0fc15c" + }, + { + "path": "ae_contract_signature_001/reward.py", + "size": 18068, + "lfs_oid": null, + "omitted": false, + "sha256": "bfb09a403755e4a7af8850914b51df8b288c52c807b7bb0aad9c923c85145eee" + }, + { + "path": "ae_contract_signature_001/reward_label.json", + "size": 18324, + "lfs_oid": null, + "omitted": false, + "sha256": "8b45f78a491a8f82457a6ce382743936d2e7af50ce9f1be5a177f347f9922e3f" + }, + { + "path": "ae_deal_handoff_002__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ae_deal_handoff_002__long/initial_setup.py", + "size": 30173, + "lfs_oid": null, + "omitted": false, + "sha256": "80a16cf75525b3c28737fd0f3c3e8f0ca7137081fa1a3a0a02db170bed2dae8f" + }, + { + "path": "ae_deal_handoff_002__long/reward.py", + "size": 31982, + "lfs_oid": null, + "omitted": false, + "sha256": "1eee2349fbcdb75e665d485f22fe0b4f2b0ccc6eb019e90460a014da83cd92c5" + }, + { + "path": "ae_pipeline_hygiene_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ae_pipeline_hygiene_003/initial_setup.py", + "size": 30140, + "lfs_oid": null, + "omitted": false, + "sha256": "e345952fb1c195c83fdfb7c3347e190fe90474d0d6ca2ea948c6d38c7448c186" + }, + { + "path": "ae_pipeline_hygiene_003/reward.py", + "size": 23657, + "lfs_oid": null, + "omitted": false, + "sha256": "5126b52a43765c083172e22fb15b7b9cfcf955c700ff9a256b8e1e5f14e8712b" + }, + { + "path": "ae_pipeline_hygiene_003/reward_label.json", + "size": 19945, + "lfs_oid": null, + "omitted": false, + "sha256": "5f14f5b8b2f86d1f3d08f8498ef293a50e28f0b8c36e9ae952773cd5bd470c6b" + }, + { + "path": "ae_pipeline_review_004__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ae_pipeline_review_004__long/initial_setup.py", + "size": 39364, + "lfs_oid": null, + "omitted": false, + "sha256": "739317f356350b5fa7153b4f5e5f1b1eae5f047e9a926088464b60aa2316028c" + }, + { + "path": "ae_pipeline_review_004__long/reward.py", + "size": 22847, + "lfs_oid": null, + "omitted": false, + "sha256": "f821a43f162e95c60dfe3a81e847afa5e9f0576cfd7b72a3f645526939f4c3cf" + }, + { + "path": "am_renewal_contract_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "am_renewal_contract_001/initial_setup.py", + "size": 33391, + "lfs_oid": null, + "omitted": false, + "sha256": "7f65e6a38e1df00435cf5e47c49736461aec6f288ff5406f32fff2a7dc995b91" + }, + { + "path": "am_renewal_contract_001/reward.py", + "size": 17323, + "lfs_oid": null, + "omitted": false, + "sha256": "3b62b30c8fdad08966bd677fcedcb76be354d9f43f6c54880abc9f3e94874fcc" + }, + { + "path": "am_renewal_contract_001/reward_label.json", + "size": 26293, + "lfs_oid": null, + "omitted": false, + "sha256": "c6090f97068efea7a47186def03aaf728afd995e0b84f12da54e398d6f99dac8" + }, + { + "path": "am_renewal_hubspot_004__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "am_renewal_hubspot_004__long/initial_setup.py", + "size": 32517, + "lfs_oid": null, + "omitted": false, + "sha256": "65d3f27f3d60f4a57adef102d9db01086455cac4f1663867b782871ac37fefde" + }, + { + "path": "am_renewal_hubspot_004__long/reward.py", + "size": 26955, + "lfs_oid": null, + "omitted": false, + "sha256": "9dcaced85b30e8fc05e906b43da066657838df4968a40100eff0384fa2234ac0" + }, + { + "path": "am_renewal_outreach_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "am_renewal_outreach_002/initial_setup.py", + "size": 27364, + "lfs_oid": null, + "omitted": false, + "sha256": "823d748a36a66a29c6adf4a0d7bed84e46ad7cab98aab6442fd926b2c08aad49" + }, + { + "path": "am_renewal_outreach_002/reward.py", + "size": 17758, + "lfs_oid": null, + "omitted": false, + "sha256": "0414d22a1c07da70cee3d7bbd7e5a6770d1cff2aa69eaf884b442c6e029c1783" + }, + { + "path": "am_renewal_outreach_002/reward_label.json", + "size": 26362, + "lfs_oid": null, + "omitted": false, + "sha256": "46875d21eb8909bef8711765a02894cae0cba756af13ec4226c1718d115f8f8f" + }, + { + "path": "am_renewal_tracker_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "am_renewal_tracker_003/initial_setup.py", + "size": 22146, + "lfs_oid": null, + "omitted": false, + "sha256": "38f5c5f6e082f2039d4225ce26ed310059a69453fb17b6b6e981cba3595f8224" + }, + { + "path": "am_renewal_tracker_003/reward.py", + "size": 15767, + "lfs_oid": null, + "omitted": false, + "sha256": "08c711b7a8280aab473f81315b45ee018d3259bd892fd4446aea025275ed98e6" + }, + { + "path": "am_renewal_tracker_003/reward_label.json", + "size": 15423, + "lfs_oid": null, + "omitted": false, + "sha256": "e8e8f76bf988d8193fc71fb1c0438eafe81a8eecba0ab215d92b517d8c4f46f8" + }, + { + "path": "ar_aging_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_aging_001/initial_setup.py", + "size": 8981, + "lfs_oid": null, + "omitted": false, + "sha256": "951140b46d583e20e0d44d68ff0085abe91c21938d076042662013186e129fb3" + }, + { + "path": "ar_aging_001/reward.py", + "size": 8062, + "lfs_oid": null, + "omitted": false, + "sha256": "75680854e92e6290dfeeca3d50690f5a35373efbe0b5cc90f740b75efe026565" + }, + { + "path": "ar_aging_001/reward_label.json", + "size": 15073, + "lfs_oid": null, + "omitted": false, + "sha256": "996eeb56e6c550a0bcca8c551d202addd58eea7540cbd0ddd97b64e991a6f297" + }, + { + "path": "ar_approval_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_approval_002/initial_setup.py", + "size": 9984, + "lfs_oid": null, + "omitted": false, + "sha256": "8ddaa927a7792a9d55e5de506ae0880c9585831787063b239743fe514a395b0a" + }, + { + "path": "ar_approval_002/reward.py", + "size": 8371, + "lfs_oid": null, + "omitted": false, + "sha256": "fd5e9483b1ded6d4c4ee54f2db4fd55d332b1edfb55357b7a5d1425ec7f9d079" + }, + { + "path": "ar_approval_002/reward_label.json", + "size": 17668, + "lfs_oid": null, + "omitted": false, + "sha256": "baf0dbb6b9a9bbc0d2c70bd18bf3bffefcad76579f57778a50f904221ab9c278" + }, + { + "path": "ar_billing_exception_012__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_billing_exception_012__long/initial_setup.py", + "size": 43075, + "lfs_oid": null, + "omitted": false, + "sha256": "0871eaa2c070477f3fa982be5713347546c09bed1cfaaf2b06d1b18ea11ba80c" + }, + { + "path": "ar_billing_exception_012__long/reward.py", + "size": 25058, + "lfs_oid": null, + "omitted": false, + "sha256": "feef8701c97fab5eeaed3d0b3bbf10258d59da9f3340661805af63b8d75cad4d" + }, + { + "path": "ar_churn_refund_009__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_churn_refund_009__long/initial_setup.py", + "size": 34153, + "lfs_oid": null, + "omitted": false, + "sha256": "a7ead2b478adb346f5e80f7fc2a3a0e993f9455fa23827a84026ae5e4693089d" + }, + { + "path": "ar_churn_refund_009__long/reward.py", + "size": 22258, + "lfs_oid": null, + "omitted": false, + "sha256": "eb138423ed18a760ecf9efe10309d55d38448b75c79d2c87124b002b32400dcf" + }, + { + "path": "ar_closeout_006/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_closeout_006/initial_setup.py", + "size": 31599, + "lfs_oid": null, + "omitted": false, + "sha256": "7a0a1ab695544ca2a1ca8f971c16c8f4cae2afef3b8745f6efa11142a3e45d6a" + }, + { + "path": "ar_closeout_006/reward.py", + "size": 20947, + "lfs_oid": null, + "omitted": false, + "sha256": "e20daaf646f775d50ab6eeacbdad01394e7552a52f9f4732164f77a66007b2ce" + }, + { + "path": "ar_closeout_006/reward_label.json", + "size": 2959, + "lfs_oid": null, + "omitted": false, + "sha256": "c82a9e3ffebbcff53861467cba4d5fb75b90cb37e07873baada11d9b502482e5" + }, + { + "path": "ar_deal_to_invoice_007__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_deal_to_invoice_007__long/initial_setup.py", + "size": 29492, + "lfs_oid": null, + "omitted": false, + "sha256": "5c165165f00b3a8e9c91e6a8a312d1a9c3dccd89297e24dfd1b36e5eb1d1ca21" + }, + { + "path": "ar_deal_to_invoice_007__long/reward.py", + "size": 28110, + "lfs_oid": null, + "omitted": false, + "sha256": "7cf567da14f936f708f7af62b305ccf2d8f7a17344eb25d660df1a4fd641f614" + }, + { + "path": "ar_invoice_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_invoice_003/initial_setup.py", + "size": 13087, + "lfs_oid": null, + "omitted": false, + "sha256": "0a761678761d8f6298fb393d14016db4e0851b62e83d680ea140298c0f55c9e0" + }, + { + "path": "ar_invoice_003/reward.py", + "size": 12780, + "lfs_oid": null, + "omitted": false, + "sha256": "754d7ac36aff95943919380a2cca01b11f984df16113ed023423b126b3449eab" + }, + { + "path": "ar_invoice_003/reward_label.json", + "size": 10297, + "lfs_oid": null, + "omitted": false, + "sha256": "23a4beeb96bbcda9f2af2a9f1245412f9599d7bc3bad71ad380c1524b41513dd" + }, + { + "path": "ar_payment_004/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_payment_004/initial_setup.py", + "size": 13999, + "lfs_oid": null, + "omitted": false, + "sha256": "f5fb70d63bfb12fe6c9300a85fe58ce60f1868064b815af61c1ed2725da6d534" + }, + { + "path": "ar_payment_004/reward.py", + "size": 8959, + "lfs_oid": null, + "omitted": false, + "sha256": "d18df8e3727f6cb87d0f8f96b60e1fb6feb056cce1af2cd8a7fb26b8df6126ae" + }, + { + "path": "ar_payment_004/reward_label.json", + "size": 17520, + "lfs_oid": null, + "omitted": false, + "sha256": "1a8ffb0121cb2d142690da93f0adcdae5a459cd4c02e359f24a9eea06fa8bff4" + }, + { + "path": "ar_payment_alert_010__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_payment_alert_010__long/initial_setup.py", + "size": 45248, + "lfs_oid": null, + "omitted": false, + "sha256": "606306a8c56f92d80aca75fff15d8117b3fbb4ddb5831a8581ea8802a1e56237" + }, + { + "path": "ar_payment_alert_010__long/reward.py", + "size": 26542, + "lfs_oid": null, + "omitted": false, + "sha256": "74ca480be87d76911dafaeb323ac4199e54cb7ba9510358a547f381850100435" + }, + { + "path": "ar_remittance_008__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_remittance_008__long/initial_setup.py", + "size": 27884, + "lfs_oid": null, + "omitted": false, + "sha256": "d5b95df5ae07ac3cbe32d867a2b3de6ebca7d912ca90c22139b306ea282da727" + }, + { + "path": "ar_remittance_008__long/reward.py", + "size": 25036, + "lfs_oid": null, + "omitted": false, + "sha256": "fa0de74d811dd0d39e9131cce81f127882aceddb906f1368f8dabd6a635b7b50" + }, + { + "path": "ar_signature_005/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_signature_005/initial_setup.py", + "size": 17393, + "lfs_oid": null, + "omitted": false, + "sha256": "d8e416d885a8ecda3548d219f909e5a93084d5d706a25780e77ad0cc1eafc22c" + }, + { + "path": "ar_signature_005/reward.py", + "size": 7597, + "lfs_oid": null, + "omitted": false, + "sha256": "95f3ed1295645069122cc341df00ac1fad452b16261ddb40193bb6fa86d36606" + }, + { + "path": "ar_signature_005/reward_label.json", + "size": 18516, + "lfs_oid": null, + "omitted": false, + "sha256": "96f9ad7031b95db539d8c1e220d6f4a9e98516d7f263ddd38fd57785abd6abb0" + }, + { + "path": "ar_stripe_reconcile_011__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ar_stripe_reconcile_011__long/initial_setup.py", + "size": 27642, + "lfs_oid": null, + "omitted": false, + "sha256": "84eae87539f57448f0f554a880703b35a962f2a1ded951fc1ec432efdbd624e9" + }, + { + "path": "ar_stripe_reconcile_011__long/reward.py", + "size": 19334, + "lfs_oid": null, + "omitted": false, + "sha256": "92e684943c7b605e42c8e5ff9cffcc38df91374e61005ad1943fa2765978f7cd" + }, + { + "path": "calc_boomerang_sales_004__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "calc_boomerang_sales_004__long/338372e2-5164-5bba-be72-3024f425418f_BoomerangSales_4.xlsx", + "size": 12387, + "lfs_oid": null, + "omitted": false, + "sha256": "9962eddeb2e47c89d67374922dce5065a65e233bd806eb024506b4c6647bd6b2" + }, + { + "path": "calc_boomerang_sales_004__long/3c734b28-876f-590a-8a9b-a7dea013cdd9_BoomerangSales_5.xlsx", + "size": 12387, + "lfs_oid": null, + "omitted": false, + "sha256": "9962eddeb2e47c89d67374922dce5065a65e233bd806eb024506b4c6647bd6b2" + }, + { + "path": "calc_boomerang_sales_004__long/6_BoomerangSales_gt1_1.xlsx", + "size": 18482, + "lfs_oid": null, + "omitted": false, + "sha256": "6b8bc4c4996c9137093259752be2886deec297f8d0b34b6169e188def48d401a" + }, + { + "path": "calc_boomerang_sales_004__long/6_BoomerangSales_gt1_2.xlsx", + "size": 18482, + "lfs_oid": null, + "omitted": false, + "sha256": "6b8bc4c4996c9137093259752be2886deec297f8d0b34b6169e188def48d401a" + }, + { + "path": "calc_boomerang_sales_004__long/6_BoomerangSales_gt1_3.xlsx", + "size": 18482, + "lfs_oid": null, + "omitted": false, + "sha256": "6b8bc4c4996c9137093259752be2886deec297f8d0b34b6169e188def48d401a" + }, + { + "path": "calc_boomerang_sales_004__long/6_BoomerangSales_gt1_4.xlsx", + "size": 18482, + "lfs_oid": null, + "omitted": false, + "sha256": "6b8bc4c4996c9137093259752be2886deec297f8d0b34b6169e188def48d401a" + }, + { + "path": "calc_boomerang_sales_004__long/6_BoomerangSales_gt1_5.xlsx", + "size": 18482, + "lfs_oid": null, + "omitted": false, + "sha256": "6b8bc4c4996c9137093259752be2886deec297f8d0b34b6169e188def48d401a" + }, + { + "path": "calc_boomerang_sales_004__long/7594f1e5-2945-5a98-9eec-5aac2e8aaf1b_BoomerangSales_3.xlsx", + "size": 12387, + "lfs_oid": null, + "omitted": false, + "sha256": "9962eddeb2e47c89d67374922dce5065a65e233bd806eb024506b4c6647bd6b2" + }, + { + "path": "calc_boomerang_sales_004__long/b9ee9e4b-d3c9-5341-a797-ba31c5448117_BoomerangSales_1.xlsx", + "size": 12387, + "lfs_oid": null, + "omitted": false, + "sha256": "9962eddeb2e47c89d67374922dce5065a65e233bd806eb024506b4c6647bd6b2" + }, + { + "path": "calc_boomerang_sales_004__long/e22b8fec-7bed-5cb0-a402-a977fa125750_BoomerangSales_2.xlsx", + "size": 12387, + "lfs_oid": null, + "omitted": false, + "sha256": "9962eddeb2e47c89d67374922dce5065a65e233bd806eb024506b4c6647bd6b2" + }, + { + "path": "calc_employee_roles_003__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "calc_employee_roles_003__long/2b91e566-64fb-51d8-90c6-e534370d1020_Employee_Roles_and_Ranks_1.xlsx", + "size": 5902, + "lfs_oid": null, + "omitted": false, + "sha256": "55a78a8f2469d28c3fcb4e417e615bb6c65a65094243c973cc3b1524162ab269" + }, + { + "path": "calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_1.xlsx", + "size": 6448, + "lfs_oid": null, + "omitted": false, + "sha256": "4546a6e6f815f352a598c049df91746e85e597652b9681049b4cd2eb9ac4d837" + }, + { + "path": "calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_2.xlsx", + "size": 6448, + "lfs_oid": null, + "omitted": false, + "sha256": "4546a6e6f815f352a598c049df91746e85e597652b9681049b4cd2eb9ac4d837" + }, + { + "path": "calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_3.xlsx", + "size": 6448, + "lfs_oid": null, + "omitted": false, + "sha256": "4546a6e6f815f352a598c049df91746e85e597652b9681049b4cd2eb9ac4d837" + }, + { + "path": "calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_4.xlsx", + "size": 6448, + "lfs_oid": null, + "omitted": false, + "sha256": "4546a6e6f815f352a598c049df91746e85e597652b9681049b4cd2eb9ac4d837" + }, + { + "path": "calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_5.xlsx", + "size": 6448, + "lfs_oid": null, + "omitted": false, + "sha256": "4546a6e6f815f352a598c049df91746e85e597652b9681049b4cd2eb9ac4d837" + }, + { + "path": "calc_employee_roles_003__long/cfebbe10-8574-50f8-89ac-4adbc38c6713_Employee_Roles_and_Ranks_2.xlsx", + "size": 5902, + "lfs_oid": null, + "omitted": false, + "sha256": "55a78a8f2469d28c3fcb4e417e615bb6c65a65094243c973cc3b1524162ab269" + }, + { + "path": "calc_employee_roles_003__long/d2218574-2113-5bc6-9304-dd4fc048bb44_Employee_Roles_and_Ranks_5.xlsx", + "size": 5902, + "lfs_oid": null, + "omitted": false, + "sha256": "55a78a8f2469d28c3fcb4e417e615bb6c65a65094243c973cc3b1524162ab269" + }, + { + "path": "calc_employee_roles_003__long/d7bc84eb-e864-507e-a3bb-11f4b5a44d58_Employee_Roles_and_Ranks_4.xlsx", + "size": 5902, + "lfs_oid": null, + "omitted": false, + "sha256": "55a78a8f2469d28c3fcb4e417e615bb6c65a65094243c973cc3b1524162ab269" + }, + { + "path": "calc_employee_roles_003__long/f1da68fd-9e78-5d2b-983d-166ae7f7607b_Employee_Roles_and_Ranks_3.xlsx", + "size": 5902, + "lfs_oid": null, + "omitted": false, + "sha256": "55a78a8f2469d28c3fcb4e417e615bb6c65a65094243c973cc3b1524162ab269" + }, + { + "path": "calc_income_statement_001__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "calc_income_statement_001__long/10da84b0-f0cf-58ff-b185-1c101d3b8b00_IncomeStatement2_1.xlsx", + "size": 9941, + "lfs_oid": null, + "omitted": false, + "sha256": "8f9da5481c2bcefefebae562e037a71b5b93163ff6b48295fd4df30b86cf8279" + }, + { + "path": "calc_income_statement_001__long/350e50bf-8624-51bc-91b7-a8dd0462e518_IncomeStatement2_2.xlsx", + "size": 9941, + "lfs_oid": null, + "omitted": false, + "sha256": "8f9da5481c2bcefefebae562e037a71b5b93163ff6b48295fd4df30b86cf8279" + }, + { + "path": "calc_income_statement_001__long/4429656d-69b9-58f3-af62-b51df1b7a682_IncomeStatement2_4.xlsx", + "size": 9941, + "lfs_oid": null, + "omitted": false, + "sha256": "8f9da5481c2bcefefebae562e037a71b5b93163ff6b48295fd4df30b86cf8279" + }, + { + "path": "calc_income_statement_001__long/5_IncomeStatement2_gt1_1.xlsx", + "size": 10555, + "lfs_oid": null, + "omitted": false, + "sha256": "dce5ec128f2fcb633591ce430f73dc6a1f5041fa2e003fca42af2cb89d2ad0a9" + }, + { + "path": "calc_income_statement_001__long/5_IncomeStatement2_gt1_2.xlsx", + "size": 10555, + "lfs_oid": null, + "omitted": false, + "sha256": "dce5ec128f2fcb633591ce430f73dc6a1f5041fa2e003fca42af2cb89d2ad0a9" + }, + { + "path": "calc_income_statement_001__long/5_IncomeStatement2_gt1_3.xlsx", + "size": 10555, + "lfs_oid": null, + "omitted": false, + "sha256": "dce5ec128f2fcb633591ce430f73dc6a1f5041fa2e003fca42af2cb89d2ad0a9" + }, + { + "path": "calc_income_statement_001__long/5_IncomeStatement2_gt1_4.xlsx", + "size": 10555, + "lfs_oid": null, + "omitted": false, + "sha256": "dce5ec128f2fcb633591ce430f73dc6a1f5041fa2e003fca42af2cb89d2ad0a9" + }, + { + "path": "calc_income_statement_001__long/5_IncomeStatement2_gt1_5.xlsx", + "size": 10555, + "lfs_oid": null, + "omitted": false, + "sha256": "dce5ec128f2fcb633591ce430f73dc6a1f5041fa2e003fca42af2cb89d2ad0a9" + }, + { + "path": "calc_income_statement_001__long/876296d5-884d-51ad-b5dd-285374e43ac4_IncomeStatement2_5.xlsx", + "size": 9941, + "lfs_oid": null, + "omitted": false, + "sha256": "8f9da5481c2bcefefebae562e037a71b5b93163ff6b48295fd4df30b86cf8279" + }, + { + "path": "calc_income_statement_001__long/93be5864-b16f-5f70-8d80-1a515dedf794_IncomeStatement2_3.xlsx", + "size": 9941, + "lfs_oid": null, + "omitted": false, + "sha256": "8f9da5481c2bcefefebae562e037a71b5b93163ff6b48295fd4df30b86cf8279" + }, + { + "path": "calc_sales_rep_002__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "calc_sales_rep_002__long/0b920aed-a86f-552f-8c4e-4230d20fb019_SalesRep_3.xlsx", + "size": 9500, + "lfs_oid": null, + "omitted": false, + "sha256": "f4e54c5b2394e7c7dc5975d1f0bea29f93227aa435827d6649ce86b64734428f" + }, + { + "path": "calc_sales_rep_002__long/3_SalesRep_gt1_1.xlsx", + "size": 10094, + "lfs_oid": null, + "omitted": false, + "sha256": "36aeeb9844db1b4ca03e5e736773ad62088757eb37694ff452464f774c9b0b28" + }, + { + "path": "calc_sales_rep_002__long/3_SalesRep_gt1_2.xlsx", + "size": 10094, + "lfs_oid": null, + "omitted": false, + "sha256": "36aeeb9844db1b4ca03e5e736773ad62088757eb37694ff452464f774c9b0b28" + }, + { + "path": "calc_sales_rep_002__long/3_SalesRep_gt1_3.xlsx", + "size": 10094, + "lfs_oid": null, + "omitted": false, + "sha256": "36aeeb9844db1b4ca03e5e736773ad62088757eb37694ff452464f774c9b0b28" + }, + { + "path": "calc_sales_rep_002__long/3_SalesRep_gt1_4.xlsx", + "size": 10094, + "lfs_oid": null, + "omitted": false, + "sha256": "36aeeb9844db1b4ca03e5e736773ad62088757eb37694ff452464f774c9b0b28" + }, + { + "path": "calc_sales_rep_002__long/3_SalesRep_gt1_5.xlsx", + "size": 10094, + "lfs_oid": null, + "omitted": false, + "sha256": "36aeeb9844db1b4ca03e5e736773ad62088757eb37694ff452464f774c9b0b28" + }, + { + "path": "calc_sales_rep_002__long/5e509850-8212-5d6a-958f-c2d16aee6ceb_SalesRep_4.xlsx", + "size": 9500, + "lfs_oid": null, + "omitted": false, + "sha256": "f4e54c5b2394e7c7dc5975d1f0bea29f93227aa435827d6649ce86b64734428f" + }, + { + "path": "calc_sales_rep_002__long/6c32f05d-1532-5354-a3db-ac954dd7d2ca_SalesRep_1.xlsx", + "size": 9500, + "lfs_oid": null, + "omitted": false, + "sha256": "f4e54c5b2394e7c7dc5975d1f0bea29f93227aa435827d6649ce86b64734428f" + }, + { + "path": "calc_sales_rep_002__long/dd7e65b9-bfb4-542a-adf9-13c4153016fc_SalesRep_2.xlsx", + "size": 9500, + "lfs_oid": null, + "omitted": false, + "sha256": "f4e54c5b2394e7c7dc5975d1f0bea29f93227aa435827d6649ce86b64734428f" + }, + { + "path": "calc_sales_rep_002__long/e5d3b713-bd13-5796-83bc-ab47351ba44c_SalesRep_5.xlsx", + "size": 9500, + "lfs_oid": null, + "omitted": false, + "sha256": "f4e54c5b2394e7c7dc5975d1f0bea29f93227aa435827d6649ce86b64734428f" + }, + { + "path": "calc_student_grades_005__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "calc_student_grades_005__long/0a94aee5-1a46-57a5-b453-2402af0ffede_Student_Grades_and_Remarks_4.xlsx", + "size": 6124, + "lfs_oid": null, + "omitted": false, + "sha256": "014f9f32109a44669ec3fb4bc7d4becf93ea5622cfe208100a2783851d887aa0" + }, + { + "path": "calc_student_grades_005__long/26aa94e9-ffcf-57a5-b2dd-e92752c4b57f_Student_Grades_and_Remarks_2.xlsx", + "size": 6124, + "lfs_oid": null, + "omitted": false, + "sha256": "014f9f32109a44669ec3fb4bc7d4becf93ea5622cfe208100a2783851d887aa0" + }, + { + "path": "calc_student_grades_005__long/639ca2f8-0ba9-5a67-b827-a64f4cd425b5_Student_Grades_and_Remarks_3.xlsx", + "size": 6124, + "lfs_oid": null, + "omitted": false, + "sha256": "014f9f32109a44669ec3fb4bc7d4becf93ea5622cfe208100a2783851d887aa0" + }, + { + "path": "calc_student_grades_005__long/914ebed1-4ae1-5a3e-b9ab-bbbfe8206f7b_Student_Grades_and_Remarks_1.xlsx", + "size": 6124, + "lfs_oid": null, + "omitted": false, + "sha256": "014f9f32109a44669ec3fb4bc7d4becf93ea5622cfe208100a2783851d887aa0" + }, + { + "path": "calc_student_grades_005__long/Student_Grades_and_Remarks_gold_1.xlsx", + "size": 8823, + "lfs_oid": null, + "omitted": false, + "sha256": "5dc811582827f43111a5d6ab442f6d49a784b6b01afed2bca3af8b385fe23478" + }, + { + "path": "calc_student_grades_005__long/Student_Grades_and_Remarks_gold_2.xlsx", + "size": 8823, + "lfs_oid": null, + "omitted": false, + "sha256": "5dc811582827f43111a5d6ab442f6d49a784b6b01afed2bca3af8b385fe23478" + }, + { + "path": "calc_student_grades_005__long/Student_Grades_and_Remarks_gold_3.xlsx", + "size": 8823, + "lfs_oid": null, + "omitted": false, + "sha256": "5dc811582827f43111a5d6ab442f6d49a784b6b01afed2bca3af8b385fe23478" + }, + { + "path": "calc_student_grades_005__long/Student_Grades_and_Remarks_gold_4.xlsx", + "size": 8823, + "lfs_oid": null, + "omitted": false, + "sha256": "5dc811582827f43111a5d6ab442f6d49a784b6b01afed2bca3af8b385fe23478" + }, + { + "path": "calc_student_grades_005__long/Student_Grades_and_Remarks_gold_5.xlsx", + "size": 8823, + "lfs_oid": null, + "omitted": false, + "sha256": "5dc811582827f43111a5d6ab442f6d49a784b6b01afed2bca3af8b385fe23478" + }, + { + "path": "calc_student_grades_005__long/f4dfeace-a9ac-57e3-9cb7-b78690026317_Student_Grades_and_Remarks_5.xlsx", + "size": 6124, + "lfs_oid": null, + "omitted": false, + "sha256": "014f9f32109a44669ec3fb4bc7d4becf93ea5622cfe208100a2783851d887aa0" + }, + { + "path": "csm_escalation_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csm_escalation_001/initial_setup.py", + "size": 32071, + "lfs_oid": null, + "omitted": false, + "sha256": "198a983d20c33ecfa216f65608e95b70ccb7421f5272d7c51226d2b7114928de" + }, + { + "path": "csm_escalation_001/reward.py", + "size": 20187, + "lfs_oid": null, + "omitted": false, + "sha256": "acea819a94ebcacf10f52fa16e4a557533b7e9d14347703005927235486b0de1" + }, + { + "path": "csm_escalation_001/reward_label.json", + "size": 22890, + "lfs_oid": null, + "omitted": false, + "sha256": "592a8eaf8282cd5536cfb389ab6e75d2952380ab1243f05c00bc11331fc0b83b" + }, + { + "path": "csm_health_risk_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csm_health_risk_002/initial_setup.py", + "size": 24690, + "lfs_oid": null, + "omitted": false, + "sha256": "2233aaa3e202e832ed6613457616c9356efb665a2510489ca7f0c386fe6d971f" + }, + { + "path": "csm_health_risk_002/reward.py", + "size": 16271, + "lfs_oid": null, + "omitted": false, + "sha256": "8755792870f6889e159ca69e853f040ae5df74d6b06206c1bdb235de5256ed43" + }, + { + "path": "csm_health_risk_002/reward_label.json", + "size": 24719, + "lfs_oid": null, + "omitted": false, + "sha256": "a68f7a29c6b90ce7e293372a41072bfa17c56f2f797a200ab1ff9b24158b2ba0" + }, + { + "path": "csm_onboarding_checklist_004/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csm_onboarding_checklist_004/initial_setup.py", + "size": 15971, + "lfs_oid": null, + "omitted": false, + "sha256": "433e01607151dc61c090a88aefdce3b97665a648ce80f310a7dfb50b8d6d8cbf" + }, + { + "path": "csm_onboarding_checklist_004/reward.py", + "size": 5923, + "lfs_oid": null, + "omitted": false, + "sha256": "3fd3b86bf7b633731f019a88714e3c5c7d0e55c3b2967e1c7879fd16128db05d" + }, + { + "path": "csm_onboarding_checklist_004/reward_label.json", + "size": 18243, + "lfs_oid": null, + "omitted": false, + "sha256": "9de107dcf4ab2bd1fcfea2387551b959530ce0ccf7b41953832755dfe37f035a" + }, + { + "path": "csm_qbr_renewal_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csm_qbr_renewal_003/initial_setup.py", + "size": 34387, + "lfs_oid": null, + "omitted": false, + "sha256": "19d7504594ca2ebe6dc74b1a3c4b92d2fd2d36efee235389f6b7ebd6248c90d6" + }, + { + "path": "csm_qbr_renewal_003/reward.py", + "size": 13208, + "lfs_oid": null, + "omitted": false, + "sha256": "81629b9ce65373fa3a4cb40880f3447b97f9e06183d4a4f5418b07d8b9fd7fbc" + }, + { + "path": "csm_qbr_renewal_003/reward_label.json", + "size": 27020, + "lfs_oid": null, + "omitted": false, + "sha256": "bc6421cf6afcf69820e7837a89f576e9dc8088290bb77caa9bfbbf72fa7b3236" + }, + { + "path": "csm_training_rate_005/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csm_training_rate_005/initial_setup.py", + "size": 18043, + "lfs_oid": null, + "omitted": false, + "sha256": "907f97e236a443fb8f0960686d670e0293e7fef10fbb6a190174fc1aec8509b2" + }, + { + "path": "csm_training_rate_005/reward.py", + "size": 3173, + "lfs_oid": null, + "omitted": false, + "sha256": "24b92137ebaa2c00b79bfdc1b5a89a33214c189a4327e302231ebdf20c37c437" + }, + { + "path": "csm_training_rate_005/reward_label.json", + "size": 11059, + "lfs_oid": null, + "omitted": false, + "sha256": "b254dfcd1d756a99c7c575c9da0eb02682475d66fb7efd22c64eccccfb8ed5a0" + }, + { + "path": "csops_email_to_crm_case_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csops_email_to_crm_case_001/initial_setup.py", + "size": 27404, + "lfs_oid": null, + "omitted": false, + "sha256": "8f335cb24dd8fb4927259ca7eb9396dd9647bc7bd75dd7227efe5d383d762523" + }, + { + "path": "csops_email_to_crm_case_001/reward.py", + "size": 18261, + "lfs_oid": null, + "omitted": false, + "sha256": "61f9f0b30246084e80649a4ca79231bc1bbe9be230ec721624a14bd060c92444" + }, + { + "path": "csops_email_to_crm_case_001/reward_label.json", + "size": 23514, + "lfs_oid": null, + "omitted": false, + "sha256": "04d37060cc7957eb02babe4dc8bcb74c525f00bda3e41dd388259b4381ba43ac" + }, + { + "path": "csops_inbox_triage_006__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csops_inbox_triage_006__long/initial_setup.py", + "size": 34286, + "lfs_oid": null, + "omitted": false, + "sha256": "cca433a97b70d598c6f80dcceee5c493eef784fdaf0230e3e311ea5cf7b8626c" + }, + { + "path": "csops_inbox_triage_006__long/reward.py", + "size": 24579, + "lfs_oid": null, + "omitted": false, + "sha256": "a7bd532314226e24b25cccb77d8f87293ae8212d0e8bd67ef6b583da35606b81" + }, + { + "path": "csops_incident_command_004__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csops_incident_command_004__long/initial_setup.py", + "size": 29934, + "lfs_oid": null, + "omitted": false, + "sha256": "506e7a902112f353f16d3772baa73f46b75513214abca68488ed5eeb7d28d5ff" + }, + { + "path": "csops_incident_command_004__long/reward.py", + "size": 8508, + "lfs_oid": null, + "omitted": false, + "sha256": "a330f7b00287d3a7079fa48cbff864e52ba78feae999fc5ae7c07f93aafc94e3" + }, + { + "path": "csops_p1_incident_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csops_p1_incident_002/initial_setup.py", + "size": 28518, + "lfs_oid": null, + "omitted": false, + "sha256": "2962d04f53c251613b722b56e26ecbe5219910f23f142a9fa17526d8a1b466c3" + }, + { + "path": "csops_p1_incident_002/reward.py", + "size": 20309, + "lfs_oid": null, + "omitted": false, + "sha256": "2eba6df8e5aaba5312253d849de5234d84267509c1017ac2fc83da63aac6b03d" + }, + { + "path": "csops_p1_incident_002/reward_label.json", + "size": 30193, + "lfs_oid": null, + "omitted": false, + "sha256": "baf6a073b9930c0f5b56ecaad0b8933cff3585e45c304330c29abf5d3495af97" + }, + { + "path": "csops_sla_queue_triage_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csops_sla_queue_triage_003/initial_setup.py", + "size": 30827, + "lfs_oid": null, + "omitted": false, + "sha256": "ae50cb4bc26d8c369eecbb149c604538494c2c3dc9e68674647f95c9b2a387ed" + }, + { + "path": "csops_sla_queue_triage_003/reward.py", + "size": 22744, + "lfs_oid": null, + "omitted": false, + "sha256": "5344a87f6281389d2cef2db58957acb88bfb6a21cef062047d1ab8925fb03464" + }, + { + "path": "csops_sla_queue_triage_003/reward_label.json", + "size": 20743, + "lfs_oid": null, + "omitted": false, + "sha256": "4896c6d9db08d2d20bddc4c7a586da7e6f59d5726d4aac1bcd712828678b33d2" + }, + { + "path": "csops_ticket_queue_005__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "csops_ticket_queue_005__long/initial_setup.py", + "size": 35553, + "lfs_oid": null, + "omitted": false, + "sha256": "d1eb14158d1f165ff9250e3b7752931b726792d80a9fe12b83b2107737b77ca5" + }, + { + "path": "csops_ticket_queue_005__long/reward.py", + "size": 13948, + "lfs_oid": null, + "omitted": false, + "sha256": "6b98e83c329e8bd75985e23ebfc4da946d4ba30e4d550732e07c33e9a1e08f6e" + }, + { + "path": "fin_expense_claim_001__long__cond/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "fin_expense_claim_001__long__cond/19c19c59-8dab-5287-9f11-546056a463b0_oa_server.py", + "size": 33884, + "lfs_oid": null, + "omitted": false, + "sha256": "f5d7ad61d32c1b4d0e657610c8d4b7d7ee997b76c2023608384a0962d30062ba" + }, + { + "path": "fin_expense_claim_001__long__cond/87712b8f-fa0d-5df1-8c79-dd0c877ab6a7_invoice_2.pdf", + "size": 2112, + "lfs_oid": null, + "omitted": false, + "sha256": "7349f1b374f1e0c4c53cd2236cb23d0dbd9f4f527094c951b4c1d6e160a5b58d" + }, + { + "path": "fin_expense_claim_001__long__cond/8fc9101a-9ae0-52e6-9d9f-6cf7033d05ff_invoice_1.pdf", + "size": 2111, + "lfs_oid": null, + "omitted": false, + "sha256": "9b78fcf4f4fa80b8ceed3f43eccb4490757766c4e80b56d577749ca7ba5a57cf" + }, + { + "path": "fin_expense_claim_001__long__cond/ef610de1-d103-514c-9ddd-9fda1b34d5c2_mentor_id_and_approval_code.xlsx", + "size": 4971, + "lfs_oid": null, + "omitted": false, + "sha256": "9fddddfe0bc8f418a85a4e785cc63599e9a74c6256c68d5c9598e92de1404ee1" + }, + { + "path": "fin_expense_claim_002__long__cond/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "fin_expense_claim_002__long__cond/0a7fc64f-9ca0-54e1-90d0-9bdb1fea4b10_oa_server.py", + "size": 33884, + "lfs_oid": null, + "omitted": false, + "sha256": "f5d7ad61d32c1b4d0e657610c8d4b7d7ee997b76c2023608384a0962d30062ba" + }, + { + "path": "fin_expense_claim_002__long__cond/5cb11caa-90fb-53cc-9f6b-1489523366db_manager_approval.pdf", + "size": 2209, + "lfs_oid": null, + "omitted": false, + "sha256": "0bf46f2f1a8026cb9a0a0532bb312978e11a09215c506316154a0f097e703957" + }, + { + "path": "fin_expense_claim_002__long__cond/999fca2d-ceec-581b-9623-500d62780607_invoice_1.pdf", + "size": 2113, + "lfs_oid": null, + "omitted": false, + "sha256": "60af1edf62c814e6a3278f9ea1b8d58b6cd97a617001ca54d899364a54a8acce" + }, + { + "path": "fin_expense_claim_002__long__cond/c97f91fe-8f04-5f0f-a397-971c012d254d_invoice_2.pdf", + "size": 2114, + "lfs_oid": null, + "omitted": false, + "sha256": "4250a063adb77f8505f3365859ef251aac3c1bb1d033398ed554c49f5b8fc2df" + }, + { + "path": "fin_expense_claim_002__long__cond/ce9481c5-7ab8-50e7-a97b-0f4f833ad690_justification.txt", + "size": 499, + "lfs_oid": null, + "omitted": false, + "sha256": "d07152177f4c1d63f304627db484b6b0b2a3a90541b16f1d3e69320770f8a65b" + }, + { + "path": "hr_it_provisioning_008__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_it_provisioning_008__long/initial_setup.py", + "size": 30508, + "lfs_oid": null, + "omitted": false, + "sha256": "7182b6d5efcf9fb6175b8a4481789650ad02ddbf7a0fda6ea528afd619d95426" + }, + { + "path": "hr_it_provisioning_008__long/reward.py", + "size": 9963, + "lfs_oid": null, + "omitted": false, + "sha256": "ea842c918a1d99c630a8b30321640af7afe0e79fb6216f8fd101668c9c12315c" + }, + { + "path": "hr_midyear_review_007__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_midyear_review_007__long/initial_setup.py", + "size": 38649, + "lfs_oid": null, + "omitted": false, + "sha256": "35709eb2911309013c88f6eed3734161f314dd9354a5ba9e240e57e4c01934bf" + }, + { + "path": "hr_midyear_review_007__long/reward.py", + "size": 12862, + "lfs_oid": null, + "omitted": false, + "sha256": "2bab03436985e064d846d61361dc848a953c9bbd850b049e74ef92d616d96f6b" + }, + { + "path": "hr_onboarding_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_onboarding_003/initial_setup.py", + "size": 9103, + "lfs_oid": null, + "omitted": false, + "sha256": "46abda020e9a134faa48246f130b1e9967db6ea5d0ad837012d310a3449e2db0" + }, + { + "path": "hr_onboarding_003/reward.py", + "size": 6090, + "lfs_oid": null, + "omitted": false, + "sha256": "26c1214bd7242ff30fc7fc974b6e07ad6afefed3ab55daba903535071ef0a014" + }, + { + "path": "hr_onboarding_003/reward_label.json", + "size": 18485, + "lfs_oid": null, + "omitted": false, + "sha256": "4e735706b2340ed68913a044a2bfdc3b7be38839506b445fa46f378c9f44867d" + }, + { + "path": "hr_onboarding_checklist_004/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_onboarding_checklist_004/initial_setup.py", + "size": 8449, + "lfs_oid": null, + "omitted": false, + "sha256": "c6b86bd0006be35ee2a404a4148a733aec3c7be54788b8ccda64a97b63f479ce" + }, + { + "path": "hr_onboarding_checklist_004/reward.py", + "size": 7769, + "lfs_oid": null, + "omitted": false, + "sha256": "747775fa7ea32328f3667cdea57f12804cc9d538f49ae8301aa082f59f095bc6" + }, + { + "path": "hr_onboarding_checklist_004/reward_label.json", + "size": 13365, + "lfs_oid": null, + "omitted": false, + "sha256": "9b2746375cea88634b39bf2c8781990d51e1efe2ad1b03f7f3b0cf197fa62019" + }, + { + "path": "hr_one_on_one_009/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_one_on_one_009/initial_setup.py", + "size": 183735, + "lfs_oid": null, + "omitted": false, + "sha256": "ca31e3f90b43bb8e3ccc761cabeeeb783e37c6723f4de414b2c406dfc9ec6b5c" + }, + { + "path": "hr_one_on_one_009/reward.py", + "size": 4994, + "lfs_oid": null, + "omitted": false, + "sha256": "e28b67b816eb14eba8d0b4a263cd4a2a998dc247f956226cf4976fabc38c94c8" + }, + { + "path": "hr_one_on_one_009/reward_label.json", + "size": 19734, + "lfs_oid": null, + "omitted": false, + "sha256": "4c0f631b7bdf0ec738baf4df7fab63d321fb7774dd5ab107169ee5493ca07c6b" + }, + { + "path": "hr_payroll_approval_006__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_payroll_approval_006__long/initial_setup.py", + "size": 37284, + "lfs_oid": null, + "omitted": false, + "sha256": "b7acb65b4f3838a770e08e16b6ed998f146dd9addb6da0a283286143d0b188de" + }, + { + "path": "hr_payroll_approval_006__long/reward.py", + "size": 13292, + "lfs_oid": null, + "omitted": false, + "sha256": "dd8bbaa54e69eb24abf8aeeae35e3750bbc1ab7cf5700966d937a802546e93c6" + }, + { + "path": "hr_policy_ack_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_policy_ack_001/initial_setup.py", + "size": 8239, + "lfs_oid": null, + "omitted": false, + "sha256": "d0a3ea283908d59a218b812a04c28001876bb54e377e7cf454117bf78f31b178" + }, + { + "path": "hr_policy_ack_001/reward.py", + "size": 5798, + "lfs_oid": null, + "omitted": false, + "sha256": "602583c9e104086ef0762ad01fa8ab97788c2ecfba4605d1e1240a5f1a6fcf8c" + }, + { + "path": "hr_policy_ack_001/reward_label.json", + "size": 17936, + "lfs_oid": null, + "omitted": false, + "sha256": "277f28868bad10d9de297653f8e9929612b0ccdb66a641789751a5c8b5c4d880" + }, + { + "path": "hr_policy_ack_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_policy_ack_002/initial_setup.py", + "size": 12983, + "lfs_oid": null, + "omitted": false, + "sha256": "c21d1e4962553e1d4ecedc6a604ac77e059cfc528a380dee4513edee7ef4be30" + }, + { + "path": "hr_policy_ack_002/reward.py", + "size": 5262, + "lfs_oid": null, + "omitted": false, + "sha256": "98c2c7ff931199467c8b3320d388a66d5fd7ebde3c60db2326034f681099a168" + }, + { + "path": "hr_policy_ack_002/reward_label.json", + "size": 11373, + "lfs_oid": null, + "omitted": false, + "sha256": "80aa29282087f9bff63d4c942d7c4f15ec47e5bfaf21bd53462d457677d2edba" + }, + { + "path": "hr_policy_package_005/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "hr_policy_package_005/initial_setup.py", + "size": 31915, + "lfs_oid": null, + "omitted": false, + "sha256": "58db4954fd3dbdb8e767a736c300bdfab79d260ea3156eb7dadd41a9701ab864" + }, + { + "path": "hr_policy_package_005/reward.py", + "size": 13504, + "lfs_oid": null, + "omitted": false, + "sha256": "9eee5660456dcde40d3dd10d4424baa9df001e14abf5bf7017da3ee6db5bfe08" + }, + { + "path": "hr_policy_package_005/reward_label.json", + "size": 3439, + "lfs_oid": null, + "omitted": false, + "sha256": "562020ef41d976f2b0f195bc6f78172c353b040b42a3be4d1a0c378c4526939e" + }, + { + "path": "images/Ubuntu_openpyxl.qcow2", + "size": 27445690368, + "lfs_oid": null, + "omitted": true, + "sha256": "ec20b56ed19d2fe2cca0f11d8fb3564cfd2926996a4a984ad12ace5af73acb5d" + }, + { + "path": "images/osworld_image.tar", + "size": 264421376, + "lfs_oid": null, + "omitted": false, + "sha256": "71ab5700240d4ac0888227432df47a438367e7b18133c86e4df08fa9582dbb27" + }, + { + "path": "img_brightness_001__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "img_brightness_001__long/3673f262-ac90-5656-be2d-67a5317aac23_photo_2.png", + "size": 705029, + "lfs_oid": null, + "omitted": false, + "sha256": "febedea6760b2b5a9a4e0e31612cf0815ab4531495e65c068242c8ecb030d7f0" + }, + { + "path": "img_brightness_001__long/413ec05e-d9cf-5b8b-836a-c3f3cbfb1984_photo_4.png", + "size": 693680, + "lfs_oid": null, + "omitted": false, + "sha256": "d60f65dcc465c67431fb9302e83f4f988823824421fe972a990a3e24e210cd10" + }, + { + "path": "img_brightness_001__long/b36334a2-230f-5cc5-9d18-8d3b82af63ce_photo_5.png", + "size": 861147, + "lfs_oid": null, + "omitted": false, + "sha256": "40049dcbf0d51fd181e5f4154d635ce8be23417a08e924f2856188f388eab5d8" + }, + { + "path": "img_brightness_001__long/bc675d17-7187-5b5b-bef3-6dec1320871e_photo_3.png", + "size": 620364, + "lfs_oid": null, + "omitted": false, + "sha256": "af2a97fd988dfba4d96e4dc2c01dcc0c8da52b2b2082169a19d7b0c8880c2e1d" + }, + { + "path": "img_brightness_001__long/cac2ea50-b0a0-5d48-bbaa-6fa2f4f962d6_photo_1.png", + "size": 715382, + "lfs_oid": null, + "omitted": false, + "sha256": "1049a6f06ee481705b70306a3e6e075ade5b1478440d2ccb7feee1b6c4220b56" + }, + { + "path": "img_brightness_001__long/photo_1.png", + "size": 715382, + "lfs_oid": null, + "omitted": false, + "sha256": "1049a6f06ee481705b70306a3e6e075ade5b1478440d2ccb7feee1b6c4220b56" + }, + { + "path": "img_brightness_001__long/photo_2.png", + "size": 705029, + "lfs_oid": null, + "omitted": false, + "sha256": "febedea6760b2b5a9a4e0e31612cf0815ab4531495e65c068242c8ecb030d7f0" + }, + { + "path": "img_brightness_001__long/photo_3.png", + "size": 620364, + "lfs_oid": null, + "omitted": false, + "sha256": "af2a97fd988dfba4d96e4dc2c01dcc0c8da52b2b2082169a19d7b0c8880c2e1d" + }, + { + "path": "img_brightness_001__long/photo_4.png", + "size": 693680, + "lfs_oid": null, + "omitted": false, + "sha256": "d60f65dcc465c67431fb9302e83f4f988823824421fe972a990a3e24e210cd10" + }, + { + "path": "img_brightness_001__long/photo_5.png", + "size": 861147, + "lfs_oid": null, + "omitted": false, + "sha256": "40049dcbf0d51fd181e5f4154d635ce8be23417a08e924f2856188f388eab5d8" + }, + { + "path": "img_contrast_002__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "img_contrast_002__long/28f5eaae-8ffc-502a-9f01-039da9e20e87_photo_1.png", + "size": 550025, + "lfs_oid": null, + "omitted": false, + "sha256": "77feca22b7193cfb67751681152eec2057a242c2c5db6ebc19131ee985d59881" + }, + { + "path": "img_contrast_002__long/2d424fd7-e0ab-5940-bd12-f5dd39049c39_photo_3.png", + "size": 396307, + "lfs_oid": null, + "omitted": false, + "sha256": "c3d1b4e1d88f6637675c53599675553e48fc93a5ad8708a4440e80a075a7f6a3" + }, + { + "path": "img_contrast_002__long/6870a57f-fe99-5ba3-9019-d50e6ba26a23_photo_2.png", + "size": 421281, + "lfs_oid": null, + "omitted": false, + "sha256": "a4a86373a65c419cb3cad0f0cad35c9e71a5bb599c93f5e18a59dd280fb7398a" + }, + { + "path": "img_contrast_002__long/cc48f80b-4146-5863-b022-116118d616dc_photo_5.png", + "size": 340331, + "lfs_oid": null, + "omitted": false, + "sha256": "c16b7575ba71758ff6935067799236f4530a939060717f9c940a9c2f36c51e6d" + }, + { + "path": "img_contrast_002__long/d4da3309-5ea1-5901-8541-382f3a249e3f_photo_4.png", + "size": 797461, + "lfs_oid": null, + "omitted": false, + "sha256": "4dd9702a69344a03f86055e3e736c82dff18cdb99c0918e233b8c2632ccc5d5e" + }, + { + "path": "img_contrast_002__long/photo_1.png", + "size": 550025, + "lfs_oid": null, + "omitted": false, + "sha256": "77feca22b7193cfb67751681152eec2057a242c2c5db6ebc19131ee985d59881" + }, + { + "path": "img_contrast_002__long/photo_2.png", + "size": 421281, + "lfs_oid": null, + "omitted": false, + "sha256": "a4a86373a65c419cb3cad0f0cad35c9e71a5bb599c93f5e18a59dd280fb7398a" + }, + { + "path": "img_contrast_002__long/photo_3.png", + "size": 396307, + "lfs_oid": null, + "omitted": false, + "sha256": "c3d1b4e1d88f6637675c53599675553e48fc93a5ad8708a4440e80a075a7f6a3" + }, + { + "path": "img_contrast_002__long/photo_4.png", + "size": 797461, + "lfs_oid": null, + "omitted": false, + "sha256": "4dd9702a69344a03f86055e3e736c82dff18cdb99c0918e233b8c2632ccc5d5e" + }, + { + "path": "img_contrast_002__long/photo_5.png", + "size": 340331, + "lfs_oid": null, + "omitted": false, + "sha256": "c16b7575ba71758ff6935067799236f4530a939060717f9c940a9c2f36c51e6d" + }, + { + "path": "itops_access_approval_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "itops_access_approval_001/initial_setup.py", + "size": 12425, + "lfs_oid": null, + "omitted": false, + "sha256": "371abc1cc28184dfc4f47238977e0139e6a90279d6aeb4541d51edc4ac782216" + }, + { + "path": "itops_access_approval_001/reward.py", + "size": 7215, + "lfs_oid": null, + "omitted": false, + "sha256": "38992fffb2f6d0e2fb8b5a5031b648aef4ef1bf251c4055f659ab3ecd027f585" + }, + { + "path": "itops_access_approval_001/reward_label.json", + "size": 12946, + "lfs_oid": null, + "omitted": false, + "sha256": "a7d804c8e552af3fc42d05ec84709e9f44246908c6c7c2a458277e8dc6507be8" + }, + { + "path": "itops_access_log_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "itops_access_log_003/initial_setup.py", + "size": 10215, + "lfs_oid": null, + "omitted": false, + "sha256": "53c659cc4d0eaf0bd97d18a10b5df8fc535406cc822553d2f601724ecdd69da7" + }, + { + "path": "itops_access_log_003/reward.py", + "size": 6607, + "lfs_oid": null, + "omitted": false, + "sha256": "f56b559a2725893f903de657c0b0e576fa0bec0f54b4da7fa448cb9b3fa80dd2" + }, + { + "path": "itops_access_log_003/reward_label.json", + "size": 12788, + "lfs_oid": null, + "omitted": false, + "sha256": "fe53bd010361fb2471cd380e04cc4947b5e3c866b477fd930aa0053507763a9c" + }, + { + "path": "itops_access_ticket_004/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "itops_access_ticket_004/initial_setup.py", + "size": 17044, + "lfs_oid": null, + "omitted": false, + "sha256": "01af5e47ed2f667fe8006f9218f7f140810f20a722fa191c68a40bc063f15296" + }, + { + "path": "itops_access_ticket_004/reward.py", + "size": 11818, + "lfs_oid": null, + "omitted": false, + "sha256": "f3a8652c7891499b0ac7cfe3e97e23a8469d42f5e2fa7dc751513ab8b3b7d033" + }, + { + "path": "itops_access_ticket_004/reward_label.json", + "size": 17955, + "lfs_oid": null, + "omitted": false, + "sha256": "9d7b08c04d16aefb26ece28643501b1d383833c134d7c27d028faccfecdddf93" + }, + { + "path": "itops_field_change_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "itops_field_change_002/initial_setup.py", + "size": 22027, + "lfs_oid": null, + "omitted": false, + "sha256": "8d4ec7a1501c641ac43dbd8bfbc341530bf0a4adcd36c3845766af821594c38f" + }, + { + "path": "itops_field_change_002/reward.py", + "size": 7934, + "lfs_oid": null, + "omitted": false, + "sha256": "14d4b0c3ede08346f0438c501e3d9de56fa911a2593453aa1eabb51335370afb" + }, + { + "path": "itops_field_change_002/reward_label.json", + "size": 16154, + "lfs_oid": null, + "omitted": false, + "sha256": "4f7585f41a5574e581dba4f4288d50429dd97ce4d1c23100276071d727f5212a" + }, + { + "path": "legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/initial_setup.py", + "size": 30034, + "lfs_oid": null, + "omitted": false, + "sha256": "9a691f297d9eaf10e9487eab99d6cc2f4f742affcccfb05a9552eeecbdf145ff" + }, + { + "path": "legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward.py", + "size": 4654, + "lfs_oid": null, + "omitted": false, + "sha256": "ee1898d6b118b95ba2b1d6494f24184f86dc82293995f7d811729cce0a4ea532" + }, + { + "path": "legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward_label.json", + "size": 16585, + "lfs_oid": null, + "omitted": false, + "sha256": "87a771f6a8482e7c749839d143d26a7084a23022936ec4b871a89c2c133e9c2f" + }, + { + "path": "legacy/4619652a-02e6-5961-83df-6860dfb3ef29/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/4619652a-02e6-5961-83df-6860dfb3ef29/initial_setup.py", + "size": 21189, + "lfs_oid": null, + "omitted": false, + "sha256": "aaa9d0bf9e19c4cd729d9c67c1dd594b40c4a3c3f64b446c14c804932dfce5e8" + }, + { + "path": "legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward.py", + "size": 4046, + "lfs_oid": null, + "omitted": false, + "sha256": "459b2cbf0901e2be9b8007ed29b80427cc4a5efa3f93e5b84f10637dd1338c8a" + }, + { + "path": "legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward_label.json", + "size": 16832, + "lfs_oid": null, + "omitted": false, + "sha256": "33450c1df133e824a2ce51503165723c99e1ad033708232d3514d55b911890f1" + }, + { + "path": "legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/initial_setup.py", + "size": 19353, + "lfs_oid": null, + "omitted": false, + "sha256": "646508475f15d442af7b8ab362d8a009d1b4adf25aca0464723886e3d045efda" + }, + { + "path": "legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward.py", + "size": 5348, + "lfs_oid": null, + "omitted": false, + "sha256": "c38771ecdc53391b16e4f3a1843ca29ec7620294ce475b112a58e1938f412090" + }, + { + "path": "legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward_label.json", + "size": 22594, + "lfs_oid": null, + "omitted": false, + "sha256": "94083070305dccc69565f48798b80c3191613d9d8d911a6fd613d0ff2eff4eb7" + }, + { + "path": "legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/initial_setup.py", + "size": 109342, + "lfs_oid": null, + "omitted": false, + "sha256": "894d5c9c3db6507f25c816a41c723364a1e9575d819f74868a3b315bdbda1c79" + }, + { + "path": "legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward.py", + "size": 3874, + "lfs_oid": null, + "omitted": false, + "sha256": "cca0ce87ec090ab713d07746c7dd6cad9e3cb047f1345159458a92c5a5462c88" + }, + { + "path": "legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward_label.json", + "size": 15278, + "lfs_oid": null, + "omitted": false, + "sha256": "9221fb4a0db8e7c6b9f4fe48c94661f1a5242be04ff55ab7c9bc87ab91d38ac9" + }, + { + "path": "legacy/ae_forecast_001/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/ae_forecast_001/initial_setup.py", + "size": 24420, + "lfs_oid": null, + "omitted": false, + "sha256": "d12e1004a3208c74e5476a2099b0b6e29b4fc22c912ade4d5226ff85c8ed8dc5" + }, + { + "path": "legacy/ae_forecast_001/reward.py", + "size": 20235, + "lfs_oid": null, + "omitted": false, + "sha256": "bb5a69a520ec6c26a85ba76b7423d85f12670837fcbda14e369d1fe25996ea85" + }, + { + "path": "legacy/ae_forecast_001/reward_label.json", + "size": 15352, + "lfs_oid": null, + "omitted": false, + "sha256": "f0449a662faeb10024de97c53c445a12854de2d571340056cda73d232afe74a1" + }, + { + "path": "legacy/ae_meeting_followup_002/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/ae_meeting_followup_002/initial_setup.py", + "size": 24805, + "lfs_oid": null, + "omitted": false, + "sha256": "ccd0197d736f65d8817a73d9876176437ba2143dd52727af3e449eb28d12c1b9" + }, + { + "path": "legacy/ae_meeting_followup_002/reward.py", + "size": 20373, + "lfs_oid": null, + "omitted": false, + "sha256": "182ba4cd7768584f2ed9ff245be5dbe2bad1d7dafbc59fbf7faec516237ae6c7" + }, + { + "path": "legacy/ae_meeting_followup_002/reward_label.json", + "size": 18739, + "lfs_oid": null, + "omitted": false, + "sha256": "9fcd7bfea9c111a0333022ba2912b3273101e055296c802f8d325947b5f5498f" + }, + { + "path": "legacy/am_renewal_cycle_004/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/am_renewal_cycle_004/initial_setup.py", + "size": 31675, + "lfs_oid": null, + "omitted": false, + "sha256": "dc97ff265699ac6e96caec509e63cc6394874256d576c5f821e4edef5a1ac0eb" + }, + { + "path": "legacy/am_renewal_cycle_004/reward.py", + "size": 0, + "lfs_oid": null, + "omitted": false, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "path": "legacy/am_renewal_cycle_004/reward_label.json", + "size": 8127, + "lfs_oid": null, + "omitted": false, + "sha256": "0c1a8610d8634f6336e5f7b0651d5200aaf1adc62c95e4800386d0d5d0375845" + }, + { + "path": "legacy/ar_collections_001/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/ar_collections_001/initial_setup.py", + "size": 10394, + "lfs_oid": null, + "omitted": false, + "sha256": "9543ca926df420beb9a123fec78c404e2c5902b1d788829841fcf24781785b6c" + }, + { + "path": "legacy/ar_collections_001/reward.py", + "size": 8212, + "lfs_oid": null, + "omitted": false, + "sha256": "e80eff36259410514969d40af6361c5c79b430c744c09ca41449747886062251" + }, + { + "path": "legacy/ar_collections_001/reward_label.json", + "size": 21125, + "lfs_oid": null, + "omitted": false, + "sha256": "e0a0e00d5a1944a67ec523294535fd4a890c57135ba05a1bb87abdad479e23ba" + }, + { + "path": "legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/initial_setup.py", + "size": 30976, + "lfs_oid": null, + "omitted": false, + "sha256": "3e63a694ddfd081ae4bf29ab6b8d36cdba668044994377985b9027f66a0339ec" + }, + { + "path": "legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward.py", + "size": 4860, + "lfs_oid": null, + "omitted": false, + "sha256": "da072de9f7f3b5bdadf83a4319dbd86e57743457a6eea6e54a9d4c268ab5011d" + }, + { + "path": "legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward_label.json", + "size": 13413, + "lfs_oid": null, + "omitted": false, + "sha256": "01654214653a672db49c9bf1581c20d508f78805a34388d1820a4cbf97189b03" + }, + { + "path": "legacy/csm_onboarding_kickoff_002/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/csm_onboarding_kickoff_002/initial_setup.py", + "size": 24020, + "lfs_oid": null, + "omitted": false, + "sha256": "03431a666769e5312c5cb0b35a15b1fabd6752c64db146fa3828da46c88a2057" + }, + { + "path": "legacy/csm_onboarding_kickoff_002/reward.py", + "size": 15123, + "lfs_oid": null, + "omitted": false, + "sha256": "03673e038971ebc248aeba2d82e1fd53489382b8bb20d0ea588d6e5875655519" + }, + { + "path": "legacy/csm_onboarding_kickoff_002/reward_label.json", + "size": 19885, + "lfs_oid": null, + "omitted": false, + "sha256": "f691c44cd9256ef590727c9c7322723f2a157c0c0fdc53b6d987a8d2074d691e" + }, + { + "path": "legacy/csops_slack_to_jira_001/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/csops_slack_to_jira_001/initial_setup.py", + "size": 23427, + "lfs_oid": null, + "omitted": false, + "sha256": "deef5e51d798704d032e2fb63f56c85a00927503c08c8f140facf5e8a548d5ed" + }, + { + "path": "legacy/csops_slack_to_jira_001/reward.py", + "size": 17778, + "lfs_oid": null, + "omitted": false, + "sha256": "be8ee30c97beb3f62b8b2b7e603bb262f4c767901aea6d15f87881d50d2bf28b" + }, + { + "path": "legacy/csops_slack_to_jira_001/reward_label.json", + "size": 22403, + "lfs_oid": null, + "omitted": false, + "sha256": "e2e2752d0ed54b24bc60aa52c62c565661490b9523aa34dd081866de3bec120e" + }, + { + "path": "legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/initial_setup.py", + "size": 20992, + "lfs_oid": null, + "omitted": false, + "sha256": "f2e56f6449c65dc4646a794633481faa3f600dedb61500fa3385263262943021" + }, + { + "path": "legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward.py", + "size": 3370, + "lfs_oid": null, + "omitted": false, + "sha256": "5ab0a732ee8cb7ce6930ab7ca67d2d28df4ddc0f40f0b82dbfb5d398f6aa7eea" + }, + { + "path": "legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward_label.json", + "size": 14172, + "lfs_oid": null, + "omitted": false, + "sha256": "886106a68e6acd05bc579cda670c38cac2e153b9236b730d8a62d08f54e2c2c2" + }, + { + "path": "legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/initial_setup.py", + "size": 210601, + "lfs_oid": null, + "omitted": false, + "sha256": "bc6363588b10587bf83d0f357a7e2740bce8478d7f32773eb8c0762aeb27fa31" + }, + { + "path": "legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward.py", + "size": 4109, + "lfs_oid": null, + "omitted": false, + "sha256": "38c98af1d5e2cf7d03fa0251818bbc42e9112ca627954b7377533a2f35cb0aa7" + }, + { + "path": "legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward_label.json", + "size": 17230, + "lfs_oid": null, + "omitted": false, + "sha256": "831c2a6704f59b7b5d9d13523d5ee27c8d2ac8c1f52bd4f1e6e56161d21c2748" + }, + { + "path": "legacy/hr_handbook_002/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/hr_handbook_002/initial_setup.py", + "size": 13809, + "lfs_oid": null, + "omitted": false, + "sha256": "389293ba9927426dab79a1cfd082470371e2b231ecb5976bba3650f72cff12aa" + }, + { + "path": "legacy/hr_handbook_002/reward.py", + "size": 10430, + "lfs_oid": null, + "omitted": false, + "sha256": "8b4e81f8955143d22e376ca2a6ad0cabd2c8a4f3571cdbf6a083cea9da16b9c1" + }, + { + "path": "legacy/hr_handbook_002/reward_label.json", + "size": 25299, + "lfs_oid": null, + "omitted": false, + "sha256": "ccc638c746ba298832b4e9c5930cb0210535941761194e8fb4020d71892c357a" + }, + { + "path": "legacy/hr_onboarding_001/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/hr_onboarding_001/initial_setup.py", + "size": 15155, + "lfs_oid": null, + "omitted": false, + "sha256": "4ec13121c5c0cfcf6c7cf56dc21a25da506910f5b12a2adf3ba2a1ad21c0df05" + }, + { + "path": "legacy/hr_onboarding_001/reward.py", + "size": 5867, + "lfs_oid": null, + "omitted": false, + "sha256": "def73013819f23315e279f6a6d226ee0b0a330f7f2a7c1790bb296d5e8fbc8f5" + }, + { + "path": "legacy/hr_onboarding_001/reward_label.json", + "size": 18890, + "lfs_oid": null, + "omitted": false, + "sha256": "8f72ec1fddd262e35ee23a489585e1b2dbf4749edbec266efcb19a9318550ce5" + }, + { + "path": "legacy/mktg_leadhandoff_001/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/mktg_leadhandoff_001/initial_setup.py", + "size": 17222, + "lfs_oid": null, + "omitted": false, + "sha256": "4befa8d4ee91c0a61b84013ba331b3403f6357c1de50a43923bc02ca0e75ddd4" + }, + { + "path": "legacy/mktg_leadhandoff_001/reward.py", + "size": 11985, + "lfs_oid": null, + "omitted": false, + "sha256": "d1b874b283689c1561886f04779da7a53f99ce16d33e878b172aad92cf2357aa" + }, + { + "path": "legacy/mktg_leadhandoff_001/reward_label.json", + "size": 18493, + "lfs_oid": null, + "omitted": false, + "sha256": "824c515e6c06d850c239c6a6803990a592875b2e0154152d40a46dcc14ce4a25" + }, + { + "path": "legacy/mktg_postmortem_001/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/mktg_postmortem_001/initial_setup.py", + "size": 13577, + "lfs_oid": null, + "omitted": false, + "sha256": "51da5381f2f1e055140899449c34a36e2f24fadff219b353e9685e92c954e030" + }, + { + "path": "legacy/mktg_postmortem_001/reward.py", + "size": 10770, + "lfs_oid": null, + "omitted": false, + "sha256": "31578978f76b502aab889922e93a37c54b26e369ea6d9daeaa07ee4505f9448d" + }, + { + "path": "legacy/mktg_postmortem_001/reward_label.json", + "size": 21534, + "lfs_oid": null, + "omitted": false, + "sha256": "a845f92475b553dd89f3bf66972dbb54294a8c697d48b7aaf79ca126077ea032" + }, + { + "path": "legacy/prof15_calibration_cycle_003/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/prof15_calibration_cycle_003/initial_setup.py", + "size": 16865, + "lfs_oid": null, + "omitted": false, + "sha256": "0af86492f27d7eab34a946c951aa350dbda0608dfabe9f6869560233e67c7386" + }, + { + "path": "legacy/prof15_calibration_cycle_003/reward.py", + "size": 16082, + "lfs_oid": null, + "omitted": false, + "sha256": "f7106b185b12d9596ba7ba7e69035d72cd0aed05d0b1f44a0f3c65d882b7ef48" + }, + { + "path": "legacy/prof15_calibration_cycle_003/reward_label.json", + "size": 15734, + "lfs_oid": null, + "omitted": false, + "sha256": "8985990e9f720067b083dcf9bf8c80d3ee37f4a0642f7723b1d1ab40f452c364" + }, + { + "path": "legacy/prof16_postmortem_003/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/prof16_postmortem_003/initial_setup.py", + "size": 24727, + "lfs_oid": null, + "omitted": false, + "sha256": "2cd50907bd26f7e0aa68424e24976722db33115c7ea2a6e39e66fcc70ed8de17" + }, + { + "path": "legacy/prof16_postmortem_003/reward.py", + "size": 15100, + "lfs_oid": null, + "omitted": false, + "sha256": "5b0b33a068182e73009de77827915c91de52d8b8e5eb59181e5d8186d59045c4" + }, + { + "path": "legacy/prof16_postmortem_003/reward_label.json", + "size": 31451, + "lfs_oid": null, + "omitted": false, + "sha256": "74b965500c307664826fed3ce4dc35ec4137fec84d022950ce0de1d8dc1bdf03" + }, + { + "path": "legacy/prof19_hygiene_report_001/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/prof19_hygiene_report_001/initial_setup.py", + "size": 6169, + "lfs_oid": null, + "omitted": false, + "sha256": "3e1dc96f858b99fe361e7cfa9f0181520f34ed8048fde3e539965f98cc91630d" + }, + { + "path": "legacy/prof19_hygiene_report_001/reward.py", + "size": 9233, + "lfs_oid": null, + "omitted": false, + "sha256": "f785ef3bc8fe450a19428d346946989af31811d064838b8a53869c058576fff5" + }, + { + "path": "legacy/prof19_hygiene_report_001/reward_label.json", + "size": 15252, + "lfs_oid": null, + "omitted": false, + "sha256": "015d5196c76c6fbf4edaba2db8b5062801e9bbe57869420ef38ea3dabb975cec" + }, + { + "path": "legacy/prof26_integration_audit_003/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/prof26_integration_audit_003/initial_setup.py", + "size": 33747, + "lfs_oid": null, + "omitted": false, + "sha256": "0121be9d156488408f6680f1b7e65a4d29aa4ab939017b5324692bf0b169c4c5" + }, + { + "path": "legacy/prof26_integration_audit_003/reward.py", + "size": 9796, + "lfs_oid": null, + "omitted": false, + "sha256": "45a02a7aa040f7dc645952047602606a691e72121c9222e0af90cf62499ccee6" + }, + { + "path": "legacy/prof26_integration_audit_003/reward_label.json", + "size": 18091, + "lfs_oid": null, + "omitted": false, + "sha256": "03e20510884a8d45a267f4172016f7cdd3db67957b203681fdd1f37e011c15a9" + }, + { + "path": "legacy/prof35_escalate_overdue_001/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/prof35_escalate_overdue_001/initial_setup.py", + "size": 16398, + "lfs_oid": null, + "omitted": false, + "sha256": "31bda8e403ddb7d46452f3e2d9c618aaf89ac95454c2b0a21ab1d1e2dc389123" + }, + { + "path": "legacy/prof35_escalate_overdue_001/reward.py", + "size": 11998, + "lfs_oid": null, + "omitted": false, + "sha256": "2e5abcc4f7377c431c84d41234565778fc7cc2ce40cbe4635c5ae27516438645" + }, + { + "path": "legacy/prof35_escalate_overdue_001/reward_label.json", + "size": 15016, + "lfs_oid": null, + "omitted": false, + "sha256": "92ececbe622a90a5ea94b1addf8f0591c0ec95482518d9f61637b45ca4eba9bd" + }, + { + "path": "legacy/prof45_roster_invite_001/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/prof45_roster_invite_001/initial_setup.py", + "size": 9146, + "lfs_oid": null, + "omitted": false, + "sha256": "f188651efa00f769d0dd676a432b7f776d82230f286a6ca5f66de8c423be4f36" + }, + { + "path": "legacy/prof45_roster_invite_001/reward.py", + "size": 8236, + "lfs_oid": null, + "omitted": false, + "sha256": "cdb04948e66a579a84b696779153780b6496b4fc59178dad7ac91bbaf2ab0b8a" + }, + { + "path": "legacy/prof45_roster_invite_001/reward_label.json", + "size": 13023, + "lfs_oid": null, + "omitted": false, + "sha256": "8497ec858e50a974933d91fda7f9ab284604a5da4c5f86fbf05e86c580aa76a2" + }, + { + "path": "legacy/recruit_offer_001/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/recruit_offer_001/initial_setup.py", + "size": 13767, + "lfs_oid": null, + "omitted": false, + "sha256": "bbc02afeae969798fa2c8cfc01ee5d6e286ddd7c8be20f21074ca16f37a19a39" + }, + { + "path": "legacy/recruit_offer_001/reward.py", + "size": 8817, + "lfs_oid": null, + "omitted": false, + "sha256": "b52af2b81f885941d1e8dfe01048d4df0ea61531391d3d7f232c517c4a280bca" + }, + { + "path": "legacy/recruit_offer_001/reward_label.json", + "size": 30353, + "lfs_oid": null, + "omitted": false, + "sha256": "266d439e3ec43c20877dc828fee68b67b32ffbfbd7c5bf71de97fa702b4fa6e9" + }, + { + "path": "legacy/recruit_source_001/_cua_gym_vm_bridge.sh", + "size": 5123, + "lfs_oid": null, + "omitted": false, + "sha256": "c25b372e2786a1ebbb37540b83df1b0d6400d69f00d70dded781a42ddcdd992c" + }, + { + "path": "legacy/recruit_source_001/initial_setup.py", + "size": 12850, + "lfs_oid": null, + "omitted": false, + "sha256": "06cbdd22f8a18b82e0fd551641eac45c722ec1a03dbc88d1d6e04a7e01180833" + }, + { + "path": "legacy/recruit_source_001/reward.py", + "size": 10777, + "lfs_oid": null, + "omitted": false, + "sha256": "f941654121563391a9ec64622b6b00229eb65bcf448c782e275dbdf87ae2012c" + }, + { + "path": "legacy/recruit_source_001/reward_label.json", + "size": 16808, + "lfs_oid": null, + "omitted": false, + "sha256": "2d38783bbce78a0306f0c9bee1d3bccbb075d27f9f8a464162ba66bc6061cec7" + }, + { + "path": "legacy/sdr_discovery_call_003/_cua_gym_vm_bridge.sh", + "size": 5140, + "lfs_oid": null, + "omitted": false, + "sha256": "c63da5db27eee0410d3544ac52ed1128b82f4f0fc71a024240aa6bdbea938bf1" + }, + { + "path": "legacy/sdr_discovery_call_003/initial_setup.py", + "size": 22254, + "lfs_oid": null, + "omitted": false, + "sha256": "bcd616d9832165a78fe88742e755b39e8900a03f5ded1609b4a97bf8184fa16e" + }, + { + "path": "legacy/sdr_discovery_call_003/reward.py", + "size": 19512, + "lfs_oid": null, + "omitted": false, + "sha256": "49e18960d48a73bad4b4126f1d79cfc22388a789512c4088df765622500a508c" + }, + { + "path": "legacy/sdr_discovery_call_003/reward_label.json", + "size": 21134, + "lfs_oid": null, + "omitted": false, + "sha256": "3afd28fbf47a7227d3352e4df49b097b78edafb466a5256a1fd261dfb7c23b77" + }, + { + "path": "mktg_campaign_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_campaign_001/initial_setup.py", + "size": 14503, + "lfs_oid": null, + "omitted": false, + "sha256": "36bcfdadf91189973fab4ba6b1483507d0508174c784dbec24b84bf4c535fb85" + }, + { + "path": "mktg_campaign_001/reward.py", + "size": 7593, + "lfs_oid": null, + "omitted": false, + "sha256": "7ea869c542b4d40ede9bf5029ff928cf21e7793fc7661a0b2b9668697c2e16e4" + }, + { + "path": "mktg_campaign_001/reward_label.json", + "size": 18654, + "lfs_oid": null, + "omitted": false, + "sha256": "4e791fa6896475e1af7c81992ac01f913d4d3fc2523f751f440a9a2f604df785" + }, + { + "path": "mktg_campaign_create_004/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_campaign_create_004/initial_setup.py", + "size": 15054, + "lfs_oid": null, + "omitted": false, + "sha256": "d4bec7092b34d730e32e8d96be5f04fff8787b723e6a2f9e83d5e91573da5bd2" + }, + { + "path": "mktg_campaign_create_004/reward.py", + "size": 8619, + "lfs_oid": null, + "omitted": false, + "sha256": "4348cbf44c8c6c685b94d8f2ccb6693127d7873c3271131331ff854b702fdc07" + }, + { + "path": "mktg_campaign_create_004/reward_label.json", + "size": 14172, + "lfs_oid": null, + "omitted": false, + "sha256": "cbf12431840f42faecb56cf5ff7cc3bbb5f04678b0d494e2f7a3471ef00c7e11" + }, + { + "path": "mktg_field_reconcile_006/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_field_reconcile_006/initial_setup.py", + "size": 13118, + "lfs_oid": null, + "omitted": false, + "sha256": "03656da23b51ffe903cef01a4ce46dd0639ad90e5bb53439d1a88ad757d2a9e3" + }, + { + "path": "mktg_field_reconcile_006/reward.py", + "size": 6048, + "lfs_oid": null, + "omitted": false, + "sha256": "b7690d2cb67a3e2ef5081cb7203eecd56873ca2402fdcaea405f0b15ff5d0046" + }, + { + "path": "mktg_field_reconcile_006/reward_label.json", + "size": 13474, + "lfs_oid": null, + "omitted": false, + "sha256": "9dbc884f4877b115661e31ab7978889722af018d42bb4de666b7a0aa4d09587c" + }, + { + "path": "mktg_funnel_report_007/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_funnel_report_007/initial_setup.py", + "size": 17308, + "lfs_oid": null, + "omitted": false, + "sha256": "afec19fc51473cb9db7545c5e665993ad0e1178755285372d29c2df94c9a8b47" + }, + { + "path": "mktg_funnel_report_007/reward.py", + "size": 13529, + "lfs_oid": null, + "omitted": false, + "sha256": "6ed9dd1fa0e622ec108b460e5771ff3df95125a24b6f70c11f70040791f5db0d" + }, + { + "path": "mktg_funnel_report_007/reward_label.json", + "size": 16481, + "lfs_oid": null, + "omitted": false, + "sha256": "78c2df82d690f5449bef7e85aa035eff22c6c11154f8984004ab99c9b4a3345d" + }, + { + "path": "mktg_inbound_qualify_009__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_inbound_qualify_009__long/initial_setup.py", + "size": 35913, + "lfs_oid": null, + "omitted": false, + "sha256": "e9215e26790bfc8cf47dc1ecf2e3af9c4de6a9e1319882c4744ba1c4447007b8" + }, + { + "path": "mktg_inbound_qualify_009__long/reward.py", + "size": 13025, + "lfs_oid": null, + "omitted": false, + "sha256": "014d13e10f99d90207363e821d2907b40b32a4e440dd7488fb6b9b8750e80678" + }, + { + "path": "mktg_leadhandoff_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_leadhandoff_002/initial_setup.py", + "size": 17222, + "lfs_oid": null, + "omitted": false, + "sha256": "c59a69b93e9daef073e2ff3e0c4b3eb93a91a9f87b7f69e2acfe2a7edaa55da3" + }, + { + "path": "mktg_leadhandoff_002/reward.py", + "size": 11985, + "lfs_oid": null, + "omitted": false, + "sha256": "de272dfcefd83094e5041c61559fe528943ae6f417edf9bffa7745ac93ebff15" + }, + { + "path": "mktg_leadhandoff_002/reward_label.json", + "size": 16618, + "lfs_oid": null, + "omitted": false, + "sha256": "3e72dc3c6e35f801afd953a3658c766c1b1b484a5e8552a5752fd9b772a0baac" + }, + { + "path": "mktg_perf_report_005/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_perf_report_005/initial_setup.py", + "size": 25127, + "lfs_oid": null, + "omitted": false, + "sha256": "8054b31b628afce27e4d9e81bf6751162fbd2127526f2091dfd1c85ab39aeaf3" + }, + { + "path": "mktg_perf_report_005/reward.py", + "size": 10150, + "lfs_oid": null, + "omitted": false, + "sha256": "d4f131ccc127978e2aee636ee1eba8a1a8dce9f2cd9e1295a33182f880efe0e5" + }, + { + "path": "mktg_perf_report_005/reward_label.json", + "size": 30989, + "lfs_oid": null, + "omitted": false, + "sha256": "ff86b78e2180858f2e5e718d5842dbea2719931407ee04d6121514f522526083" + }, + { + "path": "mktg_report_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_report_003/initial_setup.py", + "size": 7390, + "lfs_oid": null, + "omitted": false, + "sha256": "fad4190e080cee5123178356517d58a7b76a2c945dabf1a0298465f78a277bac" + }, + { + "path": "mktg_report_003/reward.py", + "size": 7152, + "lfs_oid": null, + "omitted": false, + "sha256": "ba19290fc99ab4e32ec41578df6795ff5256bcd9215b5e1b3480fab85ef2538e" + }, + { + "path": "mktg_report_003/reward_label.json", + "size": 15296, + "lfs_oid": null, + "omitted": false, + "sha256": "e7bd6881420078342dabd96abe314934959a407dc5f5a75fb450fcb01e27aa0c" + }, + { + "path": "mktg_social_approve_010/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_social_approve_010/initial_setup.py", + "size": 7163, + "lfs_oid": null, + "omitted": false, + "sha256": "1b2aae77d610d19341e665599512849e39faff5bc18d37bac77f81eecf22edfe" + }, + { + "path": "mktg_social_approve_010/reward.py", + "size": 5555, + "lfs_oid": null, + "omitted": false, + "sha256": "b9f5d1cd4dc25fc7a4249a6566fb46454d96e99140e5f4c617b44e362bef9b35" + }, + { + "path": "mktg_social_approve_010/reward_label.json", + "size": 12795, + "lfs_oid": null, + "omitted": false, + "sha256": "0fabce10606ee050a02b4faa047f0aa8e270e37b35f4a02554b485c74673139f" + }, + { + "path": "mktg_webinar_guide_011/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_webinar_guide_011/initial_setup.py", + "size": 13421, + "lfs_oid": null, + "omitted": false, + "sha256": "5892ea8f11d433a1a08d1699b75a4246313ac23ff94f034c87c0640d9bc933b5" + }, + { + "path": "mktg_webinar_guide_011/reward.py", + "size": 6330, + "lfs_oid": null, + "omitted": false, + "sha256": "7134e850a7731a50c0e101d8f8625d72733e9dc620535c9e2d8c0228a150fa7b" + }, + { + "path": "mktg_webinar_guide_011/reward_label.json", + "size": 21815, + "lfs_oid": null, + "omitted": false, + "sha256": "4c65213fbf8b9b1684354db495ba8ff3b9d6d28d021f45052ac230c98f01b50e" + }, + { + "path": "mktg_webinar_mql_008/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "mktg_webinar_mql_008/initial_setup.py", + "size": 16010, + "lfs_oid": null, + "omitted": false, + "sha256": "af55bef3c2eff8f33a0e479a2633511ce8dbd518a2ddcf65f91d161426e1dc25" + }, + { + "path": "mktg_webinar_mql_008/reward.py", + "size": 13752, + "lfs_oid": null, + "omitted": false, + "sha256": "8656762ee040cb5057d292d0ca4139ec81d6c6d450e9cb8c14d13350b80671b8" + }, + { + "path": "mktg_webinar_mql_008/reward_label.json", + "size": 19670, + "lfs_oid": null, + "omitted": false, + "sha256": "6187903f90926ba85f2f06eb07837007f7f64f8fa3f26203b9978b21d18cb4e9" + }, + { + "path": "ops_board_agenda_008/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_board_agenda_008/initial_setup.py", + "size": 15957, + "lfs_oid": null, + "omitted": false, + "sha256": "dae9ae40deacea3809dddb71e9c22b0dde8b6712416cdbbe48da863281087d82" + }, + { + "path": "ops_board_agenda_008/reward.py", + "size": 4197, + "lfs_oid": null, + "omitted": false, + "sha256": "ac2d0108f58d42ead018bf95e706dd1ff28941fbb381b88b98fd841818b6c9de" + }, + { + "path": "ops_board_agenda_008/reward_label.json", + "size": 17104, + "lfs_oid": null, + "omitted": false, + "sha256": "f8176ce816355f0b2b0bc789fdc55ed10e81399e8d1cb5f57ecef186d47d7a5a" + }, + { + "path": "ops_catalog_update_003__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_catalog_update_003__long/initial_setup.py", + "size": 29851, + "lfs_oid": null, + "omitted": false, + "sha256": "d3bb9a9251e6e1320ed827ce3adae4d76510e9f41a7198f72fc4b05648ab7175" + }, + { + "path": "ops_catalog_update_003__long/reward.py", + "size": 11531, + "lfs_oid": null, + "omitted": false, + "sha256": "e84df17437c3f76997b8ad9a788f603f123fd138f316220752e094fa05579c94" + }, + { + "path": "ops_grade_report_011__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "ops_grade_report_011__long/0b50944b-e47d-590b-8c40-48b36c880427_template.docx", + "size": 36689, + "lfs_oid": null, + "omitted": false, + "sha256": "c029e925364fbd32509be2466ea06f9eb0c3d080cc8f51c61a89ffb59363305d" + }, + { + "path": "ops_grade_report_011__long/4bdbf8db-66f1-5daf-952d-2dce205c5951_roster.json", + "size": 114, + "lfs_oid": null, + "omitted": false, + "sha256": "a2636527162b1d04efbd4d84a481f22204829f054230f376ec131fc3b65aedb7" + }, + { + "path": "ops_grade_report_011__long/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py", + "size": 10869, + "lfs_oid": null, + "omitted": false, + "sha256": "afb077d720a70c8684b63eb57355787277081d75f347a665cc68b0572451bd9c" + }, + { + "path": "ops_grade_report_011__long/c99c7af9-2b53-5a1e-9fcd-97c0ea729e2d_b2d9report-thunderbird-profile.tar.gz", + "size": 2129544, + "lfs_oid": null, + "omitted": false, + "sha256": "eded5b46837937b5e26754f8e9993e224ad1c161b78fae87db652f8c86fb8b2a" + }, + { + "path": "ops_grade_report_011__long/df91db45-221a-5476-9b39-947185cc055f_grades.xlsx", + "size": 5066, + "lfs_oid": null, + "omitted": false, + "sha256": "4bbd8cfc37688db3ce7a5e5d42ceeb830d16f323a32306883e4a07a8088d59d3" + }, + { + "path": "ops_inbox_meeting_007/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_inbox_meeting_007/initial_setup.py", + "size": 16096, + "lfs_oid": null, + "omitted": false, + "sha256": "d06189507a1aa296f7313591a531bfef63c12ef82749062ebfc8934adb7d4036" + }, + { + "path": "ops_inbox_meeting_007/reward.py", + "size": 3557, + "lfs_oid": null, + "omitted": false, + "sha256": "2feb5ea22381330292dbc8e4a2bd341fa8debf7017b2f7ba1c8ccdd0e54a2cce" + }, + { + "path": "ops_inbox_meeting_007/reward_label.json", + "size": 14163, + "lfs_oid": null, + "omitted": false, + "sha256": "038988e70e886720a539e40d17de604269581dfa8dcc090049c357f2b3297f91" + }, + { + "path": "ops_inventory_reorder_001__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_inventory_reorder_001__long/initial_setup.py", + "size": 30467, + "lfs_oid": null, + "omitted": false, + "sha256": "c3ba03a8dcdfacd7d328eb961db357fe0de9f9915ceb8664c18b7536dd700273" + }, + { + "path": "ops_inventory_reorder_001__long/reward.py", + "size": 28494, + "lfs_oid": null, + "omitted": false, + "sha256": "0a12396de96d1cdecefce85361846e5141a94d3ee7809fff1b92008c7f0b1c8e" + }, + { + "path": "ops_license_audit_010__long/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "ops_license_audit_010__long/31cc7c4c-5e63-5f56-bdc5-79f24905368d_requirements.txt", + "size": 73, + "lfs_oid": null, + "omitted": false, + "sha256": "96746cf836ce693e3854d5d96d55a0cca01ae36f399e793b0a5f2edae28465d3" + }, + { + "path": "ops_license_audit_010__long/f44856ad-7d1a-5466-adc6-26115b152fb1_license_audit.xlsx", + "size": 4857, + "lfs_oid": null, + "omitted": false, + "sha256": "89fb66ace97e9149833b800ec8a9865aebf6704acddf57d2ff686e4ee476331e" + }, + { + "path": "ops_license_audit_010__long/license_audit_gold.xlsx", + "size": 5112, + "lfs_oid": null, + "omitted": false, + "sha256": "de7adc2a6425908dbe158067a6d824c4eca823a95fa91a65d56348060d5dd5dc" + }, + { + "path": "ops_meeting_schedule_004__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_meeting_schedule_004__long/initial_setup.py", + "size": 24782, + "lfs_oid": null, + "omitted": false, + "sha256": "077ba9761222220def8cfd3267dfbd478b46c674acd3a6da8ccc0d15d8be72a8" + }, + { + "path": "ops_meeting_schedule_004__long/reward.py", + "size": 13997, + "lfs_oid": null, + "omitted": false, + "sha256": "ba15399eee41ae10f64d326dbc2db500886f065f73edbc8affe490e5052550a5" + }, + { + "path": "ops_meeting_setup_009/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_meeting_setup_009/initial_setup.py", + "size": 52150, + "lfs_oid": null, + "omitted": false, + "sha256": "42d22d3b006012ce61b2db9494084d444a037f81a54bedcf48317349354a682a" + }, + { + "path": "ops_meeting_setup_009/reward.py", + "size": 3465, + "lfs_oid": null, + "omitted": false, + "sha256": "ff2bd315c701747d6db55ec5903e354fcf3c599621d43559b08a4be5dc1ad0a2" + }, + { + "path": "ops_meeting_setup_009/reward_label.json", + "size": 15550, + "lfs_oid": null, + "omitted": false, + "sha256": "3d609fbc1b8a41f6b2c13a77e9cdbce508f9e72a21309d24e371b77951cefe28" + }, + { + "path": "ops_pdf_mail_012__long__cond/.PLACEHOLDER", + "size": 289, + "lfs_oid": null, + "omitted": false, + "sha256": "80fccb0e34036bbb86cbe1cb09270a1bc594c6db79b5f0540e96382d99fd5ed1" + }, + { + "path": "ops_pdf_mail_012__long__cond/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py", + "size": 10869, + "lfs_oid": null, + "omitted": false, + "sha256": "afb077d720a70c8684b63eb57355787277081d75f347a665cc68b0572451bd9c" + }, + { + "path": "ops_pdf_mail_012__long__cond/c6bdf2ec-0613-5c22-ab89-6843875c6d43_mail_info.xlsx", + "size": 4967, + "lfs_oid": null, + "omitted": false, + "sha256": "e9c6b939e12e422e80fc141e02e80a06a3b580a6bbdb72f471f6c0d6959805e8" + }, + { + "path": "ops_pdf_mail_012__long__cond/c99c7af9-2b53-5a1e-9fcd-97c0ea729e2d_b2d9report-thunderbird-profile.tar.gz", + "size": 2129544, + "lfs_oid": null, + "omitted": false, + "sha256": "eded5b46837937b5e26754f8e9993e224ad1c161b78fae87db652f8c86fb8b2a" + }, + { + "path": "ops_pdf_mail_012__long__cond/e2317a9f-f460-57e6-a41d-47fae755c954_weekly_summary.pptx", + "size": 28773, + "lfs_oid": null, + "omitted": false, + "sha256": "a349ca04ca6579faba7f9f8beb6019f740c90c71d537e5e4ade9375ea6f4dc9d" + }, + { + "path": "ops_region_consolidate_002__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_region_consolidate_002__long/initial_setup.py", + "size": 34884, + "lfs_oid": null, + "omitted": false, + "sha256": "1e626469d8232a3e40c72ff0a1f5dcccdd9264e0e61fc93a84c92c327b0a6fb4" + }, + { + "path": "ops_region_consolidate_002__long/reward.py", + "size": 16690, + "lfs_oid": null, + "omitted": false, + "sha256": "33b56f73ad174b2100ce4028734a28178f52ae7c061d6a09506ab69e09b15bbd" + }, + { + "path": "ops_risk_log_006/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_risk_log_006/initial_setup.py", + "size": 20211, + "lfs_oid": null, + "omitted": false, + "sha256": "30fedb5521159d757a2a3020d27f3769fc6409b8e8859e8322f3ff346984ba10" + }, + { + "path": "ops_risk_log_006/reward.py", + "size": 6027, + "lfs_oid": null, + "omitted": false, + "sha256": "6e5f7ceda7fed8a44317b4b10ad502f15965dede825bce41ce0b7cbff22607cc" + }, + { + "path": "ops_risk_log_006/reward_label.json", + "size": 14861, + "lfs_oid": null, + "omitted": false, + "sha256": "2c93d0fe5886163bd3d5165a361bc75235455387006077d2ad591eef6d13bbfb" + }, + { + "path": "ops_shift_cover_005/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "ops_shift_cover_005/initial_setup.py", + "size": 11219, + "lfs_oid": null, + "omitted": false, + "sha256": "914d8f98bed54c56b3fd22f611e7fa98dc26af10061703fba3f65739b091787f" + }, + { + "path": "ops_shift_cover_005/reward.py", + "size": 9625, + "lfs_oid": null, + "omitted": false, + "sha256": "186131381e5d188671e2cc66dd52958e77e4aad758ab8ad881a247239d669c99" + }, + { + "path": "ops_shift_cover_005/reward_label.json", + "size": 12887, + "lfs_oid": null, + "omitted": false, + "sha256": "5ec4faf9ced29fbdd5a83afd42d6358073c3cf7e892961e3fc54b7058d7d2dbf" + }, + { + "path": "pm_board_sync_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "pm_board_sync_003/initial_setup.py", + "size": 20204, + "lfs_oid": null, + "omitted": false, + "sha256": "293a91b7ce5b930f0dce6e187925ac5d4ff70178c44eddddf9a63c419b0f5a2c" + }, + { + "path": "pm_board_sync_003/reward.py", + "size": 3097, + "lfs_oid": null, + "omitted": false, + "sha256": "5854c7d6f352b66504886d2e0bac12a7dd9e8a679dd73a699c45d8742d46bcb5" + }, + { + "path": "pm_board_sync_003/reward_label.json", + "size": 14078, + "lfs_oid": null, + "omitted": false, + "sha256": "8f22ba7d7096adf0dd12dbc532cadbfad30170125252f3fdd9ec680e76746601" + }, + { + "path": "pm_sprint_closeout_002__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "pm_sprint_closeout_002__long/initial_setup.py", + "size": 38469, + "lfs_oid": null, + "omitted": false, + "sha256": "a78b89034d1f67c159acd75e8eeb2adb8115c6609a91c6f10c3d3315952eb79a" + }, + { + "path": "pm_sprint_closeout_002__long/reward.py", + "size": 14341, + "lfs_oid": null, + "omitted": false, + "sha256": "20c4cb1f7df35e99a33c005352a899c5cc28e7c6ef3bdbf7ee357d961e73a226" + }, + { + "path": "pm_sprint_planning_001__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "pm_sprint_planning_001__long/initial_setup.py", + "size": 29452, + "lfs_oid": null, + "omitted": false, + "sha256": "5c188005e73db700cd5ab957037c07a020ebd38e7dbfcd823b570b80255ef053" + }, + { + "path": "pm_sprint_planning_001__long/reward.py", + "size": 11412, + "lfs_oid": null, + "omitted": false, + "sha256": "791ac82e92b49ebd4a3b837b6cf53e626eb1c83f74dafd4444e1508096f81241" + }, + { + "path": "qa_bug_escalate_004/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "qa_bug_escalate_004/initial_setup.py", + "size": 51695, + "lfs_oid": null, + "omitted": false, + "sha256": "ed7b6c1b13d6a46104572fa409b5ebd87e3deca9d470d1887905508c775fcc10" + }, + { + "path": "qa_bug_escalate_004/reward.py", + "size": 4448, + "lfs_oid": null, + "omitted": false, + "sha256": "162cddaeb4aae857d0e0ea654d0254608ffca8a933e23cbbc5a5810495405669" + }, + { + "path": "qa_bug_escalate_004/reward_label.json", + "size": 17434, + "lfs_oid": null, + "omitted": false, + "sha256": "4ee77e6a951df0d79450bf8fef90cf13bbbef57f212d1b67d19a451a2cbba88e" + }, + { + "path": "qa_defect_triage_001__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "qa_defect_triage_001__long/initial_setup.py", + "size": 34210, + "lfs_oid": null, + "omitted": false, + "sha256": "a160a53ddd14b6d9654b8f11dd0a0c39fb5a8a41ce6aa95988fa0cc718dd7c07" + }, + { + "path": "qa_defect_triage_001__long/reward.py", + "size": 16126, + "lfs_oid": null, + "omitted": false, + "sha256": "0c7c4056701f893487d1c514d6f8b79698e18ec9e1c20731416b975fba48ebe2" + }, + { + "path": "qa_pr_latency_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "qa_pr_latency_002/initial_setup.py", + "size": 186876, + "lfs_oid": null, + "omitted": false, + "sha256": "6d94c9338d76f82b4851787bd7d834310b9779d6d3a5ab7b5036335ac862388d" + }, + { + "path": "qa_pr_latency_002/reward.py", + "size": 4865, + "lfs_oid": null, + "omitted": false, + "sha256": "3b8ddd3802ac39e1e736f94cf84ae3930ae2567ad0c32350790762d74e7c5270" + }, + { + "path": "qa_pr_latency_002/reward_label.json", + "size": 13919, + "lfs_oid": null, + "omitted": false, + "sha256": "0b33d5ffc56551eeb87b3a213ad7a8dc8d2861cd3ed3688c6363d88f847d5d1a" + }, + { + "path": "qa_pr_mergeable_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "qa_pr_mergeable_003/initial_setup.py", + "size": 22619, + "lfs_oid": null, + "omitted": false, + "sha256": "933f5a5da4173b24e0e9d239d447239dca8522714447767ecdb5d91ee59829fc" + }, + { + "path": "qa_pr_mergeable_003/reward.py", + "size": 3433, + "lfs_oid": null, + "omitted": false, + "sha256": "3d8e52778760b9ed177261ed5a99cacc42a52234dcfec45a3c8ba0dc22c3efd2" + }, + { + "path": "qa_pr_mergeable_003/reward_label.json", + "size": 15416, + "lfs_oid": null, + "omitted": false, + "sha256": "9a7d1a792e35d2bc012ba7ce947b16ddc1b29be7537c6a265974d4c6aa70239f" + }, + { + "path": "recruit_candidate_flow_007__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_candidate_flow_007__long/initial_setup.py", + "size": 29476, + "lfs_oid": null, + "omitted": false, + "sha256": "20f91357a8654ddaf15e380e814e355ee09d94c6d0c304890665db76c2b33817" + }, + { + "path": "recruit_candidate_flow_007__long/reward.py", + "size": 19982, + "lfs_oid": null, + "omitted": false, + "sha256": "b4e948a6fd06ce7d2e456451042d43dd5760afd9739c2cb431d17befec06ec5f" + }, + { + "path": "recruit_coordinator_006__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_coordinator_006__long/initial_setup.py", + "size": 43698, + "lfs_oid": null, + "omitted": false, + "sha256": "efcd17ef3dae4f0f5e6a5080cdd0640668da90c17112ed06f3f559cb54cf2526" + }, + { + "path": "recruit_coordinator_006__long/reward.py", + "size": 25899, + "lfs_oid": null, + "omitted": false, + "sha256": "ca68fb700a2b33d60ec06a98fa7ce31010bb951dcc6665155bea4a3a446da4ee" + }, + { + "path": "recruit_followup_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_followup_001/initial_setup.py", + "size": 11193, + "lfs_oid": null, + "omitted": false, + "sha256": "a5229a46a494378718329ca4532fedee50a04857ba30861dc81179d28f9b4d53" + }, + { + "path": "recruit_followup_001/reward.py", + "size": 5869, + "lfs_oid": null, + "omitted": false, + "sha256": "9228bc2ad1d9ae95a078b98a44c7824e607d15d758aad8acfc954c29750e9862" + }, + { + "path": "recruit_followup_001/reward_label.json", + "size": 12516, + "lfs_oid": null, + "omitted": false, + "sha256": "8910f6d8e95334ee86ed2fc294ed1c2550f9597b38067139edbe08060fba9009" + }, + { + "path": "recruit_offer_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_offer_003/initial_setup.py", + "size": 15130, + "lfs_oid": null, + "omitted": false, + "sha256": "4816c7535be1d0960d162c01dea7c819e31fc5bd101ed53b080b554d8fb700ac" + }, + { + "path": "recruit_offer_003/reward.py", + "size": 8817, + "lfs_oid": null, + "omitted": false, + "sha256": "3d5debd4a649f5dc9cacd83ceeb0c98885fc24cdb714dff8548adbb80f160360" + }, + { + "path": "recruit_offer_003/reward_label.json", + "size": 21712, + "lfs_oid": null, + "omitted": false, + "sha256": "36a3ffa27cc87a0de612b0ad73d0d7d476599c77ec46fec63c350fd7e784cbb1" + }, + { + "path": "recruit_onsite_decision_005__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_onsite_decision_005__long/initial_setup.py", + "size": 32291, + "lfs_oid": null, + "omitted": false, + "sha256": "64da92e6ef2019d320028f9561f46f48540b953b52bf2db6b6cb51a1277b4cc3" + }, + { + "path": "recruit_onsite_decision_005__long/reward.py", + "size": 12310, + "lfs_oid": null, + "omitted": false, + "sha256": "9d4abe28e2e1fcb35ad339c74f2c9d0b9aa94f6c583e2e4721867fd6e805f977" + }, + { + "path": "recruit_onsite_stage_008__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_onsite_stage_008__long/initial_setup.py", + "size": 40768, + "lfs_oid": null, + "omitted": false, + "sha256": "c93870803f051b2517bf02c5fbc55f9141d8c22bb0a12a2ba572a3729834d74b" + }, + { + "path": "recruit_onsite_stage_008__long/reward.py", + "size": 26241, + "lfs_oid": null, + "omitted": false, + "sha256": "1c1479f2df3afebabd35875b60ec9cf7a1f0fc6733d4b5afc3f4d186da1752b3" + }, + { + "path": "recruit_resume_screen_004__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_resume_screen_004__long/initial_setup.py", + "size": 43845, + "lfs_oid": null, + "omitted": false, + "sha256": "4d761c8941f742d6f0b3102d3dd8b5fd86c6b8a2fb8be47e0f2f9932779d0c41" + }, + { + "path": "recruit_resume_screen_004__long/reward.py", + "size": 28307, + "lfs_oid": null, + "omitted": false, + "sha256": "ced11e7c7270ab0d05c609d069623f337be676a0bf4bcc5ff96992e9fc269977" + }, + { + "path": "recruit_screen_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "recruit_screen_002/initial_setup.py", + "size": 10065, + "lfs_oid": null, + "omitted": false, + "sha256": "aee6e1cdb8085fc34c4ca2b6e983f8a0196fabf0b65334b1ea1e27a2a192f068" + }, + { + "path": "recruit_screen_002/reward.py", + "size": 7931, + "lfs_oid": null, + "omitted": false, + "sha256": "0aa27b9a8273d697add2003a3cfb4c1e5151faefa61364dbb729648a195fc14d" + }, + { + "path": "recruit_screen_002/reward_label.json", + "size": 17846, + "lfs_oid": null, + "omitted": false, + "sha256": "bc0152b27de9109cc7d956a326c8feeee4d76a283cc155b71f817d6191de073f" + }, + { + "path": "sdr_cold_outreach_001/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sdr_cold_outreach_001/initial_setup.py", + "size": 26483, + "lfs_oid": null, + "omitted": false, + "sha256": "9521aaeb167df15035bbda5dc3ff026e577605d96a01f1300f65c082f730557d" + }, + { + "path": "sdr_cold_outreach_001/reward.py", + "size": 16691, + "lfs_oid": null, + "omitted": false, + "sha256": "eeb45330b5005a351fcd5c1ae3fd9102175c82045fd756185000f4108d1b28dc" + }, + { + "path": "sdr_cold_outreach_001/reward_label.json", + "size": 18860, + "lfs_oid": null, + "omitted": false, + "sha256": "390c22e47cd651a0123f88bf94929412cc9aa4d9616078f23457b23fa41d264d" + }, + { + "path": "sdr_inbound_lead_006__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sdr_inbound_lead_006__long/initial_setup.py", + "size": 41789, + "lfs_oid": null, + "omitted": false, + "sha256": "ea9de0a40ba5f0de8f3e91e4f89b653748f3ac5930054c655f386f38d96c16b2" + }, + { + "path": "sdr_inbound_lead_006__long/reward.py", + "size": 25408, + "lfs_oid": null, + "omitted": false, + "sha256": "f51cd7513e9eac9f5cc2d70f7017ce0a0072c5395b2bf909bac60f8c3d25f6e1" + }, + { + "path": "sdr_lead_import_004__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sdr_lead_import_004__long/initial_setup.py", + "size": 31783, + "lfs_oid": null, + "omitted": false, + "sha256": "5cd88f4b0fefe36c44f97189e88073f56f0000f23ef4ef8a0a124cf4ded9e762" + }, + { + "path": "sdr_lead_import_004__long/reward.py", + "size": 12367, + "lfs_oid": null, + "omitted": false, + "sha256": "1096e368734eb3c97ed5cd8cf024b813ce7d13e57118572c71552ddc059db243" + }, + { + "path": "sdr_lead_routing_005__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sdr_lead_routing_005__long/initial_setup.py", + "size": 25627, + "lfs_oid": null, + "omitted": false, + "sha256": "106f502e4633206be2fb5885268f350cd70d76c38ee3d6b4cf47867711bb4b46" + }, + { + "path": "sdr_lead_routing_005__long/reward.py", + "size": 12129, + "lfs_oid": null, + "omitted": false, + "sha256": "08852d91a8d4d918be255abad242b4580a03e448ccf239f3a43bcac0616ca6d1" + }, + { + "path": "sdr_outreach_tracker_002/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sdr_outreach_tracker_002/initial_setup.py", + "size": 32725, + "lfs_oid": null, + "omitted": false, + "sha256": "8f83ea79251308f44eebf9fe6fdb709d990e49d452380d7f93f9c50459dee740" + }, + { + "path": "sdr_outreach_tracker_002/reward.py", + "size": 19943, + "lfs_oid": null, + "omitted": false, + "sha256": "9030291d4a5461ddca49755f5561c18fd6ed225ae9fd43089344a4b5fdd1823a" + }, + { + "path": "sdr_outreach_tracker_002/reward_label.json", + "size": 17466, + "lfs_oid": null, + "omitted": false, + "sha256": "e67fa888d31fe70c9145cd07e9ac999f5b8cbf7a2f9f0ad59df86818d15994f4" + }, + { + "path": "sdr_source_lead_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sdr_source_lead_003/initial_setup.py", + "size": 37266, + "lfs_oid": null, + "omitted": false, + "sha256": "1e3afb64a69cdf95cd865b43039fb0ff65a0342d1c9c010ffd14c72a8df95127" + }, + { + "path": "sdr_source_lead_003/reward.py", + "size": 13928, + "lfs_oid": null, + "omitted": false, + "sha256": "25f7e5442c79533130eca1decf4c4813d513963997936585a19079c2ee113464" + }, + { + "path": "sdr_source_lead_003/reward_label.json", + "size": 23095, + "lfs_oid": null, + "omitted": false, + "sha256": "6aa4a10b11d39f8d50c5265a3b6a521b22459a0df8e903c4867004d82b6412c2" + }, + { + "path": "sre_change_review_002__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sre_change_review_002__long/initial_setup.py", + "size": 35415, + "lfs_oid": null, + "omitted": false, + "sha256": "dff34b74c7c197f5cc849b76fb2f8264b00c52bc2dbda9401e6ab6474dcd0996" + }, + { + "path": "sre_change_review_002__long/reward.py", + "size": 14874, + "lfs_oid": null, + "omitted": false, + "sha256": "b4798e4a7a3a033166ea6dc0ff1b2bca2607bcedf1896df33a1d4f1ac9a2e855" + }, + { + "path": "sre_error_triage_001__long/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sre_error_triage_001__long/initial_setup.py", + "size": 35629, + "lfs_oid": null, + "omitted": false, + "sha256": "7e2bb27ee2812dd929aadcb1a95d386da02a5441b8d19dabb7455d01e7859ee2" + }, + { + "path": "sre_error_triage_001__long/reward.py", + "size": 16264, + "lfs_oid": null, + "omitted": false, + "sha256": "c0c552c71cb8492c955872031ae168ae5798aa51dc49727a2d38d8c79f88a613" + }, + { + "path": "sre_runbook_003/_cua_gym_vm_bridge.sh", + "size": 5138, + "lfs_oid": null, + "omitted": false, + "sha256": "72c44509e52f898e426307b12f35f666b9ed9a63dce74b5b2df387ad53412030" + }, + { + "path": "sre_runbook_003/initial_setup.py", + "size": 112226, + "lfs_oid": null, + "omitted": false, + "sha256": "00e14bb44bb475e3a8e4c4276a156e19b6292562f730ea1c43960f34044b2431" + }, + { + "path": "sre_runbook_003/reward.py", + "size": 4178, + "lfs_oid": null, + "omitted": false, + "sha256": "2cf3755d578e48369b91cc82a1dda1292ba1a9f38f07a14b7a3dc9a8e5099b4e" + }, + { + "path": "sre_runbook_003/reward_label.json", + "size": 14905, + "lfs_oid": null, + "omitted": false, + "sha256": "2ba58733bf6b0cf499f223c1692e93874aab487cf31684343f69a1ba87e75d4d" + } + ] +} diff --git a/mktg_campaign_001/_cua_gym_vm_bridge.sh b/mktg_campaign_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_campaign_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/mktg_campaign_001/initial_setup.py b/mktg_campaign_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..59054f9908d1cd13d90d2f69323bdd626f6cc19c --- /dev/null +++ b/mktg_campaign_001/initial_setup.py @@ -0,0 +1,360 @@ +""" +Initial Setup: Summer Product Webinar campaign kickoff (Airtable -> Asana -> Slack) +Task ID: mktg_campaign_001 +Domain: mock_websites +Mocks: airtable_mock, asana_mock, slack_mock + +Pre-task state: +- Airtable base "Marketing Ops" with a "Campaigns" table + (fields: Campaign Name, Target Audience, Channels, Launch Date, Status) + containing a few EXISTING campaigns. NO "Summer Product Webinar" record. +- Asana workspace with an existing "Q3 Campaigns" project (with a "To Do" + section) containing a couple of unrelated existing tasks. The three target + execution tasks do NOT exist yet. +- Slack workspace with a #marketing channel containing some prior chatter, but + NO "Summer Product Webinar" kickoff message yet. +""" + +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Configuration --- +TASK_ID = 'mktg_campaign_001' + +AIRTABLE_URL = 'http://28.7.184.198:8109' +ASANA_URL = 'http://28.7.184.198:8114' +SLACK_URL = 'http://28.7.184.198:8178' + +# Generate and persist a single session ID shared across all mocks +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated session ID: {sid}') + +# --------------------------------------------------------------------------- +# Airtable initial state — Marketing Ops base, Campaigns table +# --------------------------------------------------------------------------- +COLLABORATORS = [ + {"id": "user_1", "name": "John Doe", "email": "john.doe@example.com", + "avatar": "https://ui-avatars.com/api/?name=John+Doe&background=8B5CF6&color=fff"}, + {"id": "user_2", "name": "Priya Nair", "email": "priya.nair@example.com", + "avatar": "https://ui-avatars.com/api/?name=Priya+Nair&background=EC4899&color=fff"}, + {"id": "user_3", "name": "Tom Becker", "email": "tom.becker@example.com", + "avatar": "https://ui-avatars.com/api/?name=Tom+Becker&background=10B981&color=fff"}, +] + +CAMPAIGN_STATUS_OPTIONS = [ + {"id": "st_planning", "name": "Planning", "color": "bg-[#FFEAB6] text-[#8D6302]"}, + {"id": "st_active", "name": "Active", "color": "bg-[#D0F0FD] text-[#0B76B7]"}, + {"id": "st_completed", "name": "Completed", "color": "bg-[#D1F7C4] text-[#2D7514]"}, +] + +CAMPAIGN_FIELDS = [ + {"id": "fld_name", "name": "Campaign Name", "type": "text", "primary": True}, + {"id": "fld_audience", "name": "Target Audience", "type": "text"}, + {"id": "fld_channels", "name": "Channels", "type": "text"}, + {"id": "fld_launch", "name": "Launch Date", "type": "date"}, + {"id": "fld_status", "name": "Status", "type": "single_select", "options": CAMPAIGN_STATUS_OPTIONS}, +] + +# Existing campaigns. The "Summer Product Webinar" record is intentionally absent. +CAMPAIGN_RECORDS = [ + { + "id": "rec_existing_1", + "createdTime": "2026-04-12T09:00:00.000Z", + "fields": { + "fld_name": "Spring Onboarding Push", + "fld_audience": "New SMB signups", + "fld_channels": "Email + In-app", + "fld_launch": "2026-04-20", + "fld_status": "Completed", + }, + }, + { + "id": "rec_existing_2", + "createdTime": "2026-05-18T10:30:00.000Z", + "fields": { + "fld_name": "Q2 Feature Spotlight", + "fld_audience": "Existing Pro customers", + "fld_channels": "Email + Blog", + "fld_launch": "2026-06-01", + "fld_status": "Active", + }, + }, + { + "id": "rec_existing_3", + "createdTime": "2026-06-09T14:15:00.000Z", + "fields": { + "fld_name": "Partner Co-marketing Drive", + "fld_audience": "Channel partners", + "fld_channels": "LinkedIn + Webinar", + "fld_launch": "2026-06-25", + "fld_status": "Planning", + }, + }, +] + +airtable_state = { + "currentUser": COLLABORATORS[0], + "collaborators": COLLABORATORS, + "bases": { + "base_mktg": { + "id": "base_mktg", + "name": "Marketing Ops", + "color": "bg-teal-600", + "tables": ["tbl_campaigns"], + } + }, + "tables": { + "tbl_campaigns": { + "id": "tbl_campaigns", + "name": "Campaigns", + "baseId": "base_mktg", + "fields": CAMPAIGN_FIELDS, + "records": CAMPAIGN_RECORDS, + "views": [ + { + "id": "view_grid", + "name": "All Campaigns", + "type": "grid", + "filters": [], + "sorts": [], + "groupBy": [], + "hiddenFieldIds": [], + "fieldWidths": {}, + "rowHeight": "short", + } + ], + "activeViewId": "view_grid", + } + }, + "activeBaseId": "base_mktg", + "activeTableId": "tbl_campaigns", + "ui": { + "viewSidebarOpen": False, + "expandedRecordId": None, + "searchQuery": "", + "isSearching": False, + }, +} + +# --------------------------------------------------------------------------- +# Asana initial state — Q3 Campaigns project +# --------------------------------------------------------------------------- +ASANA_USERS = [ + {"userId": "user-0", "name": "Alex Johnson", "email": "alex.johnson@company.com", + "avatar": "https://picsum.photos/100/100?random=user0", "title": "Marketing PM", + "department": "Marketing", "location": "San Francisco, CA", "timezone": "PST", "theme": "light"}, + {"userId": "user-3", "name": "Emily Watson", "email": "emily.watson@company.com", + "avatar": "https://picsum.photos/100/100?random=user3", "title": "Marketing Manager", + "department": "Marketing", "location": "New York, NY", "timezone": "EST", "theme": "light"}, + {"userId": "user-1", "name": "Sarah Chen", "email": "sarah.chen@company.com", + "avatar": "https://picsum.photos/100/100?random=user1", "title": "Designer", + "department": "Design", "location": "Seattle, WA", "timezone": "PST", "theme": "light"}, +] + +ASANA_TEAMS = [ + {"teamId": "team-3", "name": "Marketing", "description": "Marketing team", + "memberIds": ["user-0", "user-3", "user-1"], "ownerId": "user-0", + "privacy": "public", "createdDate": "2026-01-05T00:00:00Z"}, +] + +ASANA_PROJECTS = [ + { + "projectId": "project-q3", + "name": "Q3 Campaigns", + "teamId": "team-3", + "description": "All marketing campaigns launching in Q3.", + "color": "green", + "icon": "megaphone", + "ownerId": "user-0", + "memberIds": ["user-0", "user-3", "user-1"], + "sections": [ + {"sectionId": "section-q3-1", "name": "To Do", "collapsed": False}, + {"sectionId": "section-q3-2", "name": "In Progress", "collapsed": False}, + {"sectionId": "section-q3-3", "name": "Done", "collapsed": False}, + ], + "customFields": [], + "privacy": "public", + "startDate": "2026-07-01", + "dueDate": "2026-09-30", + "archived": False, + "starred": False, + "createdDate": "2026-06-15T00:00:00Z", + "modifiedDate": "2026-06-20T00:00:00Z", + }, +] + +# Existing unrelated tasks in Q3 Campaigns. The three target tasks are absent. +ASANA_TASKS = [ + { + "taskId": "task-existing-1", + "name": "Finalize Q3 campaign calendar", + "projectId": "project-q3", + "sectionId": "section-q3-2", + "description": "Lock in launch dates for all Q3 campaigns.", + "assigneeId": "user-3", + "creatorId": "user-0", + "dueDate": "2026-07-05", + "startDate": "2026-07-01", + "completed": False, + "parentTaskId": None, + "dependencies": [], + "tags": [], + "attachmentIds": [], + "customFieldValues": {}, + "likeCount": 0, + "createdDate": "2026-06-16T00:00:00Z", + "modifiedDate": "2026-06-18T00:00:00Z", + }, + { + "taskId": "task-existing-2", + "name": "Confirm Q3 marketing budget", + "projectId": "project-q3", + "sectionId": "section-q3-3", + "description": "Sign-off from finance on the Q3 marketing budget.", + "assigneeId": "user-0", + "creatorId": "user-0", + "dueDate": "2026-06-28", + "startDate": "2026-06-20", + "completed": True, + "completedDate": "2026-06-27T00:00:00Z", + "parentTaskId": None, + "dependencies": [], + "tags": [], + "attachmentIds": [], + "customFieldValues": {}, + "likeCount": 1, + "createdDate": "2026-06-16T00:00:00Z", + "modifiedDate": "2026-06-27T00:00:00Z", + }, +] + +asana_state = { + "currentUser": ASANA_USERS[0], + "users": ASANA_USERS, + "teams": ASANA_TEAMS, + "projects": ASANA_PROJECTS, + "tasks": ASANA_TASKS, + "comments": [], + "portfolios": [], + "goals": [], + "notifications": [], + "attachments": [], +} + +# --------------------------------------------------------------------------- +# Slack initial state — #marketing channel +# --------------------------------------------------------------------------- +SLACK_USERS = [ + {"userId": "user_1", "fullName": "Alex Johnson", "displayName": "Alex", + "email": "alex.johnson@company.com", "avatar": "https://picsum.photos/200/200?random=1", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"}, + {"userId": "user_2", "fullName": "Emily Watson", "displayName": "Emily", + "email": "emily.watson@company.com", "avatar": "https://picsum.photos/200/200?random=2", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_3", "fullName": "Sarah Chen", "displayName": "Sarah", + "email": "sarah.chen@company.com", "avatar": "https://picsum.photos/200/200?random=3", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"}, +] + +slack_state = { + "currentUser": SLACK_USERS[0], + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Marketing", "icon": ""}, + "users": SLACK_USERS, + "channels": [ + {"channelId": "marketing", "name": "marketing", "description": "Marketing team channel", + "topic": "Campaign planning and launches", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1", + "createdAt": "2026-06-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "general", "name": "general", "description": "General chat", "topic": "", + "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"], + "createdBy": "user_1", "createdAt": "2026-06-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "marketing": [ + {"messageId": "msg_m1", "senderId": "user_2", + "content": "Are we still on track to launch the Summer Product Webinar campaign this month?", + "timestamp": "2026-06-29T15:20:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + {"messageId": "msg_m2", "senderId": "user_1", + "content": "Yes — setting it up in Airtable and Asana now, will post a kickoff here shortly.", + "timestamp": "2026-06-29T15:25:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + "general": [ + {"messageId": "msg_g1", "senderId": "user_3", + "content": "Morning all!", "timestamp": "2026-06-30T08:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], +} + +# --------------------------------------------------------------------------- +# Inject state into all three mocks (same sid, action: set) +# --------------------------------------------------------------------------- +print("Injecting initial state into mocks...") + +at_resp = requests.post(f'{AIRTABLE_URL}/post?sid={sid}', + json={'action': 'set', 'state': airtable_state}, timeout=30) +at_resp.raise_for_status() +print("OK: Airtable state injected") + +as_resp = requests.post(f'{ASANA_URL}/post?sid={sid}', + json={'action': 'set', 'state': asana_state}, timeout=30) +as_resp.raise_for_status() +print("OK: Asana state injected") + +sl_resp = requests.post(f'{SLACK_URL}/post?sid={sid}', + json={'action': 'set', 'state': slack_state}, timeout=30) +sl_resp.raise_for_status() +print("OK: Slack state injected") + +# --- Verify --- +print("Verifying state injection...") +at_go = requests.get(f'{AIRTABLE_URL}/go?sid={sid}', timeout=10).json() +assert at_go['initial_state'] is not None, 'Airtable initial_state is None' +print("OK: Airtable initial_state verified") + +as_go = requests.get(f'{ASANA_URL}/go?sid={sid}', timeout=10).json() +assert as_go['initial_state'] is not None, 'Asana initial_state is None' +print("OK: Asana initial_state verified") + +sl_go = requests.get(f'{SLACK_URL}/go?sid={sid}', timeout=10).json() +assert sl_go['initial_state'] is not None, 'Slack initial_state is None' +print("OK: Slack initial_state verified") + +# --------------------------------------------------------------------------- +# Launch browsers (GUI-ready start state) +# --------------------------------------------------------------------------- +def launch_gui(command: str, delay_sec: float = 1.0): + """Launch GUI app on VM display without blocking script exit.""" + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + +print("Launching browsers...") +launch_gui(f'google-chrome "{AIRTABLE_URL}/?sid={sid}"', delay_sec=2.0) +print(f"OK: launched Airtable at {AIRTABLE_URL}/?sid={sid}") +launch_gui(f'google-chrome "{ASANA_URL}/?sid={sid}"', delay_sec=1.5) +print(f"OK: launched Asana at {ASANA_URL}/?sid={sid}") +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.0) +print(f"OK: launched Slack at {SLACK_URL}/?sid={sid}") + +print('GUI_READY: launched Airtable, Asana and Slack mock websites with DISPLAY=:0') +print(f'Session ID: {sid}') diff --git a/mktg_campaign_001/reward.py b/mktg_campaign_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1e8edd32ca8b1ad031f27a6f7f1d28d11eaf501b --- /dev/null +++ b/mktg_campaign_001/reward.py @@ -0,0 +1,180 @@ +""" +Reward Script: Summer Product Webinar campaign chain (Airtable -> Asana -> Slack) +Task ID: mktg_campaign_001 +Domain: mock_websites (airtable_mock, asana_mock, slack_mock) + +Scoring (deterministic, exact-match — no LLM judge; criteria are fully deterministic): + Component A — Airtable Campaigns record (0.40) + - record named 'Summer Product Webinar' exists in 'Campaigns' table (0.10) + - Target Audience == 'Mid-market SaaS marketers' (0.10) + - Channels == 'Email + LinkedIn' (0.10) + - Launch Date == '2026-07-20' (0.10) + Component B — Asana 'Q3 Campaigns' tasks (0.35) + - three NEW tasks named exactly 'Draft webinar landing page', + 'Build email sequence', 'Design social assets' under the project + (0.35 * matched/3) + Component C — Slack #marketing kickoff (0.25) + - a NEW message (beyond the initial snapshot) in #marketing that + mentions the 'Summer Product Webinar' campaign (0.25) + +Each component checks a task-introduced change (fails on initial_env, passes on golden_env). +""" +import json +import sys + +import requests + +MOCKS = { + 'airtable': 'http://28.7.184.198:8109', + 'asana': 'http://28.7.184.198:8114', + 'slack': 'http://28.7.184.198:8178', +} + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +# --- Fetch state from all three mocks --- +states = {} +for name, url in MOCKS.items(): + try: + resp = requests.get(f'{url}/go?sid={sid}', timeout=20) + resp.raise_for_status() + states[name] = resp.json() + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {url}/go?sid={sid}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def norm(v): + return str(v).strip() if v is not None else '' + + +def find_table_by_name(state, table_name): + for t in (state.get('tables') or {}).values(): + if norm(t.get('name')) == table_name: + return t + return None + + +def verify_task(): + total_score = 0.0 + + # ============================================================ + # Component A — Airtable Campaigns record (0.40) + # ============================================================ + try: + cur = states['airtable'].get('current_state') or {} + campaigns = find_table_by_name(cur, 'Campaigns') + if not campaigns: + print('FAIL: A — no Campaigns table in airtable current_state') + else: + # Build field NAME -> id map (robust to field id naming) + name_to_id = {norm(f.get('name')): f.get('id') for f in campaigns.get('fields', [])} + fid_name = name_to_id.get('Campaign Name') + fid_aud = name_to_id.get('Target Audience') + fid_chan = name_to_id.get('Channels') + fid_launch = name_to_id.get('Launch Date') + + # Locate the new record by its campaign name + rec = None + for r in campaigns.get('records', []): + if norm((r.get('fields') or {}).get(fid_name)) == 'Summer Product Webinar': + rec = r + break + + if rec is None: + print("FAIL: A — no 'Summer Product Webinar' record in Campaigns table") + else: + print("PASS: A.1 — 'Summer Product Webinar' record exists (0.10)") + total_score += 0.10 + f = rec.get('fields') or {} + + if norm(f.get(fid_aud)) == 'Mid-market SaaS marketers': + print('PASS: A.2 — Target Audience correct (0.10)') + total_score += 0.10 + else: + print(f"FAIL: A.2 — Target Audience expected 'Mid-market SaaS marketers', found {f.get(fid_aud)!r}") + + if norm(f.get(fid_chan)) == 'Email + LinkedIn': + print('PASS: A.3 — Channels correct (0.10)') + total_score += 0.10 + else: + print(f"FAIL: A.3 — Channels expected 'Email + LinkedIn', found {f.get(fid_chan)!r}") + + if norm(f.get(fid_launch)) == '2026-07-20': + print('PASS: A.4 — Launch Date correct (0.10)') + total_score += 0.10 + else: + print(f"FAIL: A.4 — Launch Date expected '2026-07-20', found {f.get(fid_launch)!r}") + except Exception as e: + print(f'ERROR: Component A — {e}') + + # ============================================================ + # Component B — Asana 'Q3 Campaigns' tasks (0.35) + # ============================================================ + try: + cur = states['asana'].get('current_state') or {} + # Resolve project id for 'Q3 Campaigns' + proj_id = None + for p in cur.get('projects', []): + if norm(p.get('name')) == 'Q3 Campaigns': + proj_id = p.get('projectId') + break + if proj_id is None: + print("FAIL: B — no 'Q3 Campaigns' project found in asana current_state") + else: + task_names = {norm(t.get('name')) for t in cur.get('tasks', []) + if t.get('projectId') == proj_id} + required = ['Draft webinar landing page', 'Build email sequence', 'Design social assets'] + matched = [r for r in required if r in task_names] + for r in required: + if r in task_names: + print(f"PASS: B — task '{r}' present under Q3 Campaigns") + else: + print(f"FAIL: B — task '{r}' missing under Q3 Campaigns") + comp_b = 0.35 * (len(matched) / 3.0) + total_score += comp_b + print(f'Component B score: {comp_b:.4f} ({len(matched)}/3 tasks)') + except Exception as e: + print(f'ERROR: Component B — {e}') + + # ============================================================ + # Component C — Slack #marketing kickoff message (0.25) + # ============================================================ + # #marketing already has pre-task messages mentioning the campaign in BOTH + # initial and golden, so we must score a NEWLY-ADDED message (beyond the + # initial snapshot), not mere substring presence. + try: + init = states['slack'].get('initial_state') or {} + cur = states['slack'].get('current_state') or {} + init_msgs = (init.get('messages') or {}).get('marketing', []) + cur_msgs = (cur.get('messages') or {}).get('marketing', []) + new_msgs = cur_msgs[len(init_msgs):] if len(cur_msgs) > len(init_msgs) else [] + if not new_msgs: + print('FAIL: C — no new message added to #marketing') + else: + mention = any('summer product webinar' in norm(m.get('content')).lower() for m in new_msgs) + if mention: + print('PASS: C — new #marketing message mentions Summer Product Webinar (0.25)') + total_score += 0.25 + else: + print('FAIL: C — new #marketing message(s) do not mention the Summer Product Webinar campaign') + 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/mktg_campaign_001/reward_label.json b/mktg_campaign_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..6e41260b4aa7afa8f0e428ba9cf4d1a08046da16 --- /dev/null +++ b/mktg_campaign_001/reward_label.json @@ -0,0 +1,55 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/mktg_campaign_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:27:33", + "label": { + "task_id": "mktg_campaign_001", + "domain": "mock_websites", + "summary": "验证用户在 Airtable 创建包含指定字段值的 Summer Product Webinar 营销活动记录,在 Asana 的 Q3 Campaigns 项目下添加三个指定任务,并在 Slack #marketing 频道发送提及该活动的新增消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "airtable_mock", + "asana_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component A — Airtable Campaigns record", + "weight": 0.4, + "description": "检查 Airtable 的 Campaigns 表中是否存在名为 Summer Product Webinar 的记录,且其 Target Audience、Channels、Launch Date 字段值完全匹配", + "check_logic": "在 states['airtable']['current_state'] 中查找名为 'Campaigns' 的表;建立字段名到字段 ID 的映射;定位 'Campaign Name' 为 'Summer Product Webinar' 的记录;逐项比较 'Target Audience'、'Channels'、'Launch Date' 的归一化字符串值", + "pass_condition": "记录存在且 Target Audience == 'Mid-market SaaS marketers'、Channels == 'Email + LinkedIn'、Launch Date == '2026-07-20',四项各得 0.10" + }, + { + "name": "Component B — Asana 'Q3 Campaigns' tasks", + "weight": 0.35, + "description": "检查 Asana 的 Q3 Campaigns 项目下是否新增了三个指定任务", + "check_logic": "在 states['asana']['current_state'] 中查找 'Q3 Campaigns' 项目并获取 projectId;筛选 projectId 匹配的任务列表;检查任务名是否包含 'Draft webinar landing page'、'Build email sequence'、'Design social assets';得分 = 0.35 × (匹配数/3)", + "pass_condition": "三个任务全部存在于 Q3 Campaigns 项目下,得 0.35;部分匹配则按比例得分" + }, + { + "name": "Component C — Slack #marketing kickoff message", + "weight": 0.25, + "description": "检查 Slack #marketing 频道中是否有任务期间新增的消息提及该活动", + "check_logic": "对比 states['slack']['initial_state'] 与 ['current_state'] 中 messages['marketing'] 列表长度,取 cur_msgs[len(init_msgs):] 作为新增消息;对新增消息内容做归一化并转小写后,检查是否包含子串 'summer product webinar'", + "pass_condition": "存在至少一条新增消息且内容包含 'summer product webinar'(不区分大小写)" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加得到 total_score,最终通过 round(min(total_score, 1.0), 4) 钳制到上限 1.0 并四舍五入到 4 位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取非空 sid 时,脚本打印 CRITICAL 并立即以 REWARD: 0.0 退出", + "无法从任一 mock 服务(airtable/asana/slack)成功获取 JSON 状态时,脚本打印 CRITICAL 并立即以 REWARD: 0.0 退出", + "Airtable 中缺少 Campaigns 表、找不到 'Summer Product Webinar' 记录、或 Target Audience/Channels/Launch Date 字段值不匹配,导致对应子项不得分", + "Asana 中缺少 'Q3 Campaigns' 项目,或三个指定任务未全部创建,导致 Component B 按比例得分(0.35 × 匹配数/3)", + "Slack #marketing 频道无新增消息,或新增消息内容未包含 'summer product webinar',导致 Component C 不得分", + "各组件内部发生异常时被捕获,打印 ERROR 后该组件不得分,但脚本继续执行后续组件" + ], + "scoring_logic_explanation": "1. 从 /tmp/task_web_sid 读取 session ID,失败则直接返回 0.0。2. 分别向 airtable_mock、asana_mock、slack_mock 发送 HTTP GET 请求获取状态(slack 需同时获取 initial_state 与 current_state),任一失败则直接返回 0.0。3. Component A(0.40):在 Airtable current_state 中查找 'Campaigns' 表,建立字段名到字段 ID 的映射,定位 'Campaign Name' 为 'Summer Product Webinar' 的记录;记录存在得 0.10,再逐项检查 Target Audience、Channels、Launch Date 是否分别等于 'Mid-market SaaS marketers'、'Email + LinkedIn'、'2026-07-20',每项正确各加 0.10。4. Component B(0.35):在 Asana current_state 中查找 'Q3 Campaigns' 项目并获取 projectId,筛选该项目下的任务,检查是否包含 'Draft webinar landing page'、'Build email sequence'、'Design social assets',按匹配数量计算 0.35 × (matched/3)。5. Component C(0.25):在 Slack 中通过对比 initial_state 与 current_state 的 #marketing 消息列表长度提取新增消息(cur_msgs[len(init_msgs):]),若新增消息中存在内容包含 'summer product webinar'(不区分大小写)的消息,则得 0.25。6. 将各组件得分累加,最终分数为 round(min(total_score, 1.0), 4)。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: mktg_campaign_001(从 docstring 中明确提取)\n - Domain: mock_websites (airtable_mock, asana_mock, slack_mock)(从 docstring 中提取)\n\n2. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - `http://28.7.186.212:8129` (airtable_mock)\n - `http://28.7.186.212:8134` (asana_mock)\n - `http://28.7.186.212:8198` (slack_mock)\n\n3. **评分组件**:\n\n **Component A (0.40)**:\n - A.1: Airtable 的 Campaigns 表中存在名为 'Summer Product Webinar' 的记录 (0.10)\n - A.2: Target Audience == 'Mid-market SaaS marketers' (0.10)\n - A.3: Channels == 'Email + LinkedIn' (0.10)\n - A.4: Launch Date == '2026-07-20' (0.10)\n - 逻辑:先找 Campaigns 表,然后建立字段名到 ID 的映射,再找记录,逐项检查字段值。\n\n **Component B (0.35)**:\n - 在 Asana 的 'Q3 Campaigns' 项目下有三个任务:'Draft webinar landing page', 'Build email sequence', 'Design social assets'\n - 分数计算:0.35 * (matched / 3)\n - 逻辑:找项目 ID,然后筛选该项目的任务,检查任务名是否匹配。\n\n **Component C (0.25)**:\n - 在 Slack 的 #marketing 频道中,有新增消息(超出 initial snapshot)提到 'Summer Product Webinar'\n - 逻辑:比较 initial_state 和 current_state 的 messages.marketing 列表长度,取新增消息,检查是否有消息内容包含 'summer product webinar'(不区分大小写)。\n\n4. **分数汇总**:\n - 各组件分数相加\n - 最后 `final_score = round(min(total_score, 1.0), 4)`\n - 所以是相加后钳制到 1.0\n\n5. **失败模式**:\n - 读取 sid 失败(/tmp/task_web_sid 不存在或为空):打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 从任一 mock 服务获取状态失败:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - Component A 中找不到 Campaigns 表、找不到记录、字段值不匹配:对应子项不得分\n - Component B 中找不到 Q3 Campaigns 项目、任务缺失:按比例扣分\n - Component C 中无新消息、新消息未提及 campaign:不得分\n - 各组件内部的异常被捕获,打印 ERROR,该组件不得分,但不影响其他组件\n\n6. **is_placeholder**:\n - false,因为脚本有详细的检查逻辑,不是占位脚本。\n\n7. **confidence**:\n - 1.0,因为代码逻辑清晰,我完全理解。\n\n现在构建 JSON:\n\n- task_id: \"mktg_campaign_001\"\n- domain: \"mock_websites\"\n- summary: \"验证用户在 Airtable 创建 Summer Product Webinar 营销活动记录、在 Asana Q3 Campaigns 项目添加三个指定任务、并在 Slack #marketing 频道发送提及该活动的新消息\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"airtable_mock\", \"asana_mock\", \"slack_mock\"]\n- scoring_components: 三个组件\n - Component A: weight 0.40,但内部是四个 0.10 的子项。根据要求 \"weight 字段填写代码中显式给出的分值(如 0.3)\"。Component A 整体是 0.40,但内部是逐项加分。我可以把 Component A 作为一个整体组件,weight 0.40,description 说明包含四个子项,check_logic 说明逐项检查。或者拆成四个?docstring 说 Component A — Airtable Campaigns record (0.40),然后内部有四个 0.10。我觉得作为一个组件更合适,但 check_logic 要说明四个子条件。不过 weight 填 0.40。\n \n 等等,让我再看要求:\"weight 字段填写代码中显式给出的分值(如 0.3);若代码未显式分值但有通过/失败二值判定,weight 填 1.0 并在 check_logic 中说明。\"\n \n 这里 Component A 整体是 0.40,内部是 0.10 x 4。Component B 是 0.35 * matched/3。Component C 是 0.25。\n \n 我可以这样列:\n 1. Component A - Airtable Campaigns record, weight 0.40\n 2. Component B - Asana Q3 Campaigns tasks, weight 0.35\n 3. Component C - Slack #marketing kickoff, weight 0.25\n \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 失败或为空时,脚本打印 CRITICAL 并立即退出,返回 0.0\",\n \"从任一 mock 服务(airtable/asana/slack)拉取状态失败时,脚本打印 CRITICAL 并立即退出,返回 0.0\",\n \"Airtable 中缺少 Campaigns 表、找不到 Summer Product Webinar 记录、或字段值不匹配,导致对应子项不得分\",\n \"Asana 中缺少 Q3 Campaigns 项目或任务缺失,导致按比例扣分(0.35 * matched/3)\",\n \"Slack #marketing 频道无新增消息或新增消息未提及 Summer Product Webinar,导致 Component C 不得分\",\n \"各组件内部异常被捕获后打印 ERROR,该组件不得分但不影响其他组件\"\n ]\n- scoring_logic_explanation: 详细按执行顺序说明\n- confidence: 1.0\n\n让我再仔细检查一下 Component A 的 weight。代码中 total_score += 0.10 四次,总共 0.40。所以 Component A 的 weight 应该是 0.40。\n\nComponent B: total_score += comp_b,其中 comp_b = 0.35 * (len(matched) / 3.0)。weight 0.35。\n\nComponent C: total_score += 0.25。weight 0.25。\n\n完美。\n\n现在写 JSON,确保:\n- 只输出 JSON 对象\n- 不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n\n让我组织中文描述:\n\nsummary: \"验证用户在 Airtable 创建包含指定字段值的 Summer Product Webinar 营销活动记录,在 Asana 的 Q3 Campaigns 项目下添加三个指定任务,并在 Slack #marketing 频道发送提及该活动的新增消息\"\n\nscoring_logic_explanation: \n\"1. 从 /tmp/task_web_sid 读取 session ID,失败则直接返回 0.0。\n2. 分别向 airtable_mock、asana_mock、slack_mock 三个服务发送 HTTP GET 请求获取 current_state 和 initial_state(slack 需要 initial_state),任一失败则直接返回 0.0。\n3. Component A(0.40):在 Airtable 的 current_state 中查找名为 'Campaigns' 的表,建立字段名到字段 ID 的映射,定位 'Campaign Name' 为 'Summer Product Webinar' 的记录。若记录存在得 0.10;再检查该记录的 'Target Audience' 是否为 'Mid-market SaaS marketers'(0.10)、'Channels' 是否为 'Email + LinkedIn'(0.10)、'Launch Date' 是否为 '2026-07-20'(0.10),逐项加分。\n4. Component B(0.35):在 Asana 的 current_state 中查找名为 'Q3 Campaigns' 的项目,获取其 projectId,再筛选属于该项目的任务。检查是否包含 'Draft webinar landing page'、'Build email sequence'、'Design social assets' 三个任务,按匹配数量计算得分 0.35 × (matched/3)。\n5. Component C(0.25):在 Slack 中比较 initial_state 与 current_state 的 #marketing 消息列表,提取新增消息(cur_msgs[len(init_msgs):])。若新增消息中存在内容包含 'summer product webinar'(不区分大小写)的消息,则得 0.25。\n6. 将各组件得分累加得到 total_score,最终分数为 round(min(total_score, 1.0), 4)。\"\n\n检查 data_sources:代码中 MOCKS 的 URL 是 IP 地址,但通常我们按服务名标识。docstring 中写的是 airtable_mock, asana_mock, slack_mock。URL 是 http://28.7.186.212:8129 等。我应该写 mock 服务名还是 URL?要求说 \"如 slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid 等\",所以我写 [\"airtable_mock\", \"asana_mock\", \"slack_mock\", \"/tmp/task_web_sid\"] 更合适。\n\nfailure_modes 再完善:\n- \"无法从 /tmp/task_web_sid 读取非空 sid 时,脚本打印 CRITICAL 并立即以 REWARD: 0.0 退出\"\n- \"无法从任一 mock 服务(airtable/asana/slack)成功获取 JSON 状态时,脚本打印 CRITICAL 并立即以 REWARD: 0.0 退出\"\n- \"Airtable 中缺少 Campaigns 表、找不到 'Summer Product Webinar' 记录、或 Target Audience/Channels/Launch Date 字段值不匹配,导致对应子项不得分\"\n- \"Asana 中缺少 'Q3 Campaigns' 项目,或三个指定任务未全部创建,导致 Component B 按比例得分(0.35 × 匹配数/3)\"\n- \"Slack #marketing 频道无新增消息,或新增消息内容未包含 'summer product webinar',导致 Component C 不得分\"\n- \"各组件内部发生异常时被捕获,打印 ERROR 后该组件不得分,但脚本继续执行后续组件\"\n\n所有内容都准备好了。现在输出纯 JSON。 {\"task_id\":\"mktg_campaign_001\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Airtable 创建包含指定字段值的 Summer Product Webinar 营销活动记录,在 Asana 的 Q3 Campaigns 项目下添加三个指定任务,并在 Slack #marketing 频道发送提及该活动的新增消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"airtable_mock\",\"asana_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component A — Airtable Campaigns record\",\"weight\":0.4,\"description\":\"检查 Airtable 的 Campaigns 表中是否存在名为 Summer Product Webinar 的记录,且其 Target Audience、Channels、Launch Date 字段值完全匹配\",\"check_logic\":\"在 states['airtable']['current_state'] 中查找名为 'Campaigns' 的表;建立字段名到字段 ID 的映射;定位 'Campaign Name' 为 'Summer Product Webinar' 的记录;逐项比较 'Target Audience'、'Channels'、'Launch Date' 的归一化字符串值\",\"pass_condition\":\"记录存在且 Target Audience == 'Mid-market SaaS marketers'、Channels == 'Email + LinkedIn'、Launch Date == '2026-07-20',四项各得 0.10\"},{\"name\":\"Component B — Asana 'Q3 Campaigns' tasks\",\"weight\":0.35,\"description\":\"检查 Asana 的 Q3 Campaigns 项目下是否新增了三个指定任务\",\"check_logic\":\"在 states['asana']['current_state'] 中查找 'Q3 Campaigns' 项目并获取 projectId;筛选 projectId 匹配的任务列表;检查任务名是否包含 'Draft webinar landing page'、'Build email sequence'、'Design social assets';得分 = 0.35 × (匹配数/3)\",\"pass_condition\":\"三个任务全部存在于 Q3 Campaigns 项目下,得 0.35;部分匹配则按比例得分\"},{\"name\":\"Component C — Slack #marketing kickoff message\",\"weight\":0.25,\"description\":\"检查 Slack #marketing 频道中是否有任务期间新增的消息提及该活动\",\"check_logic\":\"对比 states['slack']['initial_state'] 与 ['current_state'] 中 messages['marketing'] 列表长度,取 cur_msgs[len(init_msgs):] 作为新增消息;对新增消息内容做归一化并转小写后,检查是否包含子串 'summer product webinar'\",\"pass_condition\":\"存在至少一条新增消息且内容包含 'summer product webinar'(不区分大小写)\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加得到 total_score,最终通过 round(min(total_score, 1.0), 4) 钳制到上限 1.0 并四舍五入到 4 位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取非空 sid 时,脚本打印 CRITICAL 并立即以 REWARD: 0.0 退出\",\"无法从任一 mock 服务(airtable/asana/slack)成功获取 JSON 状态时,脚本打印 CRITICAL 并立即以 REWARD: 0.0 退出\",\"Airtable 中缺少 Campaigns 表、找不到 'Summer Product Webinar' 记录、或 Target Audience/Channels/Launch Date 字段值不匹配,导致对应子项不得分\",\"Asana 中缺少 'Q3 Campaigns' 项目,或三个指定任务未全部创建,导致 Component B 按比例得分(0.35 × 匹配数/3)\",\"Slack #marketing 频道无新增消息,或新增消息内容未包含 'summer product webinar',导致 Component C 不得分\",\"各组件内部发生异常时被捕获,打印 ERROR 后该组件不得分,但脚本继续执行后续组件\"],\"scoring_logic_explanation\":\"1. 从 /tmp/task_web_sid 读取 session ID,失败则直接返回 0.0。2. 分别向 airtable_mock、asana_mock、slack_mock 发送 HTTP GET 请求获取状态(slack 需同时获取 initial_state 与 current_state),任一失败则直接返回 0.0。3. Component A(0.40):在 Airtable current_state 中查找 'Campaigns' 表,建立字段名到字段 ID 的映射,定位 'Campaign Name' 为 'Summer Product Webinar' 的记录;记录存在得 0.10,再逐项检查 Target Audience、Channels、Launch Date 是否分别等于 'Mid-market SaaS marketers'、'Email + LinkedIn'、'2026-07-20',每项正确各加 0.10。4. Component B(0.35):在 Asana current_state 中查找 'Q3 Campaigns' 项目并获取 projectId,筛选该项目下的任务,检查是否包含 'Draft webinar landing page'、'Build email sequence'、'Design social assets',按匹配数量计算 0.35 × (matched/3)。5. Component C(0.25):在 Slack 中通过对比 initial_state 与 current_state 的 #marketing 消息列表长度提取新增消息(cur_msgs[len(init_msgs):]),若新增消息中存在内容包含 'summer product webinar'(不区分大小写)的消息,则得 0.25。6. 将各组件得分累加,最终分数为 round(min(total_score, 1.0), 4)。\",\"confidence\":1.0}" +} diff --git a/mktg_campaign_create_004/_cua_gym_vm_bridge.sh b/mktg_campaign_create_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_campaign_create_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/mktg_campaign_create_004/initial_setup.py b/mktg_campaign_create_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..255abf6d283afa784dd8b7d3e3fa925359003faa --- /dev/null +++ b/mktg_campaign_create_004/initial_setup.py @@ -0,0 +1,396 @@ +""" +Initial Setup: Create Airtable campaign record + Asana execution task. +Task ID: mktg_campaign_create_004 +Domain: mock_websites (airtable + asana) + +This script establishes the PRE-TASK state: + - Airtable: base 'Campaign Ops', table 'Campaigns' with 5 columns and 3 existing + campaign records. NO record named 'Summer SaaS Launch 2026'. + - Asana: project 'Campaign Execution' with 3 existing tasks. NO task titled + 'Execute: Summer SaaS Launch 2026'. + +It injects this state into BOTH mocks via action:"set" (same sid across both), +launches a Chrome window for each mock, and blocks until both render. +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# ---------------------------------------------------------------------------- +# Config +# ---------------------------------------------------------------------------- +AIRTABLE_URL = 'http://28.7.184.198:8109' +ASANA_URL = 'http://28.7.184.198:8114' + +CURRENT_USER = { + "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": "San Francisco, CA", + "timezone": "PST", + "theme": "light", +} + +USERS = [ + {"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": "San Francisco, CA", "timezone": "PST", "theme": "light"}, + {"userId": "user-1", "name": "Sarah Chen", "email": "sarah.chen@company.com", + "avatar": "https://picsum.photos/100/100?random=user1", "title": "Senior Designer", + "department": "Design", "location": "New York, NY", "timezone": "EST", "theme": "light"}, + {"userId": "user-2", "name": "Mike Rodriguez", "email": "mike.rodriguez@company.com", + "avatar": "https://picsum.photos/100/100?random=user2", "title": "Lead Engineer", + "department": "Engineering", "location": "Austin, TX", "timezone": "CST", "theme": "dark"}, + {"userId": "user-3", "name": "Emily Watson", "email": "emily.watson@company.com", + "avatar": "https://picsum.photos/100/100?random=user3", "title": "Marketing Manager", + "department": "Marketing", "location": "Chicago, IL", "timezone": "CST", "theme": "light"}, +] + + +# ---------------------------------------------------------------------------- +# Build Airtable initial state +# ---------------------------------------------------------------------------- +def build_airtable_state(): + base_id = "base_campaign_ops" + table_id = "tbl_campaigns" + f_name = "fld_camp_name" + f_audience = "fld_camp_audience" + f_channels = "fld_camp_channels" + f_launch = "fld_camp_launch" + f_status = "fld_camp_status" + + records = [ + { + "id": "rec_winter_reboot", + "createdTime": "2026-01-10T09:00:00.000Z", + "fields": { + f_name: "Winter Reboot 2025", + f_audience: "Enterprise SaaS procurement teams", + f_channels: "Email, Webinar", + f_launch: "2025-12-01", + f_status: "Completed", + }, + }, + { + "id": "rec_spring_nurture", + "createdTime": "2026-02-15T09:00:00.000Z", + "fields": { + f_name: "Spring Nurture Sequence", + f_audience: "Mid-market SaaS operations leaders", + f_channels: "Email, LinkedIn", + f_launch: "2026-03-20", + f_status: "Active", + }, + }, + { + "id": "rec_q2_webinar", + "createdTime": "2026-04-01T09:00:00.000Z", + "fields": { + f_name: "Q2 Webinar Series", + f_audience: "SMB SaaS founders", + f_channels: "Webinar, LinkedIn", + f_launch: "2026-05-05", + f_status: "Planned", + }, + }, + ] + + tables = { + table_id: { + "id": table_id, + "name": "Campaigns", + "baseId": base_id, + "fields": [ + {"id": f_name, "name": "Campaign Name", "type": "text", "primary": True}, + {"id": f_audience, "name": "Target Audience", "type": "text"}, + {"id": f_channels, "name": "Channels", "type": "text"}, + {"id": f_launch, "name": "Launch Date", "type": "date"}, + {"id": f_status, "name": "Status", "type": "single_select", "options": [ + {"id": "opt_planned", "name": "Planned", "color": "bg-blue-100 text-blue-800"}, + {"id": "opt_active", "name": "Active", "color": "bg-green-100 text-green-800"}, + {"id": "opt_paused", "name": "Paused", "color": "bg-yellow-100 text-yellow-800"}, + {"id": "opt_completed", "name": "Completed", "color": "bg-gray-100 text-gray-800"}, + ]}, + ], + "records": records, + "views": [ + {"id": "view_campaigns_grid", "name": "Grid view", "type": "grid", + "filters": [], "sorts": [], "groupBy": [], "hiddenFieldIds": [], + "fieldWidths": {}, "rowHeight": "short"}, + ], + "activeViewId": "view_campaigns_grid", + } + } + + bases = { + base_id: { + "id": base_id, + "name": "Campaign Ops", + "color": "bg-orange-500", + "tables": [table_id], + } + } + + return { + "currentUser": { + "id": "user_1", + "name": "Alex Johnson", + "email": "alex.johnson@example.com", + "avatar": "https://ui-avatars.com/api/?name=Alex+Johnson&background=8B5CF6&color=fff", + }, + "collaborators": [ + {"id": "user_1", "name": "Alex Johnson", "email": "alex.johnson@example.com", + "avatar": "https://ui-avatars.com/api/?name=Alex+Johnson&background=8B5CF6&color=fff"}, + {"id": "user_2", "name": "Priya Nair", "email": "priya.nair@example.com", + "avatar": "https://ui-avatars.com/api/?name=Priya+Nair&background=EC4899&color=fff"}, + ], + "bases": bases, + "tables": tables, + "activeBaseId": base_id, + "activeTableId": table_id, + "ui": { + "viewSidebarOpen": False, + "expandedRecordId": None, + "searchQuery": "", + "isSearching": False, + }, + "activityLog": [], + } + + +# ---------------------------------------------------------------------------- +# Build Asana initial state +# ---------------------------------------------------------------------------- +def build_asana_state(): + project_id = "project_campaign_exec" + section_ids = [ + "section_exec_todo", + "section_exec_inprogress", + "section_exec_done", + ] + + project = { + "projectId": project_id, + "name": "Campaign Execution", + "teamId": "team-3", + "description": "Cross-channel campaign execution tracking", + "color": "#6e3ec8", + "icon": "bullhorn", + "ownerId": "user-0", + "memberIds": ["user-0", "user-1", "user-2", "user-3"], + "sections": [ + {"sectionId": section_ids[0], "name": "To Do", "collapsed": False}, + {"sectionId": section_ids[1], "name": "In Progress", "collapsed": False}, + {"sectionId": section_ids[2], "name": "Done", "collapsed": False}, + ], + "customFields": [], + "privacy": "public", + "startDate": "2026-06-01", + "dueDate": "2026-08-31", + "archived": False, + "starred": True, + "createdDate": "2026-06-01T00:00:00Z", + "modifiedDate": "2026-06-01T00:00:00Z", + } + + tasks = [ + { + "taskId": "task_exec_1", + "name": "Finalize campaign brief", + "projectId": project_id, + "sectionId": section_ids[0], + "description": "Consolidate target audience and channel plan into a single brief.", + "assigneeId": "user-3", + "creatorId": "user-0", + "dueDate": "2026-06-20", + "startDate": None, + "completed": False, + "completedDate": None, + "parentTaskId": None, + "dependencies": [], + "tags": ["planning"], + "attachmentIds": [], + "customFieldValues": {}, + "likeCount": 0, + "createdDate": "2026-06-01T00:00:00Z", + "modifiedDate": "2026-06-01T00:00:00Z", + }, + { + "taskId": "task_exec_2", + "name": "Build email templates", + "projectId": project_id, + "sectionId": section_ids[1], + "description": "Create the HTML email templates for the nurture sequence.", + "assigneeId": "user-1", + "creatorId": "user-0", + "dueDate": "2026-06-28", + "startDate": None, + "completed": False, + "completedDate": None, + "parentTaskId": None, + "dependencies": ["task_exec_1"], + "tags": ["email"], + "attachmentIds": [], + "customFieldValues": {}, + "likeCount": 0, + "createdDate": "2026-06-01T00:00:00Z", + "modifiedDate": "2026-06-01T00:00:00Z", + }, + { + "taskId": "task_exec_3", + "name": "Schedule LinkedIn posts", + "projectId": project_id, + "sectionId": section_ids[0], + "description": "Queue the LinkedIn organic posts for the launch window.", + "assigneeId": "user-2", + "creatorId": "user-0", + "dueDate": "2026-07-05", + "startDate": None, + "completed": False, + "completedDate": None, + "parentTaskId": None, + "dependencies": [], + "tags": ["social"], + "attachmentIds": [], + "customFieldValues": {}, + "likeCount": 0, + "createdDate": "2026-06-01T00:00:00Z", + "modifiedDate": "2026-06-01T00:00:00Z", + }, + ] + + return { + "currentUser": CURRENT_USER, + "users": USERS, + "teams": [ + {"teamId": "team-3", "name": "Marketing", "description": "Marketing team", + "memberIds": ["user-0", "user-1", "user-2", "user-3"], "ownerId": "user-0", + "privacy": "public", "createdDate": "2026-01-01T00:00:00Z"}, + ], + "projects": [project], + "tasks": tasks, + "comments": [], + "portfolios": [], + "goals": [], + "notifications": [], + "attachments": [], + } + + +# ---------------------------------------------------------------------------- +# Inject state +# ---------------------------------------------------------------------------- +def main(): + # The mock servers (Airtable :8129, Asana :8134) are SHARED between the + # initial_env and golden_env VMs. To keep the two environments isolated despite + # sharing the physical server, we use a DISTINCT sid per environment. This script + # (initial_setup.py) runs ONLY on initial_env and uses the '_initial' sid, which + # holds the BASELINE (3 records, 3 tasks, no Summer entry). The golden_patch.py + # uses the '_golden' sid, which holds the TARGET (4 records, 4 tasks). Because the + # reward script reads /tmp/task_web_sid on each VM, initial_env sees '_initial' + # (reward 0.0) and golden_env sees '_golden' (reward 1.0). + sid = 'prof16_campaign_create_001_initial' + with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + mocks = { + 'airtable': AIRTABLE_URL, + 'asana': ASANA_URL, + } + states = { + 'airtable': build_airtable_state(), + 'asana': build_asana_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} set failed: {resp.text}' + print(f'[{name}] initial state injected (sid={sid})') + + # Verify + for name, url in mocks.items(): + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go['initial_state'] is not None, f'{name} initial_state is None' + print('Verified: both mocks have initial_state set') + + # Launch a Chrome window for EACH mock + def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + + for name, url in mocks.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.5) + + wait_for_mocks_loaded(mocks, sid) + print(f'GUI_READY: all {len(mocks)} mocks launched and verified (sid={sid})') + + +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND the page renders real content.""" + 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() + + +if __name__ == '__main__': + main() diff --git a/mktg_campaign_create_004/reward.py b/mktg_campaign_create_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..c06554a05a9303d055cb881fd82e69eb86ce7ac0 --- /dev/null +++ b/mktg_campaign_create_004/reward.py @@ -0,0 +1,220 @@ +""" +Reward Script: Create a campaign record (Airtable) and its execution task (Asana) +Task ID: mktg_campaign_create_004 +Domain: mock_websites (Airtable :8129 + Asana :8134) +Scoring: + Component 1 (0.5): Airtable 'Campaigns' has new record 'Summer SaaS Launch 2026' + with exact field values. + Component 2 (0.3): Asana 'Campaign Execution' has new task 'Execute: Summer SaaS + Launch 2026' with exact description, due date, assignee. + Component 3 (0.2): Exactly one new record + one new task added; the 3 pre-existing + records/tasks are preserved unchanged. +The reward script reads the sid from /tmp/task_web_sid on whichever VM it runs on, +so the SAME script scores 0.0 on the initial_env (baseline sid) and 1.0 on the +golden_env (target sid). No sid is hardcoded. +""" +import json +import sys + +import requests + +# --- Read sid from the LOCAL VM's /tmp/task_web_sid (NOT hardcoded) --- +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) + +# Mock server URLs (per task_config.json) +AIRTABLE_URL = 'http://28.7.184.198:8109' +ASANA_URL = 'http://28.7.184.198:8114' + +# Expected field IDs (from the injected Campaigns table schema, observed on VM) +FLD_NAME = 'fld_camp_name' +FLD_AUDIENCE = 'fld_camp_audience' +FLD_CHANNELS = 'fld_camp_channels' +FLD_LAUNCH = 'fld_camp_launch' +FLD_STATUS = 'fld_camp_status' + +# Ground-truth values from task_config.json context +EXP_NAME = 'Summer SaaS Launch 2026' +EXP_AUDIENCE = 'Mid-market SaaS operations leaders' +EXP_CHANNELS = 'Email, LinkedIn, Webinar' +EXP_LAUNCH = '2026-07-15' +EXP_STATUS = 'Planned' + +EXP_TASK_NAME = 'Execute: Summer SaaS Launch 2026' +EXP_TASK_DESC = 'Run Email + LinkedIn + Webinar per Airtable plan; launch 2026-07-15' +EXP_TASK_DUE = '2026-07-15' +EXP_TASK_ASSIGNEE = 'user-0' + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility. + + Parsed by the evaluator to report which sub-objectives passed/failed + instead of only a single aggregate float. Format: ``COMPONENT: ``. + """ + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check 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 + + +# --- Fetch helpers (real HTTP state reads) --- + +def _fetch_current_state(base_url, key): + """Fetch current_state from a mock's /go?sid= endpoint. Returns dict or None.""" + try: + resp = requests.get(f'{base_url}/go?sid={SID}', timeout=15) + resp.raise_for_status() + data = resp.json() + except Exception as e: + print(f'CRITICAL: Cannot fetch {base_url}/go?sid={SID}: {e}') + return None + cs = data.get('current_state') + if cs is None: + print(f'CRITICAL: current_state is None for {base_url}') + return None + # Drill into the relevant sub-key (e.g. 'tables' for airtable mock) + if key: + return cs.get(key) + return cs + + +# --- Per-component checks (one function per sub-objective) --- + +def check_component_1(airtable_state): + """Airtable 'Campaigns' contains a new record named 'Summer SaaS Launch 2026' + with exactly the required field values. Pass condition: a record exists whose + Campaign Name == 'Summer SaaS Launch 2026', Target Audience == 'Mid-market SaaS + operations leaders', Channels == 'Email, LinkedIn, Webinar', Launch Date == + '2026-07-15', Status == 'Planned'. + """ + if not airtable_state: + return False, 0.0, 'no Airtable state' + tables = airtable_state.get('tables', {}) + tbl = tables.get('tbl_campaigns') + if not tbl: + return False, 0.0, 'tbl_campaigns not found' + records = tbl.get('records', []) + for r in records: + f = r.get('fields', {}) + if f.get(FLD_NAME) == EXP_NAME: + ok = ( + f.get(FLD_AUDIENCE) == EXP_AUDIENCE and + f.get(FLD_CHANNELS) == EXP_CHANNELS and + f.get(FLD_LAUNCH) == EXP_LAUNCH and + f.get(FLD_STATUS) == EXP_STATUS + ) + if ok: + return True, 0.5, f'found record with exact field values (id={r.get("id")})' + return False, 0.0, ( + f'record name matches but values differ: ' + f'audience={f.get(FLD_AUDIENCE)!r} channels={f.get(FLD_CHANNELS)!r} ' + f'launch={f.get(FLD_LAUNCH)!r} status={f.get(FLD_STATUS)!r}' + ) + return False, 0.0, f'no record named {EXP_NAME!r} in tbl_campaigns' + + +def check_component_2(asana_state): + """Asana 'Campaign Execution' contains a new task titled 'Execute: Summer SaaS + Launch 2026' with the exact description, due date 2026-07-15, and assignee + user-0. Pass condition: a task with matching name, description, dueDate, assigneeId. + """ + if not asana_state: + return False, 0.0, 'no Asana state' + tasks = asana_state.get('tasks', []) + for t in tasks: + if t.get('name') == EXP_TASK_NAME: + ok = ( + t.get('description') == EXP_TASK_DESC and + t.get('dueDate') == EXP_TASK_DUE and + t.get('assigneeId') == EXP_TASK_ASSIGNEE + ) + if ok: + return True, 0.3, f'found task with exact title/desc/due/assignee (id={t.get("taskId")})' + return False, 0.0, ( + f'task name matches but values differ: ' + f'description={t.get("description")!r} dueDate={t.get("dueDate")!r} ' + f'assigneeId={t.get("assigneeId")!r}' + ) + return False, 0.0, f'no task named {EXP_TASK_NAME!r}' + + +def check_component_3(airtable_state, asana_state, comp1_pass, comp2_pass): + """Exactly one new record and one new task were added (counts 4 each) and the 3 + pre-existing records/tasks are preserved. Pass condition: Airtable now has 4 + records (was 3) AND Asana now has 4 tasks (was 3), and components 1 & 2 both pass. + """ + if not (comp1_pass and comp2_pass): + return False, 0.0, 'requires components 1 and 2 to pass first' + if not airtable_state or not asana_state: + return False, 0.0, 'missing state' + tbl = airtable_state.get('tables', {}).get('tbl_campaigns', {}) + rec_count = len(tbl.get('records', [])) + task_count = len(asana_state.get('tasks', [])) + if rec_count == 4 and task_count == 4: + return True, 0.2, f'record count={rec_count}, task count={task_count} (was 3/3)' + return False, 0.0, f'expected 4 records and 4 tasks, got {rec_count} records / {task_count} tasks' + + +def verify_task(): + """Verify task completion with progressive scoring.""" + # Fetch real state from each mock using the LOCAL VM's sid. + airtable_state = _fetch_current_state(AIRTABLE_URL, key=None) + asana_state = _fetch_current_state(ASANA_URL, key=None) + + if airtable_state is None or asana_state is None: + print('REWARD: 0.0') + return 0.0 + + total_score = 0.0 + + # Independent components 1 & 2. + _, c1_score, _ = _run_component( + 1, 'Airtable Summer SaaS Launch 2026 record', 0.5, + check_component_1, (airtable_state,)) + total_score += c1_score + + _, c2_score, _ = _run_component( + 2, 'Asana Execute task (title/desc/due/assignee)', 0.3, + check_component_2, (asana_state,)) + total_score += c2_score + + # Dependent component 3 (needs c1 & c2 results). + _, c3_score, _ = _run_component( + 3, 'Exactly 4 records + 4 tasks (pre-existing preserved)', 0.2, + check_component_3, (airtable_state, asana_state, c1_score > 0, c2_score > 0)) + total_score += c3_score + + final_score = round(min(total_score, 1.0), 4) + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +verify_task() diff --git a/mktg_campaign_create_004/reward_label.json b/mktg_campaign_create_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..9d462d2931f18e94b777199cbb362f32a7858575 --- /dev/null +++ b/mktg_campaign_create_004/reward_label.json @@ -0,0 +1,54 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof16_campaign_create_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:28:45", + "label": { + "task_id": "mktg_campaign_create_004", + "domain": "mock_websites", + "summary": "验证在 Airtable 创建指定 Campaign 记录并在 Asana 创建对应执行任务,且仅新增一条记录和一个任务、保留原有数据", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8129", + "http://28.7.186.212:8134" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.5, + "description": "检查 Airtable Campaigns 表中是否存在名为 'Summer SaaS Launch 2026' 的新记录,且其字段值与预期完全一致", + "check_logic": "遍历 airtable_state['tables']['tbl_campaigns']['records'],查找 fields['fld_camp_name'] == 'Summer SaaS Launch 2026' 的记录;找到后依次校验 fields['fld_camp_audience']、fields['fld_camp_channels']、fields['fld_camp_launch']、fields['fld_camp_status'] 是否分别等于预期字符串;全部匹配则通过,否则失败", + "pass_condition": "Airtable tbl_campaigns 中存在一条 Campaign Name 为 'Summer SaaS Launch 2026' 的记录,且 Target Audience、Channels、Launch Date、Status 四个字段与预期值完全相等" + }, + { + "name": "Component 2", + "weight": 0.3, + "description": "检查 Asana 中是否存在名为 'Execute: Summer SaaS Launch 2026' 的新任务,且其描述、截止日期、负责人与预期完全一致", + "check_logic": "遍历 asana_state['tasks'],查找 name == 'Execute: Summer SaaS Launch 2026' 的任务;找到后依次校验 description、dueDate、assigneeId 是否分别等于预期字符串;全部匹配则通过,否则失败", + "pass_condition": "Asana tasks 中存在一条 name 为 'Execute: Summer SaaS Launch 2026' 的任务,且 description、dueDate、assigneeId 与预期值完全相等" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "检查 Airtable 和 Asana 中各自恰好新增了一条数据,原有 3 条记录/任务未被改动", + "check_logic": "先判断 comp1_pass 与 comp2_pass 均为 True,否则直接失败;然后分别计算 Airtable tbl_campaigns 的 records 长度与 Asana 的 tasks 长度,要求两者均等于 4(原有 3 条 + 新增 1 条)", + "pass_condition": "Component 1 和 Component 2 均通过,且 Airtable 记录总数为 4、Asana 任务总数为 4" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 sid 时脚本打印 CRITICAL 并返回 0.0", + "无法从 Airtable mock (8129) 或 Asana mock (8134) 获取 current_state 时打印 CRITICAL 并返回 0.0", + "Component 1 找不到匹配记录名或字段值不符时得 0.0", + "Component 2 找不到匹配任务名或字段值不符时得 0.0", + "Component 3 要求 Component 1 和 Component 2 均通过,否则直接得 0.0", + "Airtable 记录数或 Asana 任务数不为 4 时 Component 3 得 0.0" + ], + "scoring_logic_explanation": "脚本首先读取本地 VM 的 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后使用该 sid 分别向 Airtable mock (8129) 和 Asana mock (8134) 的 /go?sid= 接口请求 current_state,任一失败也返回 0.0。接着依次执行三个组件:Component 1 在 Airtable 的 tbl_campaigns 表中查找 Campaign Name 为 'Summer SaaS Launch 2026' 的记录,并严格比对其余四个字段,通过得 0.5 分;Component 2 在 Asana 的 tasks 列表中查找 name 为 'Execute: Summer SaaS Launch 2026' 的任务,并严格比对 description、dueDate、assigneeId,通过得 0.3 分;Component 3 依赖前两个组件的结果,仅在两者均通过时检查 Airtable 记录总数是否为 4(原有 3 + 新增 1)且 Asana 任务总数是否为 4(原有 3 + 新增 1),通过得 0.2 分。最后将各组件得分累加,使用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数作为最终 REWARD 输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读源码:\n\n1. **Task ID**: prof16_campaign_create_001(从 docstring 中提取)\n2. **Domain**: mock_websites (Airtable :8129 + Asana :8134)(从 docstring 中提取)\n3. **Summary**: 验证在 Airtable 创建特定 Campaign 记录并在 Asana 创建对应执行任务的行为。\n4. **is_placeholder**: false(脚本有实际检查逻辑,不是占位脚本)\n5. **data_sources**: \n - /tmp/task_web_sid(读取 sid)\n - http://28.7.186.212:8129(Airtable mock)\n - http://28.7.186.212:8134(Asana mock)\n\n6. **scoring_components**:\n - Component 1: weight 0.5,检查 Airtable 'Campaigns' 表是否有新记录 'Summer SaaS Launch 2026' 且字段值完全匹配(Target Audience, Channels, Launch Date, Status)\n - Component 2: weight 0.3,检查 Asana 'Campaign Execution' 是否有新任务 'Execute: Summer SaaS Launch 2026' 且 description、dueDate、assigneeId 完全匹配\n - Component 3: weight 0.2,检查 Airtable 是否恰好有 4 条记录(原有 3 条 + 1 条新记录),Asana 是否恰好有 4 个任务(原有 3 个 + 1 个新任务),且 Component 1 和 2 都通过\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数\n9. **failure_modes**:\n - 无法从 /tmp/task_web_sid 读取 sid(CRITICAL,返回 0.0)\n - 无法从 mock 服务器获取 current_state(CRITICAL,返回 0.0)\n - Airtable 状态为空或找不到 tbl_campaigns\n - Asana 状态为空\n - Component 3 依赖 Component 1 和 2,如果前两个未通过则直接失败\n\n10. **scoring_logic_explanation**: 按执行顺序:\n - 从 /tmp/task_web_sid 读取 sid,失败则返回 0.0\n - 使用 sid 分别请求 Airtable mock (8129) 和 Asana mock (8134) 的 /go?sid= 接口获取 current_state,失败则返回 0.0\n - 运行 Component 1:遍历 Airtable Campaigns 表记录,查找 Campaign Name 为 'Summer SaaS Launch 2026' 的记录,并验证其余四个字段是否完全匹配预期值。通过得 0.5 分。\n - 运行 Component 2:遍历 Asana tasks,查找 name 为 'Execute: Summer SaaS Launch 2026' 的任务,并验证 description、dueDate、assigneeId 完全匹配。通过得 0.3 分。\n - 运行 Component 3:要求 Component 1 和 2 均通过,然后检查 Airtable 记录总数是否为 4(原有 3 + 新增 1),Asana 任务总数是否为 4(原有 3 + 新增 1)。通过得 0.2 分。\n - 汇总分数,min(总分, 1.0) 后四舍五入到 4 位小数输出。\n\n11. **confidence**: 1.0(源码完整,逻辑清晰)\n\n现在构建 JSON。注意:\n- 不要输出 Markdown 代码块\n- 第一个字符必须是 {,最后一个必须是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- weight 填写显式分值\n\n让我确认字段名保留原样:\n- FLD_NAME = 'fld_camp_name'\n- FLD_AUDIENCE = 'fld_camp_audience'\n- FLD_CHANNELS = 'fld_camp_channels'\n- FLD_LAUNCH = 'fld_camp_launch'\n- FLD_STATUS = 'fld_camp_status'\n\n以及 Asana 字段:\n- name\n- description\n- dueDate\n- assigneeId\n\n检查 Component 3 的 pass_condition:Airtable 记录数为 4 且 Asana 任务数为 4,且 Component 1 和 2 都通过。\n\nJSON 结构检查:\n- task_id: \"prof16_campaign_create_001\"\n- domain: \"mock_websites\"\n- summary: \"验证在 Airtable 创建指定 Campaign 记录并在 Asana 创建对应执行任务,且仅新增一条记录和一个任务、保留原有数据\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"http://28.7.186.212:8129\", \"http://28.7.186.212:8134\"]\n- scoring_components: 数组包含 3 个对象\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数\"\n- failure_modes: [\"无法从 /tmp/task_web_sid 读取 sid 时返回 0.0\", \"无法从 Airtable 或 Asana mock 获取 current_state 时返回 0.0\", \"Component 3 要求 Component 1 和 Component 2 均通过,否则失败\", \"Airtable 记录数或 Asana 任务数不为 4 时 Component 3 失败\"]\n- scoring_logic_explanation: 详细中文解释...\n- confidence: 1.0\n\n确保没有思考过程、没有额外文字、没有 markdown 代码块标记。\n\n再仔细检查一下 Component 1 的 check_logic:\n代码中:\n```python\nfor r in records:\n f = r.get('fields', {})\n if f.get(FLD_NAME) == EXP_NAME:\n ok = (\n f.get(FLD_AUDIENCE) == EXP_AUDIENCE and\n f.get(FLD_CHANNELS) == EXP_CHANNELS and\n f.get(FLD_LAUNCH) == EXP_LAUNCH and\n f.get(FLD_STATUS) == EXP_STATUS\n )\n if ok:\n return True, 0.5, ...\n return False, 0.0, ...\nreturn False, 0.0, ...\n```\n\n所以是查找 name 匹配的记录,然后检查其余字段。\n\nComponent 2:\n```python\nfor t in tasks:\n if t.get('name') == EXP_TASK_NAME:\n ok = (\n t.get('description') == EXP_TASK_DESC and\n t.get('dueDate') == EXP_TASK_DUE and\n t.get('assigneeId') == EXP_TASK_ASSIGNEE\n )\n```\n\nComponent 3:\n```python\nif not (comp1_pass and comp2_pass):\n return False, 0.0, 'requires components 1 and 2 to pass first'\n...\nrec_count == 4 and task_count == 4\n```\n\n注意 comp1_pass 和 comp2_pass 是布尔值,从 `c1_score > 0, c2_score > 0` 传入。\n\n一切看起来正确。 {\"task_id\":\"prof16_campaign_create_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Airtable 创建指定 Campaign 记录并在 Asana 创建对应执行任务,且仅新增一条记录和一个任务、保留原有数据\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"http://28.7.186.212:8129\",\"http://28.7.186.212:8134\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.5,\"description\":\"检查 Airtable Campaigns 表中是否存在名为 'Summer SaaS Launch 2026' 的新记录,且其字段值与预期完全一致\",\"check_logic\":\"遍历 airtable_state['tables']['tbl_campaigns']['records'],查找 fields['fld_camp_name'] == 'Summer SaaS Launch 2026' 的记录;找到后依次校验 fields['fld_camp_audience']、fields['fld_camp_channels']、fields['fld_camp_launch']、fields['fld_camp_status'] 是否分别等于预期字符串;全部匹配则通过,否则失败\",\"pass_condition\":\"Airtable tbl_campaigns 中存在一条 Campaign Name 为 'Summer SaaS Launch 2026' 的记录,且 Target Audience、Channels、Launch Date、Status 四个字段与预期值完全相等\"},{\"name\":\"Component 2\",\"weight\":0.3,\"description\":\"检查 Asana 中是否存在名为 'Execute: Summer SaaS Launch 2026' 的新任务,且其描述、截止日期、负责人与预期完全一致\",\"check_logic\":\"遍历 asana_state['tasks'],查找 name == 'Execute: Summer SaaS Launch 2026' 的任务;找到后依次校验 description、dueDate、assigneeId 是否分别等于预期字符串;全部匹配则通过,否则失败\",\"pass_condition\":\"Asana tasks 中存在一条 name 为 'Execute: Summer SaaS Launch 2026' 的任务,且 description、dueDate、assigneeId 与预期值完全相等\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"检查 Airtable 和 Asana 中各自恰好新增了一条数据,原有 3 条记录/任务未被改动\",\"check_logic\":\"先判断 comp1_pass 与 comp2_pass 均为 True,否则直接失败;然后分别计算 Airtable tbl_campaigns 的 records 长度与 Asana 的 tasks 长度,要求两者均等于 4(原有 3 条 + 新增 1 条)\",\"pass_condition\":\"Component 1 和 Component 2 均通过,且 Airtable 记录总数为 4、Asana 任务总数为 4\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 sid 时脚本打印 CRITICAL 并返回 0.0\",\"无法从 Airtable mock (8129) 或 Asana mock (8134) 获取 current_state 时打印 CRITICAL 并返回 0.0\",\"Component 1 找不到匹配记录名或字段值不符时得 0.0\",\"Component 2 找不到匹配任务名或字段值不符时得 0.0\",\"Component 3 要求 Component 1 和 Component 2 均通过,否则直接得 0.0\",\"Airtable 记录数或 Asana 任务数不为 4 时 Component 3 得 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取本地 VM 的 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后使用该 sid 分别向 Airtable mock (8129) 和 Asana mock (8134) 的 /go?sid= 接口请求 current_state,任一失败也返回 0.0。接着依次执行三个组件:Component 1 在 Airtable 的 tbl_campaigns 表中查找 Campaign Name 为 'Summer SaaS Launch 2026' 的记录,并严格比对其余四个字段,通过得 0.5 分;Component 2 在 Asana 的 tasks 列表中查找 name 为 'Execute: Summer SaaS Launch 2026' 的任务,并严格比对 description、dueDate、assigneeId,通过得 0.3 分;Component 3 依赖前两个组件的结果,仅在两者均通过时检查 Airtable 记录总数是否为 4(原有 3 + 新增 1)且 Asana 任务总数是否为 4(原有 3 + 新增 1),通过得 0.2 分。最后将各组件得分累加,使用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数作为最终 REWARD 输出。\",\"confidence\":1.0}" +} diff --git a/mktg_field_reconcile_006/_cua_gym_vm_bridge.sh b/mktg_field_reconcile_006/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_field_reconcile_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/mktg_field_reconcile_006/initial_setup.py b/mktg_field_reconcile_006/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fa383bdf5a43b1b2d591a90391f1e81cc53cee5e --- /dev/null +++ b/mktg_field_reconcile_006/initial_setup.py @@ -0,0 +1,285 @@ +""" +Initial Setup: prof18_field_reconcile_001 +Task: Cross-system lifecycle-stage reconciliation between Google Sheets (source of + truth) and HubSpot (target). Three HubSpot leads are missing a Lifecycle Stage. +Domain: mock_websites (multi-mock: google_sheets_mock + hubspot_mock) +Mocks: + - Google Sheets mock : http://28.7.184.198:8145 (READ-ONLY source of truth) + - HubSpot mock : http://28.7.184.198:8150 (TARGET to edit) +""" + +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +SHEETS_URL = "http://28.7.184.198:8145" +HUBSPOT_URL = "http://28.7.184.198:8150" + +# --- Shared session id (multi-mock task: same sid for both) --- +sid = str(uuid.uuid4()) +with open("/tmp/task_web_sid", "w") as f: + f.write(sid) +print(f"Generated sid={sid}") + +# --------------------------------------------------------------------------- +# DATA: 12 companies / leads, keyed by domain +# --------------------------------------------------------------------------- +# (company, domain, lifecycle_stage_for_sheets, hubspot_target_stage) +# Sheets shows the source-of-truth lifecycle stage (uppercase as displayed). +# HubSpot stores LOWERCASE enum values. +ROWS = [ + ("Acme Robotics", "acme-robotics.com", "Lead", "lead"), + ("Bexter", "bexter.com", "MQL", "mql"), + ("Cobalt Stack", "cobaltstack.io", "SQL", "sql"), + ("Denova Works", "denovaworks.com", "Lead", "lead"), + ("Everlytics", "everlytics.io", "MQL", "mql"), + ("FinchPay", "finchpay.com", "SQL", "sql"), + ("GreyDesk", "greydesk.com", "Lead", "lead"), + ("HelioSys", "heliosys.com", "MQL", "mql"), + ("Ironclad Labs", "ironcladlabs.io", "SQL", "sql"), + ("Northwind Cloud", "northwindcloud.com", "Lead", ""), # TARGET -> lead + ("Lumen Data", "lumendata.io", "MQL", ""), # TARGET -> mql + ("Vector Labs", "vectorlabs.ai", "SQL", ""), # TARGET -> sql +] + +# The three target domains whose HubSpot lead is missing a stage. +TARGETS = { + "northwindcloud.com": "lead", + "lumendata.io": "mql", + "vectorlabs.ai": "sql", +} + +# Company id per domain (comp1..comp12) +def comp_id(i): + return f"comp{i+1}" + +def contact_id(i): + return f"c{i+1}" + +# Realistic per-contact data (first, last, email, job title, owner, city, state, +# country, createDate, lastActivityDate) +CONTACT_DETAILS = [ + ("Sarah", "Chen", "sarah@acme-robotics.com", "VP Engineering", "Admin User", "Austin", "TX", "United States", "2024-01-12T09:15:00Z", "2024-05-20T13:40:00Z"), + ("Marcus", "Johnson", "marcus@bexter.com", "Head of Growth", "Admin User", "Denver", "CO", "United States", "2024-01-18T11:05:00Z", "2024-05-18T10:20:00Z"), + ("Priya", "Nair", "priya@cobaltstack.io", "CTO", "Admin User", "Seattle", "WA", "United States", "2024-02-02T08:30:00Z", "2024-05-22T16:10:00Z"), + ("Diego", "Alvarez", "diego@denovaworks.com", "Founder", "Admin User", "Miami", "FL", "United States", "2024-02-09T14:45:00Z", "2024-05-15T09:05:00Z"), + ("Hannah", "Weber", "hannah@everlytics.io", "Director of Data", "Admin User", "Boston", "MA", "United States", "2024-02-14T10:10:00Z", "2024-05-19T12:30:00Z"), + ("Liam", "O'Sullivan","liam@finchpay.com", "VP Finance", "Admin User", "Chicago", "IL", "United States", "2024-02-21T13:25:00Z", "2024-05-21T15:50:00Z"), + ("Yuki", "Tanaka", "yuki@greydesk.com", "Product Lead", "Admin User", "Portland", "OR", "United States", "2024-03-01T09:00:00Z", "2024-05-17T11:15:00Z"), + ("Omar", "Hassan", "omar@heliosys.com", "COO", "Admin User", "Phoenix", "AZ", "United States", "2024-03-08T12:40:00Z", "2024-05-23T14:25:00Z"), + ("Elena", "Rossi", "elena@ironcladlabs.io", "Chief Scientist", "Admin User", "San Jose", "CA", "United States", "2024-03-15T08:50:00Z", "2024-05-16T10:45:00Z"), + ("Grace", "Kim", "grace@northwindcloud.com", "Procurement Mgr", "Admin User", "Atlanta", "GA", "United States", "2024-03-22T15:20:00Z", "2024-05-24T09:30:00Z"), + ("Noah", "Becker", "noah@lumendata.io", "Analytics Lead", "Admin User", "Raleigh", "NC", "United States", "2024-03-29T11:35:00Z", "2024-05-25T13:05:00Z"), + ("Maya", "Patel", "maya@vectorlabs.ai", "Research Director", "Admin User", "Nashville", "TN", "United States", "2024-04-05T10:00:00Z", "2024-05-26T14:55:00Z"), +] + +PHONE_NUMBERS = [ + "+1 (555) 010-1001", "+1 (555) 010-1002", "+1 (555) 010-1003", "+1 (555) 010-1004", + "+1 (555) 010-1005", "+1 (555) 010-1006", "+1 (555) 010-1007", "+1 (555) 010-1008", + "+1 (555) 010-1009", "+1 (555) 010-1010", "+1 (555) 010-1011", "+1 (555) 010-1012", +] + +INDUSTRIES = [ + "Manufacturing", "Marketing", "Technology", "Technology", "Technology", "Finance", + "Design", "Technology", "Technology", "Environmental Services", "Technology", "Healthcare", +] + +DESCRIPTIONS = [ + "Autonomous robotics and warehouse automation systems", + "B2B marketing automation and campaign tooling", + "Cloud-native infrastructure observability stack", + "No-code workflow platform for operations teams", + "Real-time product analytics for SaaS teams", + "Embedded payments and ledger infrastructure", + "Collaborative workspace and document platform", + "Distributed solar energy management platform", + "Post-quantum encryption research and tooling", + "Multi-region cloud migration and orchestration", + "Customer data platform and identity resolution", + "Applied ML research lab for drug discovery", +] + +# --------------------------------------------------------------------------- +# Build Google Sheets state (8165) — read-only source of truth +# --------------------------------------------------------------------------- +def build_sheets_state(): + data = {} + # Header row (bold) + header_style = {"bold": True, "bg": "#E8EAED", "align": "center"} + data["A1"] = {"value": "Company", "formula": "Company", "style": header_style} + data["B1"] = {"value": "Domain", "formula": "Domain", "style": header_style} + data["C1"] = {"value": "Lifecycle Stage", "formula": "Lifecycle Stage", "style": header_style} + for i, (company, domain, stage, _) in enumerate(ROWS): + r = i + 2 # rows 2..13 + data[f"A{r}"] = {"value": company, "formula": company} + data[f"B{r}"] = {"value": domain, "formula": domain} + data[f"C{r}"] = {"value": stage, "formula": stage} + sheet = { + "id": "sheet_1", + "name": "Accounts", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": "#1A73E8", + "isHidden": False, + "columnWidths": {"0": 200, "1": 200, "2": 160}, + "data": data, + } + state = { + "id": "workbook_q3_targets", + "title": "Target Accounts Q3", + "activeSheetId": "sheet_1", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [sheet], + } + return state + + +# --------------------------------------------------------------------------- +# Build HubSpot state (8170) — target; 3 leads missing lifecycleStage +# --------------------------------------------------------------------------- +def build_hubspot_state(): + companies = [] + for i, (company, domain, _stage, _hs) in enumerate(ROWS): + companies.append({ + "id": comp_id(i), + "name": company, + "domain": domain, + "industry": INDUSTRIES[i], + "phone": PHONE_NUMBERS[i], + "city": CONTACT_DETAILS[i][5], + "state": CONTACT_DETAILS[i][6], + "country": CONTACT_DETAILS[i][7], + "numberOfEmployees": 50 + i * 17, + "annualRevenue": 2000000 + i * 750000, + "lifecycleStage": _hs if _hs else "lead", + "owner": "Admin User", + "description": DESCRIPTIONS[i], + "createDate": "2024-01-10T09:00:00Z", + }) + + contacts = [] + for i, (company, domain, _stage, hs_stage) in enumerate(ROWS): + fn, ln, email, job, owner, city, st, country, cdate, ldate = CONTACT_DETAILS[i] + contacts.append({ + "id": contact_id(i), + "firstName": fn, + "lastName": ln, + "email": email, + "phone": PHONE_NUMBERS[i], + "jobTitle": job, + "companyId": comp_id(i), + "lifecycleStage": hs_stage, # "" for the 3 targets + "leadStatus": "open_deal" if hs_stage else "new", + "owner": owner, + "city": city, + "state": st, + "country": country, + "createDate": cdate, + "lastActivityDate": ldate, + "timeline": [], + }) + + state = { + "contacts": contacts, + "companies": companies, + "deals": [], + "tickets": [], + "tasks": [], + "notes": [], + "templates": [], + "meetings": [], + "forms": [], + "dealStages": { + "appointment_scheduled": {"id": "appointment_scheduled", "label": "Appointment Scheduled", "probability": 20, "color": "#E5F4FF", "order": 1}, + "qualified_to_buy": {"id": "qualified_to_buy", "label": "Qualified to Buy", "probability": 40, "color": "#FFF0E6", "order": 2}, + "presentation_scheduled": {"id": "presentation_scheduled", "label": "Presentation Scheduled", "probability": 60, "color": "#FFF8E6", "order": 3}, + "decision_maker_bought_in": {"id": "decision_maker_bought_in", "label": "Decision Maker Bought-In", "probability": 80, "color": "#E8F5E9", "order": 4}, + "contract_sent": {"id": "contract_sent", "label": "Contract Sent", "probability": 90, "color": "#E6FFFA", "order": 5}, + "closed_won": {"id": "closed_won", "label": "Closed Won", "probability": 100, "color": "#E6FFEC", "order": 6}, + "closed_lost": {"id": "closed_lost", "label": "Closed Lost", "probability": 0, "color": "#FFE6E6", "order": 7}, + }, + "ticketStatuses": { + "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1}, + "waiting_on_contact": {"id": "waiting_on_contact", "label": "Waiting on Contact", "color": "#FFF8E6", "order": 2}, + "waiting_on_us": {"id": "waiting_on_us", "label": "Waiting on Us", "color": "#FFF0E6", "order": 3}, + "in_progress": {"id": "in_progress", "label": "In Progress", "color": "#E6FFFA", "order": 4}, + "closed": {"id": "closed", "label": "Closed", "color": "#E6FFEC", "order": 5}, + }, + "appState": { + "sidebarOpen": True, + "currentUser": {"name": "Admin User", "email": "admin@example.com", "avatar": None}, + }, + } + return state + + +# --------------------------------------------------------------------------- +# Inject into both mocks with the SAME sid +# --------------------------------------------------------------------------- +sheets_state = build_sheets_state() +hubspot_state = build_hubspot_state() + +resp = requests.post( + f"{SHEETS_URL}/post?sid={sid}", + json={"action": "set", "state": sheets_state}, + timeout=30, +) +assert resp.status_code == 200, f"Sheets set failed: {resp.text}" +print("Sheets state injected.") + +resp = requests.post( + f"{HUBSPOT_URL}/post?sid={sid}", + json={"action": "set", "state": hubspot_state}, + timeout=30, +) +assert resp.status_code == 200, f"HubSpot set failed: {resp.text}" +print("HubSpot state injected.") + +# Verify both +gs = requests.get(f"{SHEETS_URL}/go?sid={sid}", timeout=10).json() +assert gs["initial_state"] is not None, "Sheets initial_state is None" +hs = requests.get(f"{HUBSPOT_URL}/go?sid={sid}", timeout=10).json() +assert hs["initial_state"] is not None, "HubSpot initial_state is None" +print("Verified: both mocks have initial_state set.") + + +# --------------------------------------------------------------------------- +# Launch a Chrome window for EACH mock +# --------------------------------------------------------------------------- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + + +launch_gui(f'google-chrome "{SHEETS_URL}/?sid={sid}"', delay_sec=2.0) +launch_gui(f'google-chrome "{HUBSPOT_URL}/?sid={sid}"', delay_sec=2.0) + +# Brief settle so windows register before the harness declares GUI_READY. +time.sleep(3.0) + +print(f"GUI_READY: launched Chrome for both mocks (sid={sid})") diff --git a/mktg_field_reconcile_006/reward.py b/mktg_field_reconcile_006/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..8dd8963631449dde794bd0b888b7d6c7a7dcfe72 --- /dev/null +++ b/mktg_field_reconcile_006/reward.py @@ -0,0 +1,167 @@ +""" +Reward Script: prof18_field_reconcile_001 +Task ID: mktg_field_reconcile_006 +Domain: mock_websites (HubSpot + Google Sheets) +Mock: hubspot_mock (http://28.7.184.198:8150) — TARGET to verify +Scoring: 3 independent components, one per target domain whose HubSpot + Lifecycle Stage must equal the value copied from the Google Sheets + 'Target Accounts Q3' workbook. Each component checks the live + HubSpot current_state, resolving contact.companyId -> company.domain + to find the contact for the target domain. Pure state inspector — + reads only; never injects or resets state. +""" +import json +import sys + +import requests + +# --- Config --- +# HubSpot is the TARGET system whose state we verify. +HUBSPOT_URL = "http://28.7.184.198:8150" + +# Ground-truth target domains and their required lowercase lifecycleStage +# values, taken from task_config.json context (the Sheets workbook is the +# read-only source of truth; HubSpot lifecycleStage enum is lowercase). +TARGETS = { + "northwindcloud.com": "lead", + "lumendata.io": "mql", + "vectorlabs.ai": "sql", +} + + +def _load_state(): + """Read sid and fetch the live HubSpot state. Returns current_state dict + or None on any failure (caller prints REWARD: 0.0).""" + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + print('CRITICAL: sid is empty') + return None + except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + return None + + try: + resp = requests.get(f'{HUBSPOT_URL}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {HUBSPOT_URL}/go?sid={sid}: {e}') + return None + + current = data.get('current_state') + if current is None: + print('CRITICAL: current_state is None for this sid') + return None + return current + + +def _build_domain_map(current_state): + """Build a domain -> lifecycleStage map for all contacts by resolving + contact.companyId -> company.id -> company.domain.""" + companies = current_state.get('companies', []) or [] + domain_by_company = {} + for comp in companies: + cid = comp.get('id') + if cid is not None: + domain_by_company[cid] = comp.get('domain') + + result = {} + for contact in current_state.get('contacts', []) or []: + comp_id = contact.get('companyId') + domain = domain_by_company.get(comp_id) + if domain is not None: + result[domain] = contact.get('lifecycleStage') + return result + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# --- Per-component checks (one function per target domain) --- + +def check_component_1(domain_map): + """northwindcloud.com contact has lifecycleStage == 'lead'. + Pass condition: domain_map['northwindcloud.com'] == 'lead' (case-insensitive + exact match after lowercasing; empty string fails).""" + actual = domain_map.get('northwindcloud.com') + if actual is None: + return False, 0.0, 'no contact found for domain northwindcloud.com' + if actual == 'lead': + return True, 0.34, "northwindcloud.com lifecycleStage == 'lead'" + return False, 0.0, f"expected 'lead', found {actual!r}" + + +def check_component_2(domain_map): + """lumendata.io contact has lifecycleStage == 'mql'. + Pass condition: domain_map['lumendata.io'] == 'mql' (exact lowercase match; + empty string fails).""" + actual = domain_map.get('lumendata.io') + if actual is None: + return False, 0.0, 'no contact found for domain lumendata.io' + if actual == 'mql': + return True, 0.33, "lumendata.io lifecycleStage == 'mql'" + return False, 0.0, f"expected 'mql', found {actual!r}" + + +def check_component_3(domain_map): + """vectorlabs.ai contact has lifecycleStage == 'sql'. + Pass condition: domain_map['vectorlabs.ai'] == 'sql' (exact lowercase match; + empty string fails).""" + actual = domain_map.get('vectorlabs.ai') + if actual is None: + return False, 0.0, 'no contact found for domain vectorlabs.ai' + if actual == 'sql': + return True, 0.33, "vectorlabs.ai lifecycleStage == 'sql'" + return False, 0.0, f"expected 'sql', found {actual!r}" + + +def verify_task(): + """Verify task completion with progressive scoring. + Returns: float between 0.0 and 1.0 + """ + current_state = _load_state() + if current_state is None: + print('REWARD: 0.0') + return 0.0 + + domain_map = _build_domain_map(current_state) + + total_score = 0.0 + for idx, name, weight, fn in [ + (1, 'northwindcloud.com -> lead', 0.34, check_component_1), + (2, 'lumendata.io -> mql', 0.33, check_component_2), + (3, 'vectorlabs.ai -> sql', 0.33, check_component_3), + ]: + _, score, _ = _run_component(idx, name, weight, fn, (domain_map,)) + total_score += score + + final_score = round(min(total_score, 1.0), 4) + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +if __name__ == '__main__': + verify_task() diff --git a/mktg_field_reconcile_006/reward_label.json b/mktg_field_reconcile_006/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..7fd81e31c9394ecac9fc5012bd0ab48bbfb7cc5e --- /dev/null +++ b/mktg_field_reconcile_006/reward_label.json @@ -0,0 +1,52 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof18_field_reconcile_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:29:27", + "label": { + "task_id": "mktg_field_reconcile_006", + "domain": "mock_websites", + "summary": "验证 HubSpot 中三个目标域名联系人的生命周期阶段是否与 Google Sheets 中的目标值一致", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "hubspot_mock (http://28.7.186.212:8170)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.34, + "description": "检查 northwindcloud.com 联系人的 lifecycleStage 是否为 'lead'", + "check_logic": "从 domain_map 中获取 'northwindcloud.com' 对应的 lifecycleStage,判断 actual == 'lead';若 actual 为 None 或不相等则失败", + "pass_condition": "domain_map['northwindcloud.com'] 存在且等于 'lead'" + }, + { + "name": "Component 2", + "weight": 0.33, + "description": "检查 lumendata.io 联系人的 lifecycleStage 是否为 'mql'", + "check_logic": "从 domain_map 中获取 'lumendata.io' 对应的 lifecycleStage,判断 actual == 'mql';若 actual 为 None 或不相等则失败", + "pass_condition": "domain_map['lumendata.io'] 存在且等于 'mql'" + }, + { + "name": "Component 3", + "weight": 0.33, + "description": "检查 vectorlabs.ai 联系人的 lifecycleStage 是否为 'sql'", + "check_logic": "从 domain_map 中获取 'vectorlabs.ai' 对应的 lifecycleStage,判断 actual == 'sql';若 actual 为 None 或不相等则失败", + "pass_condition": "domain_map['vectorlabs.ai'] 存在且等于 'sql'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,然后使用 min(total_score, 1.0) 钳制到上限 1.0,最后四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或 sid 为空,返回 0.0", + "从 HubSpot mock 获取状态失败或请求异常,返回 0.0", + "current_state 为 None,返回 0.0", + "domain_map 中找不到目标域名对应的联系人,该组件得 0.0", + "lifecycleStage 值与预期不符,该组件得 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向 hubspot_mock 发送请求拉取 current_state。接着通过 _build_domain_map 解析 current_state 中的 companies 和 contacts,利用 contact.companyId 关联 company.id 得到 domain -> lifecycleStage 的映射。之后依次执行三个组件检查:northwindcloud.com 是否为 lead(0.34 分)、lumendata.io 是否为 mql(0.33 分)、vectorlabs.ai 是否为 sql(0.33 分)。每个组件独立判断,通过则获得对应权重分数,失败得 0.0。最终总分由三个组件分数累加,经 min(total_score, 1.0) 钳制上限后四舍五入到 4 位小数输出为 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不包含任何额外文本、Markdown 代码块标记或思考过程。\n\n让我仔细阅读源码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: prof18_field_reconcile_001\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (HubSpot + Google Sheets)\"\n3. **summary**: 一句话概括。这个脚本验证 HubSpot 中三个目标域名的联系人生命周期阶段是否等于从 Google Sheets 复制过来的值。\n4. **is_placeholder**: false,因为脚本真正检查了状态。\n5. **data_sources**: \n - /tmp/task_web_sid(读取 sid)\n - hubspot_mock (http://28.7.186.212:8170)(获取状态)\n - 脚本提到 Google Sheets 是 ground-truth 来源,但脚本本身并不直接读取 Google Sheets,而是使用硬编码的 TARGETS。不过数据源应该包括提到的 mock 服务和文件。\n - 根据要求:\"脚本从哪些数据源/mock 服务/文件获取状态\",所以应列出:/tmp/task_web_sid、hubspot_mock (http://28.7.186.212:8170)\n6. **scoring_components**: 三个独立组件\n - Component 1: northwindcloud.com -> lead, weight 0.34\n - Component 2: lumendata.io -> mql, weight 0.33\n - Component 3: vectorlabs.ai -> sql, weight 0.33\n 每个组件检查 domain_map 中对应域名的 lifecycleStage 是否等于目标值。\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,然后 min(total_score, 1.0),再 round(..., 4)。所以是\"相加后钳制到上限 1.0 并四舍五入到 4 位小数\"。\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或 sid 为空\n - 从 HubSpot mock 获取状态失败\n - current_state 为 None\n - 找不到对应域名的联系人\n - lifecycleStage 值不匹配\n10. **scoring_logic_explanation**: 详细中文解释\n - 首先读取 /tmp/task_web_sid 获取会话 ID\n - 使用 sid 请求 HubSpot mock 的 /go 端点获取 current_state\n - 构建 domain_map:通过 companyId 关联 contact 和 company,得到 domain -> lifecycleStage 映射\n - 依次检查三个目标域名:\n - northwindcloud.com 是否为 lead(0.34 分)\n - lumendata.io 是否为 mql(0.33 分)\n - vectorlabs.ai 是否为 sql(0.33 分)\n - 各组件得分相加,总和钳制在 1.0 以内,四舍五入到 4 位小数作为最终 REWARD\n11. **confidence**: 1.0(源码完整清晰)\n\n让我再仔细检查一下 weight 的数值:\n- Component 1: 0.34\n- Component 2: 0.33\n- Component 3: 0.33\n总和正好是 1.0。\n\ncheck_logic 和 pass_condition 需要引用关键代码条件。\n\nJSON 格式要求:\n- 只输出 JSON 对象\n- 第一个字符是 {,最后一个字符是 }\n- 不要 Markdown 代码块\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n\n我需要确保 JSON 是有效的,没有尾随逗号等问题。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"prof18_field_reconcile_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证 HubSpot 中三个目标域名联系人的生命周期阶段是否与 Google Sheets 中的目标值一致\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"hubspot_mock (http://28.7.186.212:8170)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.34,\n \"description\": \"检查 northwindcloud.com 联系人的 lifecycleStage 是否为 'lead'\",\n \"check_logic\": \"从 domain_map 中获取 'northwindcloud.com' 对应的 lifecycleStage,判断 actual == 'lead';若 actual 为 None 或不相等则失败\",\n \"pass_condition\": \"domain_map['northwindcloud.com'] 存在且等于 'lead'\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.33,\n \"description\": \"检查 lumendata.io 联系人的 lifecycleStage 是否为 'mql'\",\n \"check_logic\": \"从 domain_map 中获取 'lumendata.io' 对应的 lifecycleStage,判断 actual == 'mql';若 actual 为 None 或不相等则失败\",\n \"pass_condition\": \"domain_map['lumendata.io'] 存在且等于 'mql'\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.33,\n \"description\": \"检查 vectorlabs.ai 联系人的 lifecycleStage 是否为 'sql'\",\n \"check_logic\": \"从 domain_map 中获取 'vectorlabs.ai' 对应的 lifecycleStage,判断 actual == 'sql';若 actual 为 None 或不相等则失败\",\n \"pass_condition\": \"domain_map['vectorlabs.ai'] 存在且等于 'sql'\"\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 为空,返回 0.0\",\n \"从 HubSpot mock 获取状态失败或返回异常,返回 0.0\",\n \"current_state 为 None,返回 0.0\",\n \"domain_map 中找不到目标域名对应的联系人,该组件得 0.0\",\n \"lifecycleStage 值与预期不符,该组件得 0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向 hubspot_mock 发送请求拉取 current_state。接着通过 _build_domain_map 解析 current_state 中的 companies 和 contacts,利用 contact.companyId 关联 company.id 得到 domain -> lifecycleStage 的映射。之后依次执行三个组件检查:northwindcloud.com 是否为 lead(0.34 分)、lumendata.io 是否为 mql(0.33 分)、vectorlabs.ai 是否为 sql(0.33 分)。每个组件独立判断,通过则获得对应权重分数,失败得 0.0。最终总分由三个组件分数累加,经 min(total_score, 1.0) 钳制上限后四舍五入到 4 位小数输出为 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n等等,domain 的提取。docstring 中写的是 \"Domain: mock_websites (HubSpot + Google Sheets)\",所以 domain 应该是 \"mock_websites\"。\n\ndata_sources 中是否需要包含 Google Sheets?脚本提到 \"Ground-truth target domains... taken from task_config.json context (the Sheets workbook is the read-only source of truth)\",但脚本本身并没有从 Google Sheets 获取状态,它是纯状态检查器,只读取 HubSpot mock。所以 data_sources 应该只包含它实际读取的:/tmp/task_web_sid 和 hubspot_mock。\n\n让我再检查一下 summary 和 description 是否需要更精确。\n\nsummary: \"验证 HubSpot 中三个目标域名联系人的生命周期阶段是否与 Google Sheets 中的目标值一致\" — 这准确。\n\nscoring_logic_explanation 已经很详细了。\n\nconfidence: 1.0 是合适的,因为代码非常清晰。\n\n确保 JSON 中没有中文引号或其他非法字符。所有引号必须是英文双引号。\n\n再检查一下字段名是否都正确:\n- task_id\n- domain\n- summary\n- is_placeholder\n- data_sources\n- scoring_components\n- total_max_score\n- score_aggregation\n- failure_modes\n- scoring_logic_explanation\n- confidence\n\n都包含了。\n\n输出格式:不要 Markdown 代码块,不要额外解释,不要思考过程标签。只输出 JSON。\n\n让我最终确认 JSON 内容。 {\n \"task_id\": \"prof18_field_reconcile_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证 HubSpot 中三个目标域名联系人的生命周期阶段是否与 Google Sheets 中的目标值一致\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"hubspot_mock (http://28.7.186.212:8170)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.34,\n \"description\": \"检查 northwindcloud.com 联系人的 lifecycleStage 是否为 'lead'\",\n \"check_logic\": \"从 domain_map 中获取 'northwindcloud.com' 对应的 lifecycleStage,判断 actual == 'lead';若 actual 为 None 或不相等则失败\",\n \"pass_condition\": \"domain_map['northwindcloud.com'] 存在且等于 'lead'\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.33,\n \"description\": \"检查 lumendata.io 联系人的 lifecycleStage 是否为 'mql'\",\n \"check_logic\": \"从 domain_map 中获取 'lumendata.io' 对应的 lifecycleStage,判断 actual == 'mql';若 actual 为 None 或不相等则失败\",\n \"pass_condition\": \"domain_map['lumendata.io'] 存在且等于 'mql'\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.33,\n \"description\": \"检查 vectorlabs.ai 联系人的 lifecycleStage 是否为 'sql'\",\n \"check_logic\": \"从 domain_map 中获取 'vectorlabs.ai' 对应的 lifecycleStage,判断 actual == 'sql';若 actual 为 None 或不相等则失败\",\n \"pass_condition\": \"domain_map['vectorlabs.ai'] 存在且等于 'sql'\"\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 为空,返回 0.0\",\n \"从 HubSpot mock 获取状态失败或请求异常,返回 0.0\",\n \"current_state 为 None,返回 0.0\",\n \"domain_map 中找不到目标域名对应的联系人,该组件得 0.0\",\n \"lifecycleStage 值与预期不符,该组件得 0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向 hubspot_mock 发送请求拉取 current_state。接着通过 _build_domain_map 解析 current_state 中的 companies 和 contacts,利用 contact.companyId 关联 company.id 得到 domain -> lifecycleStage 的映射。之后依次执行三个组件检查:northwindcloud.com 是否为 lead(0.34 分)、lumendata.io 是否为 mql(0.33 分)、vectorlabs.ai 是否为 sql(0.33 分)。每个组件独立判断,通过则获得对应权重分数,失败得 0.0。最终总分由三个组件分数累加,经 min(total_score, 1.0) 钳制上限后四舍五入到 4 位小数输出为 REWARD。\",\n \"confidence\": 1.0\n}" +} diff --git a/mktg_funnel_report_007/_cua_gym_vm_bridge.sh b/mktg_funnel_report_007/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_funnel_report_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/mktg_funnel_report_007/initial_setup.py b/mktg_funnel_report_007/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..554aecb5a4b7bad931e09a927b3fdac08bae25d6 --- /dev/null +++ b/mktg_funnel_report_007/initial_setup.py @@ -0,0 +1,484 @@ +""" +Initial Setup: Weekly Funnel Report cross-app pipeline +Task ID: mktg_funnel_report_007 +Domain: mock_websites (multi-mock: google_sheets, salesforce, google_docs, slack) +Mocks: + - Google Sheets http://28.7.184.198:8145 (workbook 'Growth Funnel Q3', sheet 'Weekly') + - Salesforce http://28.7.184.198:8175 (Campaign Attribution report / Pipeline Report) + - Google Docs http://28.7.184.198:8142 (document creation) + - Slack http://28.7.184.198:8178 (#growth-reviews channel) + +This script establishes the documented INITIAL STATE: + - Sheets: 'Weekly' sheet with Target table filled (rows 2-6) and Current table + (rows 10-14) with only Stage labels, B/C/D blank. + - Salesforce: Campaign Attribution report + Pipeline Report object showing the + canonical figures (SQL=63, Opportunity=24, Customer=7). Read-only reference. + - Google Docs: NO document titled 'Weekly Funnel Report - 2026-W27' exists yet. + - Slack: #growth-reviews channel exists but is empty (no funnel message yet). +""" + +import json +import os +import shlex +import subprocess +import time + +import requests + +# ---------------------------------------------------------------------------- +# Config — distinct sid for the INITIAL environment. +# The initial and golden VMs hit the SAME shared mock server, so the sid is the +# isolation key. We use a SEPARATE sid per environment so that golden_patch.py +# (which runs on the golden VM) cannot overwrite the initial env's current_state. +# - initial_setup.py -> SID_initial (this file) +# - golden_patch.py -> SID_golden (separate file) +# initial_setup uses action:"set" (baseline) AND action:"set_current" (clean end +# state) so the initial env's current_state is also clean (reward(initial) == 0.0). +# ---------------------------------------------------------------------------- +SID = "prof18_funnel_report_003_initial" +MOCKS = { + "google_sheets": "http://28.7.184.198:8145", + "salesforce": "http://28.7.184.198:8175", + "google_docs": "http://28.7.184.198:8142", + "slack": "http://28.7.184.198:8178", +} + +# Persist sid for reward.py (and for golden_patch.py if it reads the file). +with open("/tmp/task_web_sid", "w") as f: + f.write(SID) + + +# ---------------------------------------------------------------------------- +# Google Sheets state +# ---------------------------------------------------------------------------- +def build_sheets_state(): + data = {} + + def cell(cid, value, bold=False, bg=None, align=None): + c = {"value": str(value), "formula": str(value)} + style = {} + if bold: + style["bold"] = True + if bg: + style["bg"] = bg + if align: + style["align"] = align + if style: + c["style"] = style + return c + + # Target table header (row 1) + data["A1"] = cell("A1", "Stage", bold=True, bg="#E8EAED", align="center") + data["B1"] = cell("B1", "Weekly Target", bold=True, bg="#E8EAED", align="center") + # Target table rows 2-6 (5 stages) + targets = [ + ("Leads", 500), + ("MQLs", 180), + ("SQLs", 70), + ("Opportunities", 28), + ("Customers", 9), + ] + r = 2 + for stage, tgt in targets: + data[f"A{r}"] = cell(f"A{r}", stage) + data[f"B{r}"] = cell(f"B{r}", tgt) + r += 1 + # row 7 left blank (end of target table) + + # Current table header (row 9) + data["A9"] = cell("A9", "Stage", bold=True, bg="#E8EAED", align="center") + data["B9"] = cell("B9", "Actual", bold=True, bg="#E8EAED", align="center") + data["C9"] = cell("C9", "Source System", bold=True, bg="#E8EAED", align="center") + data["D9"] = cell("D9", "Variance", bold=True, bg="#E8EAED", align="center") + # Current table rows 10-14 (5 stages) — Stage label only; B/C/D blank + stages = ["Leads", "MQLs", "SQLs", "Opportunities", "Customers"] + r = 10 + for stage in stages: + data[f"A{r}"] = cell(f"A{r}", stage) + # B, C, D intentionally left empty (to be filled by the agent) + r += 1 + # row 15 left blank + + return { + "id": "workbook_growth_funnel_q3", + "title": "Growth Funnel Q3", + "activeSheetId": "sheet_weekly", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [ + { + "id": "sheet_weekly", + "name": "Weekly", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": None, + "isHidden": False, + "columnWidths": {"0": 140, "1": 120, "2": 140, "3": 100}, + "rowHeights": {}, + "filterRange": None, + "filterCriteria": {}, + "sortColumn": None, + "sortDirection": None, + "data": data, + } + ], + } + + +# ---------------------------------------------------------------------------- +# Salesforce state (read-only reference; same in initial & golden) +# ---------------------------------------------------------------------------- +def build_salesforce_state(): + return { + "user": { + "userId": "user-1", + "firstName": "John", + "lastName": "Smith", + "email": "john.smith@company.com", + "phone": "(555) 123-4567", + "title": "Sales Manager", + "department": "Sales", + "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + }, + "users": [ + { + "userId": "user-1", + "firstName": "John", + "lastName": "Smith", + "email": "john.smith@company.com", + "phone": "(555) 123-4567", + "title": "Sales Manager", + "department": "Sales", + "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + }, + { + "userId": "user-2", + "firstName": "Emma", + "lastName": "Wilson", + "email": "emma.wilson@company.com", + "phone": "(555) 234-5678", + "title": "Senior Sales Rep", + "department": "Sales", + "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/New_York", + "locale": "en-US", + "theme": "lightning", + }, + ], + "leads": [], + "accounts": [], + "contacts": [], + "opportunities": [], + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + "reportSnapshots": [ + { + "id": "snapshot_campaign_attr", + "reportName": "Campaign Attribution", + "reportType": "Campaign Attribution", + "columns": ["Stage", "Count", "Source System"], + "rows": [ + {"Stage": "SQLs", "Count": 63, "Source System": "Salesforce"}, + {"Stage": "Opportunities", "Count": 24, "Source System": "Salesforce"}, + {"Stage": "Customers", "Count": 7, "Source System": "Salesforce"}, + ], + "generatedAt": "2026-07-02T09:00:00Z", + } + ], + "dashboards": [ + { + "id": "dash_pipeline", + "name": "Pipeline Report", + "components": [ + {"label": "SQLs", "value": 63, "source": "Campaign Attribution"}, + {"label": "Opportunities", "value": 24, "source": "Pipeline Report"}, + {"label": "Customers", "value": 7, "source": "Pipeline Report"}, + ], + } + ], + "emailDrafts": [], + "partners": [], + } + + +# ---------------------------------------------------------------------------- +# Google Docs state (NO funnel report doc yet) +# ---------------------------------------------------------------------------- +def build_docs_state(): + return { + "currentUser": { + "id": "user-1", + "name": "Demo User", + "email": "demo@example.com", + "avatar": "https://picsum.photos/100/100?random=user1", + }, + "users": [ + { + "id": "user-1", + "name": "Demo User", + "email": "demo@example.com", + "avatar": "https://picsum.photos/100/100?random=user1", + }, + { + "id": "user-2", + "name": "Alice Chen", + "email": "alice@example.com", + "avatar": "https://picsum.photos/100/100?random=user2", + }, + ], + "documents": { + "doc-1": { + "id": "doc-1", + "title": "Project Proposal", + "content": "

Project Proposal

Draft proposal document.

", + "ownerId": "user-1", + "starred": False, + "created": "2026-06-20T10:00:00Z", + "updated": "2026-06-25T14:30: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": "", + }, + } + + +# ---------------------------------------------------------------------------- +# Slack state (#growth-reviews exists, empty) +# ---------------------------------------------------------------------------- +def build_slack_state(): + users = [ + { + "userId": f"user_{i}", + "fullName": n, + "displayName": n.split()[0], + "email": f"user{i}@company.com", + "avatar": f"https://picsum.photos/200/200?random={i}", + "status": "active", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York", + } + for i, n in enumerate( + [ + "John Smith", + "Sarah Johnson", + "Mike Chen", + "Emily Davis", + "David Lee", + "Jessica Wong", + "Tom Brown", + "Rachel Lee", + ], + start=1, + ) + ] + channels = [ + { + "channelId": "general", + "name": "general", + "description": "Company-wide announcements", + "topic": "", + "isPrivate": False, + "isStarred": False, + "members": [u["userId"] for u in users], + "createdBy": "user_1", + "createdAt": "2026-01-01T10:00:00Z", + "pinnedMessages": [], + "unreadCount": 0, + }, + { + "channelId": "growth-reviews", + "name": "growth-reviews", + "description": "Weekly growth funnel reviews and pipeline discussion", + "topic": "Growth funnel reporting", + "isPrivate": False, + "isStarred": False, + "members": [u["userId"] for u in users], + "createdBy": "user_1", + "createdAt": "2026-06-15T10:00:00Z", + "pinnedMessages": [], + "unreadCount": 0, + }, + ] + return { + "currentUser": users[0], + "workspace": { + "workspaceId": "ws_1", + "workspaceName": "Acme Corp", + "icon": "https://picsum.photos/64/64?random=workspace", + }, + "users": users, + "channels": channels, + "messages": {"general": [], "growth-reviews": []}, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": { + "theme": "light", + "notifications": "all", + "displayDensity": "comfortable", + "showAvatars": True, + "use24Hour": False, + }, + "invitations": [], + "notifications": [], + } + + +# ---------------------------------------------------------------------------- +# Inject + launch +# ---------------------------------------------------------------------------- +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) + + +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() + + +def main(): + states = { + "google_sheets": build_sheets_state(), + "salesforce": build_salesforce_state(), + "google_docs": build_docs_state(), + "slack": build_slack_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} set failed: {resp.text}" + print(f"Injected initial state for {name}") + + # CRITICAL: also set the CURRENT state to the SAME clean baseline so the + # initial env's current_state is clean (reward(initial) == 0.0). Without this + # the initial env's current_state would be empty/None and could be polluted + # by the golden env sharing the same server. Using a distinct sid here means + # golden_patch.py (different sid) can never touch this env's state. + for name, url in MOCKS.items(): + resp = requests.post( + f"{url}/post?sid={SID}", + json={"action": "set_current", "state": states[name]}, + timeout=30, + ) + assert resp.status_code == 200, f"{name} set_current failed: {resp.text}" + print(f"Injected clean current state for {name}") + + # Verify + for name, url in MOCKS.items(): + go = requests.get(f"{url}/go?sid={SID}", timeout=10).json() + assert go["initial_state"] is not None, f"{name} initial_state is None" + assert go["current_state"] is not None, f"{name} current_state is None" + print("Verified: all initial_states and current_states set (clean)") + + # Launch a Chrome window for EVERY mock the task touches + for name, url in MOCKS.items(): + launch_gui(f'google-chrome "{url}/?sid={SID}"', delay_sec=0.5) + + wait_for_mocks_loaded(MOCKS, SID) + print(f"GUI_READY: all {len(MOCKS)} mocks launched and verified (sid={SID})") + + +if __name__ == "__main__": + main() diff --git a/mktg_funnel_report_007/reward.py b/mktg_funnel_report_007/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce2902fa3d127730e5306b7dbafdd59b778c233 --- /dev/null +++ b/mktg_funnel_report_007/reward.py @@ -0,0 +1,319 @@ +""" +Reward Script: Weekly Funnel Report cross-app pipeline (Sheets -> Salesforce -> Docs -> Slack) +Task ID: mktg_funnel_report_007 +Domain: mock_websites (multi-mock: google_sheets, salesforce, google_docs, slack) +Scoring: 3 scored components (sheets=0.40, docs=0.35, slack=0.25) + Salesforce precondition gate. + All scoring components verify TASK-INTRODUCED changes (they fail on the clean initial + state and pass on the golden state). Salesforce is a read-only reference and is used + only as a precondition gate (0 points) so it cannot inflate the initial_env score. + The reward script reads the sid dynamically from /tmp/task_web_sid on the target VM, + so it works identically on both the initial and golden VMs. +""" +import json +import sys + +import requests + +# Mock base URLs (from task_config.json task_instruction) +MOCKS = { + 'sheets': 'http://28.7.184.198:8145', + 'salesforce': 'http://28.7.184.198:8175', + 'docs': 'http://28.7.184.198:8142', + 'slack': 'http://28.7.184.198:8178', +} + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility. + + Parsed by the evaluator to report which sub-objectives passed/failed + instead of only a single aggregate float. Format: ``COMPONENT: ``. + """ + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check function, emit PASS/FAIL + COMPONENT line. + + Returns (passed, score, detail) — score is 0.0 on exception. + """ + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# ---------------------------------------------------------------------------- +# Precondition gate: Salesforce Campaign Attribution report (read-only reference) +# ---------------------------------------------------------------------------- + +def check_salesforce_gate(sf_state): + """Salesforce 'Campaign Attribution' report exists and shows SQL=63/Opp=24/Customer=7. + This is a read-only reference the agent must confirm; it is identical in both envs + so it is used as a precondition gate (0 points) and must pass for scoring to proceed. + Pass condition: reportSnapshots contains a 'Campaign Attribution' report whose rows + include SQLs=63, Opportunities=24, Customers=7. + """ + snapshots = sf_state.get('reportSnapshots', []) or [] + target = {'SQLs': 63, 'Opportunities': 24, 'Customers': 7} + found = {} + for snap in snapshots: + if snap.get('reportType') == 'Campaign Attribution' or 'Campaign Attribution' in str(snap.get('reportName', '')): + for row in snap.get('rows', []): + stage = row.get('Stage') + cnt = row.get('Count') + if stage in target: + found[stage] = cnt + missing = [k for k, v in target.items() if found.get(k) != v] + if not missing: + return True, 0.0, f'Campaign Attribution confirms SQLs=63/Opp=24/Customers=7 (found: {found})' + return False, 0.0, f'Campaign Attribution missing/invalid: {found} (expected {target})' + + +# ---------------------------------------------------------------------------- +# Scored component 1: Google Sheets 'Weekly' Current table (rows 10-14) +# ---------------------------------------------------------------------------- + +def check_component_1(sheets_state): + """Google Sheets 'Weekly' 'Current' table rows 10-14 have B=472/165/63/24/7, + C=HubSpot/HubSpot/Salesforce/Salesforce/Salesforce, D=-28/-15/-7/-4/-2. + Pass condition: the 'Weekly' sheet exists and rows 10-14 B/C/D match the ground-truth + values (all 5 stages). Column D accepts either the literal computed value (e.g. '-28') + or an equivalent formula '=B{r}-B{r-8}' (e.g. '=B10-B2') that evaluates to the expected + variance when resolved against the sheet's B column. Fails on the clean initial state + (B/C/D blank). + """ + stages = ['Leads', 'MQLs', 'SQLs', 'Opportunities', 'Customers'] + exp_b = ['472', '165', '63', '24', '7'] + exp_c = ['HubSpot', 'HubSpot', 'Salesforce', 'Salesforce', 'Salesforce'] + exp_d = ['-28', '-15', '-7', '-4', '-2'] + + weekly = None + for s in sheets_state.get('sheets', []): + if s.get('name') == 'Weekly': + weekly = s + break + if weekly is None: + return False, 0.0, "sheet 'Weekly' not found" + + data = weekly.get('data', {}) + + def _resolve_d(val, r): + """Resolve a D-column cell to its effective numeric string. + + Accepts a literal value (e.g. '-28') or a formula of the form + '=B{a}-B{b}' (with optional whitespace) whose referenced B cells + exist in the sheet. Returns the computed string, or None if the + formula cannot be parsed/resolved. The mock does not evaluate + formulas, so we resolve them here against the B column values. + """ + import re + s = str(val).strip() if val is not None else '' + # Literal value — return as-is (will be compared against exp_d). + if not s.startswith('='): + return s + # Formula: '=B{a}-B{b}' (Actual - Target). Resolve via B column. + m = re.match(r'^=B(\d+)\s*-\s*B(\d+)$', s) + if not m: + return None + a_row, b_row = int(m.group(1)), int(m.group(2)) + a_val = data.get(f'B{a_row}', {}).get('value') + b_val = data.get(f'B{b_row}', {}).get('value') + try: + return str(int(a_val) - int(b_val)) + except (TypeError, ValueError): + return None + + for i in range(5): + r = 10 + i + b = data.get(f'B{r}', {}).get('value') + c = data.get(f'C{r}', {}).get('value') + d_raw = data.get(f'D{r}', {}).get('value') + d_resolved = _resolve_d(d_raw, r) + if str(b) != exp_b[i] or str(c) != exp_c[i] or d_resolved != exp_d[i]: + return False, 0.0, ( + f"row{r} ({stages[i]}) mismatch: " + f"B={b!r}(exp {exp_b[i]}), C={c!r}(exp {exp_c[i]}), " + f"D={d_raw!r} -> {d_resolved!r}(exp {exp_d[i]})" + ) + return True, 0.40, "All 5 Current rows B/C/D match ground truth (472/165/63/24/7, sources, variances)" + + +# ---------------------------------------------------------------------------- +# Scored component 2: Google Docs funnel report +# ---------------------------------------------------------------------------- + +def check_component_2(docs_state): + """Google Docs has a doc titled 'Weekly Funnel Report - 2026-W27' containing an H1 + 'Weekly Funnel Report (2026-W27)', a Summary sentence with the exact pipeline text, + a 5-row Stage Detail table, and an At-Risk section naming Customers (7 vs 9, -22.2%). + Pass condition: at least one document with that title exists AND its content includes + the H1 heading, the summary sentence, the 5-stage table, and the at-risk Customers line. + Fails on the clean initial state (no such doc exists). + """ + docs = docs_state.get('documents', {}) + target_title = 'Weekly Funnel Report - 2026-W27' + candidates = [] + for did, doc in docs.items(): + if doc.get('title') == target_title: + candidates.append((did, doc.get('content', ''))) + + if not candidates: + return False, 0.0, f"no document titled {target_title!r} found" + + doc_id, content = candidates[0] + + # H1 heading + has_h1 = 'Weekly Funnel Report (2026-W27)' in content + # Summary sentence (exact) + summary = 'Pipeline is tracking 4% below target on volume; Customers are the at-risk stage at -22.2% vs goal.' + has_summary = summary in content + # 5-row table: check all 5 stage rows present with stage/target/actual + table_rows = [ + ('Leads', '500', '472'), + ('MQLs', '180', '165'), + ('SQLs', '70', '63'), + ('Opportunities', '28', '24'), + ('Customers', '9', '7'), + ] + missing_rows = [tr[0] for tr in table_rows + if not all(x in content for x in tr)] + has_table = len(missing_rows) == 0 + # At-Risk section naming Customers (7 vs 9, -22.2%) + at_risk = 'Customers (7 vs 9, -22.2%)' in content and 'At-Risk' in content + + ok = has_h1 and has_summary and has_table and at_risk + if not ok: + missing = [] + if not has_h1: + missing.append('H1 heading') + if not has_summary: + missing.append('summary sentence') + if not has_table: + missing.append(f'table rows for {missing_rows}') + if not at_risk: + missing.append('At-Risk Customers line') + return False, 0.0, f"doc {doc_id} missing: {', '.join(missing)}" + + return True, 0.35, f"doc {doc_id} has H1, summary, 5-row table, and At-Risk Customers section" + + +# ---------------------------------------------------------------------------- +# Scored component 3: Slack #growth-reviews message +# ---------------------------------------------------------------------------- + +def check_component_3(slack_state): + """Slack #growth-reviews has a new message containing the pipeline-vs-target line for + all 5 stages, the 'At-risk: Customers -22.2%' line, and a link to the created Google Doc. + Pass condition: #growth-reviews has >=1 message whose content includes the per-stage + 'Leads 472/500, MQLs 165/180, SQLs 63/70, Opps 24/28, Customers 7/9' line, the + 'At-risk: Customers -22.2%' line, and a doc URL (http.../doc...). + Fails on the clean initial state (0 messages in #growth-reviews). + """ + msgs = slack_state.get('messages', {}) + # Find the growth-reviews channel (key may be channelId or name) + growth_msgs = [] + for ch, mlist in msgs.items(): + if 'growth' in str(ch).lower() or 'review' in str(ch).lower(): + growth_msgs.extend(mlist or []) + + if not growth_msgs: + return False, 0.0, "#growth-reviews has 0 messages" + + # Concatenate all message contents for robust matching + combined = "\n".join(m.get('content', '') for m in growth_msgs) + + # Pipeline line: all 5 stages with their actual/target + pipeline_parts = [ + 'Leads 472/500', + 'MQLs 165/180', + 'SQLs 63/70', + 'Opps 24/28', + 'Customers 7/9', + ] + has_pipeline = all(p in combined for p in pipeline_parts) + has_atrisk = 'At-risk: Customers -22.2%' in combined + # Doc URL: should link to a Google Doc (contains /doc and a doc id) + import re + has_doc_url = bool(re.search(r'https?://\S*/doc\S*', combined)) + + if not (has_pipeline and has_atrisk and has_doc_url): + missing = [] + if not has_pipeline: + missing.append('pipeline line for all 5 stages') + if not has_atrisk: + missing.append('At-risk: Customers -22.2% line') + if not has_doc_url: + missing.append('Google Doc URL') + return False, 0.0, f"message missing: {', '.join(missing)}" + + return True, 0.25, "Slack message has pipeline line, at-risk line, and doc URL" + + +# ---------------------------------------------------------------------------- +# Main +# ---------------------------------------------------------------------------- + +def verify_task(): + # --- Read sid dynamically from the target VM --- + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') + except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + return 0.0 + + # --- Fetch state from all 4 mocks --- + states = {} + for name, url in MOCKS.items(): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + states[name] = data.get('current_state', {}) + except Exception as e: + print(f'CRITICAL: Cannot fetch {name} state for sid={sid}: {e}') + print('REWARD: 0.0') + return 0.0 + + # --- Precondition gate: Salesforce Campaign Attribution (0 points, must pass) --- + gate_passed, _, gate_detail = check_salesforce_gate(states['salesforce']) + if not gate_passed: + print(f'GATE FAIL: Salesforce precondition: {gate_detail}') + print('REWARD: 0.0') + return 0.0 + print(f'GATE PASS: Salesforce Campaign Attribution confirmed (0 pts, precondition)') + + total_score = 0.0 + # Independent scored components (each verifies a task-introduced change) + for idx, name, weight, fn, args in [ + (1, 'Google Sheets Current table (rows 10-14)', 0.40, check_component_1, (states['sheets'],)), + (2, 'Google Docs funnel report', 0.35, check_component_2, (states['docs'],)), + (3, 'Slack #growth-reviews message', 0.25, check_component_3, (states['slack'],)), + ]: + _, score, _ = _run_component(idx, name, weight, fn, args) + total_score += score + + final_score = round(min(total_score, 1.0), 4) + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +if __name__ == '__main__': + verify_task() diff --git a/mktg_funnel_report_007/reward_label.json b/mktg_funnel_report_007/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..fcb78a12ce89263931edf1fcce7137d8bd949d83 --- /dev/null +++ b/mktg_funnel_report_007/reward_label.json @@ -0,0 +1,64 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof18_funnel_report_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-14 10:29:32", + "label": { + "task_id": "mktg_funnel_report_007", + "domain": "mock_websites", + "summary": "验证跨应用管道任务:读取 Salesforce 作为前置校验,检查 Google Sheets Weekly 工作表数据更新、Google Docs 漏斗报告创建、Slack #growth-reviews 消息发送是否正确完成", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_sheets_mock (http://28.7.186.212:8165)", + "salesforce_mock (http://28.7.186.212:8195)", + "google_docs_mock (http://28.7.186.212:8162)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Salesforce precondition gate", + "weight": 0.0, + "description": "Salesforce Campaign Attribution 报告作为只读前置条件,必须包含指定数据才能进入正式评分", + "check_logic": "遍历 sf_state['reportSnapshots'],查找 reportType 或 reportName 包含 'Campaign Attribution' 的报告,检查其 rows 中 Stage 为 SQLs/Opportunities/Customers 对应的 Count 是否分别为 63/24/7", + "pass_condition": "reportSnapshots 中存在 Campaign Attribution 报告,且行数据包含 SQLs=63、Opportunities=24、Customers=7" + }, + { + "name": "Component 1: Google Sheets Current table (rows 10-14)", + "weight": 0.4, + "description": "检查 Google Sheets 的 Weekly 工作表中 Current 表格第10-14行是否按预期更新", + "check_logic": "在 sheets_state['sheets'] 中查找 name 为 'Weekly' 的工作表,依次检查第10-14行(对应 Leads/MQLs/SQLs/Opportunities/Customers)的 B、C、D 列值是否与预期字符串完全相等:B 列为 472/165/63/24/7,C 列为 HubSpot/HubSpot/Salesforce/Salesforce/Salesforce,D 列为 -28/-15/-7/-4/-2", + "pass_condition": "Weekly 工作表存在,且第10-14行的 B、C、D 列值与预期完全一致" + }, + { + "name": "Component 2: Google Docs funnel report", + "weight": 0.35, + "description": "检查 Google Docs 中是否创建了指定标题的漏斗报告文档,且内容包含必要的标题、摘要、表格和风险提示", + "check_logic": "在 docs_state['documents'] 中查找 title 为 'Weekly Funnel Report - 2026-W27' 的文档,检查其 content 是否同时包含:(1) H1 标题 'Weekly Funnel Report (2026-W27)';(2) 摘要句 'Pipeline is tracking 4% below target on volume; Customers are the at-risk stage at -22.2% vs goal.';(3) 5阶段表格行(Leads/500/472、MQLs/180/165、SQLs/70/63、Opportunities/28/24、Customers/9/7)均出现在内容中;(4) 包含 'At-Risk' 且包含 'Customers (7 vs 9, -22.2%)'", + "pass_condition": "存在指定标题的文档,且内容同时包含 H1 标题、摘要句、5阶段表格和 At-Risk Customers 行" + }, + { + "name": "Component 3: Slack #growth-reviews message", + "weight": 0.25, + "description": "检查 Slack #growth-reviews 频道是否发送了包含各阶段数据、风险提示和文档链接的消息", + "check_logic": "在 slack_state['messages'] 中查找 channel 名称包含 'growth' 或 'review' 的频道,合并所有消息内容后检查:(1) 包含5个阶段的 pipeline 片段('Leads 472/500'、'MQLs 165/180'、'SQLs 63/70'、'Opps 24/28'、'Customers 7/9');(2) 包含 'At-risk: Customers -22.2%';(3) 内容中存在匹配正则 https?://\\S*/doc\\S* 的 Google Doc URL", + "pass_condition": "#growth-reviews 频道至少有一条消息,且合并后的内容包含全部5阶段 pipeline 行、At-risk 行和文档 URL" + } + ], + "total_max_score": 1.0, + "score_aggregation": "三个评分组件的得分直接相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留4位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 sid 或 sid 为空,直接返回 0.0", + "从任一 mock 服务(sheets/salesforce/docs/slack)拉取状态失败,直接返回 0.0", + "Salesforce precondition gate 未通过(Campaign Attribution 报告缺失或数据不匹配),直接返回 0.0", + "Google Sheets 中 Weekly 工作表不存在,或第10-14行 B/C/D 任一单元格值不匹配,该组件得 0.0", + "Google Docs 中不存在指定标题文档,或内容缺失 H1/摘要/表格/At-Risk 任一部分,该组件得 0.0", + "Slack #growth-reviews 频道无消息,或合并内容缺失 pipeline 行/At-risk 行/Doc URL 任一,该组件得 0.0", + "组件检查函数执行异常时该组件得 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,随后向四个 mock 服务并发请求当前状态。第一步执行 Salesforce precondition gate(0分):验证 Campaign Attribution 报告包含 SQLs=63、Opportunities=24、Customers=7;若未通过则立即返回 0.0。通过 gate 后,依次独立执行三个评分组件:组件1(0.40分)验证 Google Sheets Weekly 工作表第10-14行 B/C/D 列的5阶段数据与来源/偏差值是否完全匹配;组件2(0.35分)验证 Google Docs 是否存在指定标题的漏斗报告文档,并检查其内容是否包含 H1 标题、摘要句、5阶段表格和 At-Risk Customers 行;组件3(0.25分)验证 Slack #growth-reviews 频道消息是否包含5阶段 pipeline 数据、At-risk 提示和文档链接。各组件通过则获得对应权重分数,失败则得 0.0。最终总分为各组件得分之和,上限钳制在 1.0 并四舍五入到4位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中提取,是 `prof18_funnel_report_003`\n2. **domain**: 从 docstring 中提取,是 `mock_websites`\n3. **summary**: 一句话概括。这个脚本验证跨应用管道任务:从 Salesforce 读取数据,在 Google Sheets 的 Weekly 工作表中更新 Current 表格,在 Google Docs 创建漏斗报告,并在 Slack #growth-reviews 频道发送消息。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: 脚本从 `/tmp/task_web_sid` 读取 sid,然后从四个 mock 服务获取状态:google_sheets (`http://28.7.186.212:8165`)、salesforce (`http://28.7.186.212:8195`)、google_docs (`http://28.7.186.212:8162`)、slack (`http://28.7.186.212:8198`)。\n6. **scoring_components**:\n - Component 1: Google Sheets Current table (rows 10-14), weight=0.40, 检查 Weekly 工作表第10-14行 B/C/D 列是否匹配预期值。\n - Component 2: Google Docs funnel report, weight=0.35, 检查是否存在标题为 'Weekly Funnel Report - 2026-W27' 的文档,且内容包含 H1 标题、摘要句、5行表格、At-Risk Customers 部分。\n - Component 3: Slack #growth-reviews message, weight=0.25, 检查 #growth-reviews 频道是否有消息包含5个阶段的 pipeline 行、At-risk 行和 Google Doc URL。\n - 还有一个 Salesforce precondition gate,weight=0.0,检查 Campaign Attribution 报告是否存在且包含 SQLs=63, Opportunities=24, Customers=7。\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,然后钳制到上限 1.0(`min(total_score, 1.0)`)。\n9. **failure_modes**:\n - 读取 `/tmp/task_web_sid` 失败或为空,返回 0.0\n - 从任一 mock 服务获取状态失败,返回 0.0\n - Salesforce precondition gate 失败,返回 0.0\n - 各组件检查失败则该组件得 0.0 分\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 从 `/tmp/task_web_sid` 动态读取 sid\n - 使用 sid 从四个 mock 服务(sheets, salesforce, docs, slack)获取当前状态\n - 先执行 Salesforce precondition gate:检查 Campaign Attribution 报告是否包含 SQLs=63, Opportunities=24, Customers=7。若不通过,直接返回 0.0\n - 然后依次执行三个独立评分组件:\n 1. Google Sheets:检查 Weekly 工作表第10-14行(Leads/MQLs/SQLs/Opportunities/Customers)的 B/C/D 列值是否完全匹配预期(B: 472/165/63/24/7, C: HubSpot/HubSpot/Salesforce/Salesforce/Salesforce, D: -28/-15/-7/-4/-2)。通过得 0.40 分。\n 2. Google Docs:检查是否存在标题为 'Weekly Funnel Report - 2026-W27' 的文档,且内容包含特定 H1 标题、摘要句、5阶段表格和 At-Risk Customers 行。通过得 0.35 分。\n 3. Slack:检查 #growth-reviews 频道消息是否包含5阶段 pipeline 数据、At-risk: Customers -22.2% 行和 Google Doc URL。通过得 0.25 分。\n - 汇总各组件得分,总和上限为 1.0,四舍五入到4位小数返回。\n11. **confidence**: 1.0,因为代码逻辑清晰完整。\n\n现在构建 JSON。注意:\n- 所有字符串 value 使用中文\n- task_id、domain、字段名、代码标识符保留原样\n- 不要输出 Markdown 代码块标记\n- 只输出 JSON 对象,第一个字符是 {,最后一个字符是 }\n- weight 字段填写代码中显式给出的分值\n\n让我确认每个组件的 pass_condition:\n- Component 1: Weekly 工作表存在,且第10-14行的 B、C、D 列值与预期完全匹配(字符串比较)。\n- Component 2: 至少存在一个指定标题的文档,且其内容包含 H1 标题 'Weekly Funnel Report (2026-W27)'、特定摘要句、5阶段表格(每行包含阶段名/目标值/实际值)以及 At-Risk Customers 行。\n- Component 3: #growth-reviews 频道至少有一条消息,其内容(合并所有消息)包含5个阶段的 pipeline 行(如 'Leads 472/500' 等)、'At-risk: Customers -22.2%' 行以及匹配 `https?://\\S*/doc\\S*` 的文档 URL。\n- Gate: reportSnapshots 中存在 'Campaign Attribution' 报告,且其行数据包含 SQLs=63、Opportunities=24、Customers=7。\n\nfailure_modes 列表:\n- 无法从 /tmp/task_web_sid 读取 sid 或 sid 为空\n- 无法从任一 mock 服务获取状态(网络请求失败)\n- Salesforce precondition gate 未通过\n- Google Sheets 中 Weekly 工作表不存在或行数据不匹配\n- Google Docs 中不存在指定标题的文档或内容缺失必要部分\n- Slack #growth-reviews 无消息或消息内容缺失 pipeline/At-risk/Doc URL\n\nscore_aggregation: 各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到4位小数。\n\n让我再仔细检查一下代码细节:\n- `_run_component` 在异常时返回 False, 0.0, error detail\n- `verify_task` 中如果 gate 失败,打印 GATE FAIL 和 REWARD: 0.0,返回 0.0\n- 各组件分数直接相加:`total_score += score`\n- 最后 `final_score = round(min(total_score, 1.0), 4)`\n\nJSON 结构需要完全符合要求。 {\"task_id\":\"prof18_funnel_report_003\",\"domain\":\"mock_websites\",\"summary\":\"验证跨应用管道任务:读取 Salesforce 作为前置校验,检查 Google Sheets Weekly 工作表数据更新、Google Docs 漏斗报告创建、Slack #growth-reviews 消息发送是否正确完成\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock (http://28.7.186.212:8165)\",\"salesforce_mock (http://28.7.186.212:8195)\",\"google_docs_mock (http://28.7.186.212:8162)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Salesforce precondition gate\",\"weight\":0.0,\"description\":\"Salesforce Campaign Attribution 报告作为只读前置条件,必须包含指定数据才能进入正式评分\",\"check_logic\":\"遍历 sf_state['reportSnapshots'],查找 reportType 或 reportName 包含 'Campaign Attribution' 的报告,检查其 rows 中 Stage 为 SQLs/Opportunities/Customers 对应的 Count 是否分别为 63/24/7\",\"pass_condition\":\"reportSnapshots 中存在 Campaign Attribution 报告,且行数据包含 SQLs=63、Opportunities=24、Customers=7\"},{\"name\":\"Component 1: Google Sheets Current table (rows 10-14)\",\"weight\":0.4,\"description\":\"检查 Google Sheets 的 Weekly 工作表中 Current 表格第10-14行是否按预期更新\",\"check_logic\":\"在 sheets_state['sheets'] 中查找 name 为 'Weekly' 的工作表,依次检查第10-14行(对应 Leads/MQLs/SQLs/Opportunities/Customers)的 B、C、D 列值是否与预期字符串完全相等:B 列为 472/165/63/24/7,C 列为 HubSpot/HubSpot/Salesforce/Salesforce/Salesforce,D 列为 -28/-15/-7/-4/-2\",\"pass_condition\":\"Weekly 工作表存在,且第10-14行的 B、C、D 列值与预期完全一致\"},{\"name\":\"Component 2: Google Docs funnel report\",\"weight\":0.35,\"description\":\"检查 Google Docs 中是否创建了指定标题的漏斗报告文档,且内容包含必要的标题、摘要、表格和风险提示\",\"check_logic\":\"在 docs_state['documents'] 中查找 title 为 'Weekly Funnel Report - 2026-W27' 的文档,检查其 content 是否同时包含:(1) H1 标题 'Weekly Funnel Report (2026-W27)';(2) 摘要句 'Pipeline is tracking 4% below target on volume; Customers are the at-risk stage at -22.2% vs goal.';(3) 5阶段表格行(Leads/500/472、MQLs/180/165、SQLs/70/63、Opportunities/28/24、Customers/9/7)均出现在内容中;(4) 包含 'At-Risk' 且包含 'Customers (7 vs 9, -22.2%)'\",\"pass_condition\":\"存在指定标题的文档,且内容同时包含 H1 标题、摘要句、5阶段表格和 At-Risk Customers 行\"},{\"name\":\"Component 3: Slack #growth-reviews message\",\"weight\":0.25,\"description\":\"检查 Slack #growth-reviews 频道是否发送了包含各阶段数据、风险提示和文档链接的消息\",\"check_logic\":\"在 slack_state['messages'] 中查找 channel 名称包含 'growth' 或 'review' 的频道,合并所有消息内容后检查:(1) 包含5个阶段的 pipeline 片段('Leads 472/500'、'MQLs 165/180'、'SQLs 63/70'、'Opps 24/28'、'Customers 7/9');(2) 包含 'At-risk: Customers -22.2%';(3) 内容中存在匹配正则 https?://\\\\S*/doc\\\\S* 的 Google Doc URL\",\"pass_condition\":\"#growth-reviews 频道至少有一条消息,且合并后的内容包含全部5阶段 pipeline 行、At-risk 行和文档 URL\"}],\"total_max_score\":1.0,\"score_aggregation\":\"三个评分组件的得分直接相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留4位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空,直接返回 0.0\",\"从任一 mock 服务(sheets/salesforce/docs/slack)拉取状态失败,直接返回 0.0\",\"Salesforce precondition gate 未通过(Campaign Attribution 报告缺失或数据不匹配),直接返回 0.0\",\"Google Sheets 中 Weekly 工作表不存在,或第10-14行 B/C/D 任一单元格值不匹配,该组件得 0.0\",\"Google Docs 中不存在指定标题文档,或内容缺失 H1/摘要/表格/At-Risk 任一部分,该组件得 0.0\",\"Slack #growth-reviews 频道无消息,或合并内容缺失 pipeline 行/At-risk 行/Doc URL 任一,该组件得 0.0\",\"组件检查函数执行异常时该组件得 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,随后向四个 mock 服务并发请求当前状态。第一步执行 Salesforce precondition gate(0分):验证 Campaign Attribution 报告包含 SQLs=63、Opportunities=24、Customers=7;若未通过则立即返回 0.0。通过 gate 后,依次独立执行三个评分组件:组件1(0.40分)验证 Google Sheets Weekly 工作表第10-14行 B/C/D 列的5阶段数据与来源/偏差值是否完全匹配;组件2(0.35分)验证 Google Docs 是否存在指定标题的漏斗报告文档,并检查其内容是否包含 H1 标题、摘要句、5阶段表格和 At-Risk Customers 行;组件3(0.25分)验证 Slack #growth-reviews 频道消息是否包含5阶段 pipeline 数据、At-risk 提示和文档链接。各组件通过则获得对应权重分数,失败则得 0.0。最终总分为各组件得分之和,上限钳制在 1.0 并四舍五入到4位小数输出。\",\"confidence\":1.0}" +} diff --git a/mktg_social_approve_010/_cua_gym_vm_bridge.sh b/mktg_social_approve_010/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_social_approve_010/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/mktg_social_approve_010/initial_setup.py b/mktg_social_approve_010/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a693e3ee32d05f87e27ab3c3f78ada2a204c45ce --- /dev/null +++ b/mktg_social_approve_010/initial_setup.py @@ -0,0 +1,181 @@ +""" +Initial Setup: Trello Content Pipeline — move card-002 to Legal Review and set custom fields +Task ID: mktg_social_approve_010 +Domain: mock_websites +Mock: trello_mock +URL: http://28.7.184.198:8182 + +NOTE: The initial and golden VMs share the same external mock server +(http://28.7.184.198:8182). To keep the two environments isolated, we use a +separate deterministic session id (sid) per environment. This script owns the +"initial" sid (sid_initial), which it writes to /tmp/task_web_sid so that the +reward script on the initial VM can find it. +""" + +import hashlib +import json +import os +import shlex +import subprocess +import time + +import requests + +# --- Config --- +BASE_URL = "http://28.7.184.198:8182" +TASK_ID = "prof36_post_approve_001" + +# Deterministic sid for the INITIAL environment. Distinct from the golden sid so +# the two environments do not clobber each other on the shared mock server. +sid = "task-" + hashlib.sha256((TASK_ID + ":initial").encode()).hexdigest()[:24] +with open("/tmp/task_web_sid", "w") as f: + f.write(sid) + +# --- Build the full initial state (Content Pipeline board) --- +users = { + "u1": {"id": "u1", "name": "Maya Chen", "username": "mayac", "initials": "MC", + "email": "maya.chen@northwind.com", "avatarUrl": ""}, + "u2": {"id": "u2", "name": "Liam Foster", "username": "liamf", "initials": "LF", + "email": "liam.foster@northwind.com", "avatarUrl": ""}, + "u3": {"id": "u3", "name": "Priya Nair", "username": "priyan", "initials": "PN", + "email": "priya.nair@northwind.com", "avatarUrl": ""}, + "u4": {"id": "u4", "name": "Diego Ramos", "username": "dieg0r", "initials": "DR", + "email": "diego.ramos@northwind.com", "avatarUrl": ""}, +} + +board_cp_01 = { + "id": "board_cp_01", + "title": "Content Pipeline", + "description": "Northwind Co. social media content pipeline for Q3 2026.", + "background": "#0079BF", + "listIds": ["list_draft_01", "list_legal_01", "list_appr_01", "list_sched_01", "list_pub_01"], + "starred": True, + "visibility": "workspace", + "archivedListIds": [], + "archivedCardIds": [], + "labels": [ + {"id": "lbl_cp_1", "name": "LinkedIn", "color": "#0079bf"}, + {"id": "lbl_cp_2", "name": "Instagram", "color": "#c377e0"}, + {"id": "lbl_cp_3", "name": "X/Twitter", "color": "#00aecc"}, + {"id": "lbl_cp_4", "name": "Urgent", "color": "#eb5a46"}, + ], + "memberIds": ["u1", "u2", "u3", "u4"], + "createdAt": "2026-06-01T09:00:00.000Z", +} + +lists = { + "list_draft_01": {"id": "list_draft_01", "title": "Draft", "boardId": "board_cp_01", + "cardIds": ["card-001", "card-002", "card-003"], "archived": False}, + "list_legal_01": {"id": "list_legal_01", "title": "Legal Review", "boardId": "board_cp_01", + "cardIds": [], "archived": False}, + "list_appr_01": {"id": "list_appr_01", "title": "Approved", "boardId": "board_cp_01", + "cardIds": ["card-004", "card-005"], "archived": False}, + "list_sched_01": {"id": "list_sched_01", "title": "Scheduled", "boardId": "board_cp_01", + "cardIds": ["card-006", "card-007"], "archived": False}, + "list_pub_01": {"id": "list_pub_01", "title": "Published", "boardId": "board_cp_01", + "cardIds": ["card-008", "card-009"], "archived": False}, +} + + +def make_card(cid, title, desc, list_id, pos, member_ids=None, labels=None): + return { + "id": cid, + "title": title, + "description": desc, + "listId": list_id, + "boardId": "board_cp_01", + "labelIds": labels or [], + "memberIds": member_ids or [], + "dueDate": None, + "startDate": None, + "completed": False, + "cover": None, + "checklists": [], + "comments": [], + "attachments": [], + "archived": False, + "watching": False, + "position": pos, + "createdAt": "2026-06-10T08:00:00.000Z", + # Custom fields exist but are blank in the initial state + "customFields": {}, + } + + +cards = { + "card-001": make_card( + "card-001", "Post: Weekly Tips Roundup (Instagram)", + "Weekly Instagram carousel with 5 productivity tips for SMBs.", "list_draft_01", 0, + member_ids=["u3"], labels=["lbl_cp_2"]), + "card-002": make_card( + "card-002", "Post: Q3 Product Launch Teaser (LinkedIn)", + "Short LinkedIn teaser announcing the Q3 product launch. Needs legal review before publishing.", + "list_draft_01", 1, member_ids=["u1"], labels=["lbl_cp_1"]), + "card-003": make_card( + "card-003", "Post: Customer Spotlight (X/Twitter)", + "Feature a happy customer story for the X/Twitter channel.", "list_draft_01", 2, + member_ids=["u2"], labels=["lbl_cp_3"]), + "card-004": make_card( + "card-004", "Post: Behind the Scenes (Instagram)", + "Studio behind-the-scenes reel approved by marketing.", "list_appr_01", 0, + member_ids=["u3"], labels=["lbl_cp_2"]), + "card-005": make_card( + "card-005", "Post: Webinar Announcement (LinkedIn)", + "LinkedIn post announcing the July webinar.", "list_appr_01", 1, + member_ids=["u1"], labels=["lbl_cp_1"]), + "card-006": make_card( + "card-006", "Post: Holiday Sale (X/Twitter)", + "Promote the mid-summer sale on X/Twitter.", "list_sched_01", 0, + member_ids=["u2"], labels=["lbl_cp_3"]), + "card-007": make_card( + "card-007", "Post: Founder Q&A (LinkedIn)", + "Founder AMA scheduled for next week.", "list_sched_01", 1, + member_ids=["u1"], labels=["lbl_cp_1"]), + "card-008": make_card( + "card-008", "Post: Product of the Month (Instagram)", + "Monthly product feature, already published.", "list_pub_01", 0, + member_ids=["u3"], labels=["lbl_cp_2"]), + "card-009": make_card( + "card-009", "Post: Team Milestone (LinkedIn)", + "Company milestone celebration post, published.", "list_pub_01", 1, + member_ids=["u1"], labels=["lbl_cp_1"]), +} + +state = { + "currentUser": "u1", + "users": users, + "boards": {"board_cp_01": board_cp_01}, + "lists": lists, + "cards": cards, + "boardOrder": ["board_cp_01"], +} + +# --- Inject state (action: set creates initial_state + current_state) --- +resp = requests.post( + f"{BASE_URL}/post?sid={sid}", + json={"action": "set", "state": state}, + timeout=30, +) +assert resp.status_code == 200, f"State injection failed: {resp.text}" +print(f"Initial state injected: sid={sid}") + +# --- Verify --- +go = requests.get(f"{BASE_URL}/go?sid={sid}", timeout=10).json() +assert go["initial_state"] is not None, "initial_state is None after injection" +print("Verified: initial_state and current_state are set") + +# --- Launch browser --- +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen( + shlex.split(command), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + ) + time.sleep(delay_sec) + +launch_gui(f'google-chrome "{BASE_URL}/?sid={sid}"', delay_sec=2.0) + +print(f"GUI_READY: launched browser at {BASE_URL}/?sid={sid}") diff --git a/mktg_social_approve_010/reward.py b/mktg_social_approve_010/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..59ea78871ca92d36280caf1effb2f4f980b9d6f0 --- /dev/null +++ b/mktg_social_approve_010/reward.py @@ -0,0 +1,146 @@ +""" +Reward Script: Move Trello card-002 to Legal Review +Task ID: mktg_social_approve_010 +Domain: mock_websites +Mock: trello_mock (http://28.7.184.198:8182) +Scoring: + Component 1 (0.75): card-002 now resides in list_legal_01 ( Legal Review ) + Component 2 (0.25): No other card moved/modified (distractors + other lists unchanged) +A correct task must satisfy BOTH: 1.0 only when fully correct. +""" +import json +import sys + +import requests + +BASE_URL = 'http://28.7.184.198:8182' +BOARD_ID = 'board_cp_01' +CARD_ID = 'card-002' +TARGET_LIST = 'list_legal_01' +DRAFT_LIST = 'list_draft_01' + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# --- Per-component checks (one function per sub-objective) --- + +def check_component_1(state): + """card-002 resides in the Legal Review list (list_legal_01). + Pass condition: current_state cards[card-002].listId == 'list_legal_01' AND + lists[list_legal_01].cardIds == ['card-002'] (only this card in Legal Review).""" + cards = state.get('cards', {}) + lists = state.get('lists', {}) + card = cards.get(CARD_ID) + if card is None: + return False, 0.0, f'card {CARD_ID} not found in state' + list_id = card.get('listId') + legal = lists.get(TARGET_LIST) + legal_ids = legal.get('cardIds', []) if legal else [] + if list_id == TARGET_LIST and legal_ids == [CARD_ID]: + return True, 0.75, f'card-002 in Legal Review; list contains exactly [card-002]' + return False, 0.0, f'card-002.listId={list_id!r}, legal_01.cardIds={legal_ids!r}' + + +def check_component_2(state): + """No other card moved or modified beyond card-002. + Pass condition: card-001 and card-003 remain in Draft (list_draft_01) AND the + Approved/Scheduled/Published lists each still contain exactly their 2 original cards, + unchanged. Verifies exactly one card moved (card-002).""" + cards = state.get('cards', {}) + lists = state.get('lists', {}) + + # card-001 and card-003 must remain in Draft + for cid in ('card-001', 'card-003'): + c = cards.get(cid) + if c is None or c.get('listId') != DRAFT_LIST: + return False, 0.0, f'{cid} not in Draft (listId={c.get("listId") if c else None})' + + # Draft must contain exactly card-001, card-003 (card-002 removed) + draft_ids = lists.get(DRAFT_LIST, {}).get('cardIds', []) + if sorted(draft_ids) != ['card-001', 'card-003']: + return False, 0.0, f'Draft list cardIds={draft_ids!r} (expected [card-001, card-003])' + + # Approved/Scheduled/Published each retain exactly 2 cards + for lid, expected in (('list_appr_01', 2), ('list_sched_01', 2), ('list_pub_01', 2)): + ids = lists.get(lid, {}).get('cardIds', []) + if len(ids) != expected: + return False, 0.0, f'{lid} has {len(ids)} cards (expected {expected}): {ids!r}' + + return True, 0.25, 'distractors unchanged; Draft has [card-001,card-003]; Appr/Sched/Pub each have 2 cards' + + +def verify_task(): + """Verify task completion with progressive scoring based on current_state. + Returns: float between 0.0 and 1.0""" + # Read sid dynamically from the VM's /tmp/task_web_sid + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') + except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + return 0.0 + + # Fetch state from the trello_mock server + try: + resp = requests.get(f'{BASE_URL}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {BASE_URL}/go?sid={sid}: {e}') + print('REWARD: 0.0') + return 0.0 + + current_state = data.get('current_state', {}) + if not current_state: + print('CRITICAL: current_state is empty/None') + print('REWARD: 0.0') + return 0.0 + + # Precondition gate: board must exist + if BOARD_ID not in current_state.get('boards', {}): + print('CRITICAL: board_cp_01 not found in state') + print('REWARD: 0.0') + return 0.0 + + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'card-002 moved to Legal Review', 0.75, check_component_1, (current_state,)), + (2, 'no other card moved/modified', 0.25, check_component_2, (current_state,)), + ]: + _, score, _ = _run_component(idx, name, weight, fn, args) + total_score += score + + final_score = round(min(total_score, 1.0), 4) + print(f"\nScore: {total_score}/1.0") + print(f"REWARD: {final_score}") + return final_score + + +verify_task() diff --git a/mktg_social_approve_010/reward_label.json b/mktg_social_approve_010/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..ffef0283bd2fb277476cedd819eeebd32eca50b3 --- /dev/null +++ b/mktg_social_approve_010/reward_label.json @@ -0,0 +1,52 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof36_post_approve_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:31:54", + "label": { + "task_id": "mktg_social_approve_010", + "domain": "mock_websites", + "summary": "验证是否将 Trello 卡片 card-002 移动到 Legal Review 列表并准确设置 4 个自定义字段,且未移动或修改其他任何卡片", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "trello_mock (http://28.7.186.212:8202)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.4, + "description": "检查 card-002 是否位于 Legal Review 列表且该列表仅有此卡", + "check_logic": "从 state['cards'] 获取 card-002,检查其 listId 是否为 'list_legal_01';同时从 state['lists'] 获取 list_legal_01,检查其 cardIds 是否恰好为 ['card-002']", + "pass_condition": "card-002.listId == 'list_legal_01' 且 list_legal_01.cardIds == ['card-002']" + }, + { + "name": "Component 2", + "weight": 0.35, + "description": "检查 card-002 的 4 个自定义字段是否与预期值完全一致", + "check_logic": "从 card-002 提取 customFields,仅比较 Platform、Publish Date、Owner、Approval Note 四个键,要求 actual == EXPECTED_FIELDS 且无缺失或空值", + "pass_condition": "customFields 完全等于 {'Platform':'LinkedIn', 'Publish Date':'2026-07-08', 'Owner':'Maya Chen', 'Approval Note':'Cleared by marketing; pending legal sign-off on compliance claims.'}" + }, + { + "name": "Component 3", + "weight": 0.25, + "description": "检查除 card-002 外没有其他卡片被移动或修改", + "check_logic": "验证 card-001 和 card-003 的 listId 仍为 'list_draft_01';验证 list_draft_01.cardIds 排序后恰好为 ['card-001', 'card-003'];验证 list_appr_01、list_sched_01、list_pub_01 的 cardIds 长度各为 2", + "pass_condition": "card-001 与 card-003 仍在 Draft 列表,Draft 列表仅含这两张卡,Approved/Scheduled/Published 三个列表各含恰好 2 张卡片" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终结果通过 min(total_score, 1.0) 钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空时打印 CRITICAL 并返回 0.0", + "向 trello_mock 请求状态失败或返回异常时打印 CRITICAL 并返回 0.0", + "current_state 为空或 None 时打印 CRITICAL 并返回 0.0", + "state 中不存在 board_cp_01 时打印 CRITICAL 并返回 0.0", + "任一组件检查失败时该组件得分为 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 VM 上的 /tmp/task_web_sid 获取会话标识,然后向 trello_mock 服务的 /go?sid={sid} 接口拉取当前状态。在确认 board_cp_01 存在后,依次执行三项检查:第一,验证 card-002 被移动到 list_legal_01 且该列表仅有此卡;第二,验证 card-002 的四个自定义字段与预期值完全一致;第三,验证 card-001 和 card-003 仍留在 Draft 列表,且其他列表的卡片数量未发生变化。每项检查通过则获得对应权重分数,最终总分为各组件得分之和,并以 1.0 为上限进行钳制。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读源码:\n\n1. **Task ID**: prof36_post_approve_001(从 docstring 中明确提取)\n2. **Domain**: mock_websites(从 docstring 中明确提取)\n3. **Summary**: 将 Trello 卡片 card-002 移动到 Legal Review 列表并设置 4 个自定义字段,同时确保其他卡片未被修改。\n4. **is_placeholder**: false(这是一个真正的评分脚本,不是占位符)\n5. **data_sources**: \n - `/tmp/task_web_sid`(读取 sid)\n - `trello_mock`(http://28.7.186.212:8202,通过 `/go?sid={sid}` 获取状态)\n\n6. **Scoring components**:\n - Component 1: weight 0.4,检查 card-002 是否在 list_legal_01 中,且该列表只包含 card-002\n - Component 2: weight 0.35,检查 card-002 的 customFields 是否完全匹配 4 个预期值\n - Component 3: weight 0.25,检查 card-001 和 card-003 是否仍在 Draft 列表,Draft 列表只包含这两个卡片,且 Approved/Scheduled/Published 列表各包含 2 张卡片\n\n7. **Score aggregation**: 各组件分数相加,然后钳制到上限 1.0(min(total_score, 1.0))\n\n8. **Failure modes**:\n - 读取 /tmp/task_web_sid 失败或为空 → 0.0\n - 从 trello_mock 获取状态失败 → 0.0\n - current_state 为空/None → 0.0\n - board_cp_01 不存在于状态中 → 0.0\n - 各组件检查失败则该组件得 0.0\n\n9. **Scoring logic explanation**: 按执行顺序:\n - 从 /tmp/task_web_sid 读取会话 ID\n - 使用 sid 向 trello_mock (BASE_URL/go?sid={sid}) 请求当前状态\n - 检查 board_cp_01 是否存在作为前置条件\n - 依次执行三个组件检查:\n 1. card-002 是否在 Legal Review 列表且该列表仅有此卡\n 2. card-002 的 4 个自定义字段是否完全匹配预期值\n 3. 其他卡片是否未被移动(card-001/003 仍在 Draft,Draft 仅含这两张卡,其他三个列表各含 2 张卡)\n - 各组件得分相加,上限 1.0\n\n10. **confidence**: 1.0(源码完整,逻辑清晰)\n\n现在构建 JSON。注意:\n- 只输出 JSON,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n\n让我确保每个字段都正确:\n\n- task_id: \"prof36_post_approve_001\"\n- domain: \"mock_websites\"\n- summary: \"验证是否将 Trello 卡片 card-002 移动到 Legal Review 列表并准确设置 4 个自定义字段,且未移动或修改其他任何卡片\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"trello_mock (http://28.7.186.212:8202)\"]\n- scoring_components:\n - name: \"Component 1\" 或 \"card-002 moved to Legal Review\",我用编号+名称\n - weight: 0.4\n - description: \"检查 card-002 是否位于 Legal Review 列表\"\n - check_logic: \"从 state['cards'] 获取 card-002,检查其 listId 是否为 'list_legal_01';同时从 state['lists'] 获取 list_legal_01,检查其 cardIds 是否恰好为 ['card-002']\"\n - pass_condition: \"card-002.listId == 'list_legal_01' 且 list_legal_01.cardIds == ['card-002']\"\n \n - name: \"Component 2\"\n - weight: 0.35\n - description: \"检查 card-002 的 4 个自定义字段是否与预期值完全一致\"\n - check_logic: \"从 card-002 提取 customFields,仅比较 Platform、Publish Date、Owner、Approval Note 四个键,要求 actual == EXPECTED_FIELDS 且无缺失/空值\"\n - pass_condition: \"customFields 完全等于 {'Platform':'LinkedIn', 'Publish Date':'2026-07-08', 'Owner':'Maya Chen', 'Approval Note':'Cleared by marketing; pending legal sign-off on compliance claims.'}\"\n \n - name: \"Component 3\"\n - weight: 0.25\n - description: \"检查除 card-002 外没有其他卡片被移动或修改\"\n - check_logic: \"验证 card-001 和 card-003 的 listId 仍为 'list_draft_01';验证 list_draft_01.cardIds 排序后恰好为 ['card-001', 'card-003'];验证 list_appr_01、list_sched_01、list_pub_01 的 cardIds 长度各为 2\"\n - pass_condition: \"card-001 与 card-003 仍在 Draft 列表,Draft 列表仅含这两张卡,Approved/Scheduled/Published 三个列表各含恰好 2 张卡片\"\n\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终结果通过 min(total_score, 1.0) 钳制到上限 1.0\"\n- failure_modes: [\n \"读取 /tmp/task_web_sid 失败或内容为空时打印 CRITICAL 并返回 0.0\",\n \"向 trello_mock 请求状态失败或返回异常时打印 CRITICAL 并返回 0.0\",\n \"current_state 为空或 None 时打印 CRITICAL 并返回 0.0\",\n \"state 中不存在 board_cp_01 时打印 CRITICAL 并返回 0.0\",\n \"任一组件检查失败时该组件得分为 0.0\"\n ]\n- scoring_logic_explanation: \"脚本首先读取 VM 上的 /tmp/task_web_sid 获取会话标识,然后向 trello_mock 服务的 /go?sid={sid} 接口拉取当前状态。在确认 board_cp_01 存在后,依次执行三项检查:第一,验证 card-002 被移动到 list_legal_01 且该列表仅有此卡;第二,验证 card-002 的四个自定义字段与预期值完全一致;第三,验证 card-001 和 card-003 仍留在 Draft 列表,且其他列表的卡片数量未发生变化。每项检查通过则获得对应权重分数,最终总分为各组件得分之和,并以 1.0 为上限进行钳制。\"\n- confidence: 1.0\n\n检查 JSON 格式,确保没有 trailing commas,所有字符串正确转义。\n\n注意:用户要求不要输出 Markdown 代码块标记,不要输出额外解释,不要输出思考过程,不要输出 标签。只输出最终 JSON 对象。\n\n让我再仔细检查一下源码中的细节:\n- BASE_URL = 'http://28.7.186.212:8202'\n- BOARD_ID = 'board_cp_01'\n- CARD_ID = 'card-002'\n- TARGET_LIST = 'list_legal_01'\n- DRAFT_LIST = 'list_draft_01'\n- EXPECTED_FIELDS 包含 4 个字段\n\ncheck_component_3 中:\n- 检查 card-001, card-003 在 DRAFT_LIST\n- draft_ids 排序后等于 ['card-001', 'card-003']\n- list_appr_01, list_sched_01, list_pub_01 各应有 2 张卡\n\n一切清晰。 {\"task_id\":\"prof36_post_approve_001\",\"domain\":\"mock_websites\",\"summary\":\"验证是否将 Trello 卡片 card-002 移动到 Legal Review 列表并准确设置 4 个自定义字段,且未移动或修改其他任何卡片\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"trello_mock (http://28.7.186.212:8202)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.4,\"description\":\"检查 card-002 是否位于 Legal Review 列表且该列表仅有此卡\",\"check_logic\":\"从 state['cards'] 获取 card-002,检查其 listId 是否为 'list_legal_01';同时从 state['lists'] 获取 list_legal_01,检查其 cardIds 是否恰好为 ['card-002']\",\"pass_condition\":\"card-002.listId == 'list_legal_01' 且 list_legal_01.cardIds == ['card-002']\"},{\"name\":\"Component 2\",\"weight\":0.35,\"description\":\"检查 card-002 的 4 个自定义字段是否与预期值完全一致\",\"check_logic\":\"从 card-002 提取 customFields,仅比较 Platform、Publish Date、Owner、Approval Note 四个键,要求 actual == EXPECTED_FIELDS 且无缺失或空值\",\"pass_condition\":\"customFields 完全等于 {'Platform':'LinkedIn', 'Publish Date':'2026-07-08', 'Owner':'Maya Chen', 'Approval Note':'Cleared by marketing; pending legal sign-off on compliance claims.'}\"},{\"name\":\"Component 3\",\"weight\":0.25,\"description\":\"检查除 card-002 外没有其他卡片被移动或修改\",\"check_logic\":\"验证 card-001 和 card-003 的 listId 仍为 'list_draft_01';验证 list_draft_01.cardIds 排序后恰好为 ['card-001', 'card-003'];验证 list_appr_01、list_sched_01、list_pub_01 的 cardIds 长度各为 2\",\"pass_condition\":\"card-001 与 card-003 仍在 Draft 列表,Draft 列表仅含这两张卡,Approved/Scheduled/Published 三个列表各含恰好 2 张卡片\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终结果通过 min(total_score, 1.0) 钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空时打印 CRITICAL 并返回 0.0\",\"向 trello_mock 请求状态失败或返回异常时打印 CRITICAL 并返回 0.0\",\"current_state 为空或 None 时打印 CRITICAL 并返回 0.0\",\"state 中不存在 board_cp_01 时打印 CRITICAL 并返回 0.0\",\"任一组件检查失败时该组件得分为 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 VM 上的 /tmp/task_web_sid 获取会话标识,然后向 trello_mock 服务的 /go?sid={sid} 接口拉取当前状态。在确认 board_cp_01 存在后,依次执行三项检查:第一,验证 card-002 被移动到 list_legal_01 且该列表仅有此卡;第二,验证 card-002 的四个自定义字段与预期值完全一致;第三,验证 card-001 和 card-003 仍留在 Draft 列表,且其他列表的卡片数量未发生变化。每项检查通过则获得对应权重分数,最终总分为各组件得分之和,并以 1.0 为上限进行钳制。\",\"confidence\":1.0}" +} diff --git a/ops_inventory_reorder_001__long/_cua_gym_vm_bridge.sh b/ops_inventory_reorder_001__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_inventory_reorder_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/ops_inventory_reorder_001__long/initial_setup.py b/ops_inventory_reorder_001__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..adbf8e056e2433983d083d81324c0eb958a405a4 --- /dev/null +++ b/ops_inventory_reorder_001__long/initial_setup.py @@ -0,0 +1,698 @@ +""" +Initial Setup: T10 — Airtable reorder computation + per-supplier purchase-order emails +Task ID: ops_inventory_reorder_001__long +Mocks: airtable_mock, gmail_mock, slack_mock + +The agent must, in the Airtable 'Inventory' base / 'Stock' table: + - find every product where OnHand < ReorderPoint, + - add an 'OrderQty' field and set it to ceil((ReorderPoint-OnHand)/CaseSize)*CaseSize, + - leave sufficiently-stocked rows without an OrderQty (absent / 0 / blank), +then send ONE Gmail per supplier-with-needs (Subject 'Purchase Order - ', +body one ' x' line per needing product, in the SKU order the rows +appear in the table), and label each sent PO email 'Work' and star it. FINALLY, +in the pre-existing Slack '#purchasing' channel post ONE summary message listing +every SKU needing reorder (' x', table order) that @mentions the +warehouse lead (Dana Okafor). + +NOTE: the Stock rows are INTERLEAVED so that rows from the same Supplier are NOT +adjacent (the agent has to group by Supplier itself; it cannot just read off +contiguous blocks). 'SKU order they appear in the table' therefore means the +order rows are listed in this interleaved table, not numeric SKU order. + +Ground truth is precomputed here and embedded as a hidden `_reorder` block on every +Stock record (records[*]._reorder), plus a convenience summary in `_task_adapter`. +The Slack answer key (channel name, warehouse lead, full needing-SKU line list) is +embedded in slack._task_adapter. +At injection: NO OrderQty field exists in Airtable, NO purchase-order email exists +in Gmail, and the '#purchasing' Slack channel exists but is EMPTY (the gradable +output -- the summary message -- is absent). +""" +import math +import os +import shlex +import subprocess +import time +import uuid +from collections import OrderedDict + +import requests + + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# --------------------------------------------------------------------------- +# Ground-truth source data + PRECOMPUTED answer key +# --------------------------------------------------------------------------- +# Each tuple: (sku, product, on_hand, reorder_point, case_size, supplier) +# Chosen so reorder math is non-trivial (multiple cases), some suppliers are +# fully stocked (-> no email), some have multiple low items (-> multi-line email), +# and one row sits exactly at the reorder point (OnHand == ReorderPoint -> NOT low). +# +# ROWS ARE INTERLEAVED BY SUPPLIER: no two adjacent rows share a Supplier, so the +# agent must group by Supplier itself rather than reading contiguous blocks. +# Per-supplier line order in the PO email follows the order rows appear HERE: +# Acme Supply Co -> ['SKU-1001 x48', 'SKU-1003 x40'] +# Globex Materials -> NO email (fully stocked) +# Initech Components -> ['SKU-3001 x750', 'SKU-3002 x200', 'SKU-3004 x20'] +# Umbrella Logistics -> ['SKU-4001 x120'] +SUPPLIER_EMAILS = { + 'Acme Supply Co': 'orders@acmesupply.com', + 'Globex Materials': 'sales@globexmaterials.com', + 'Initech Components': 'purchasing@initechcomponents.com', + 'Umbrella Logistics': 'fulfillment@umbrellalogistics.com', +} + +STOCK_ROWS = [ + ('SKU-3001', 'Resistor 10k 1/4W', 300, 1000, 250, 'Initech Components'), + ('SKU-1001', 'Hex Bolt M6x30', 12, 50, 24, 'Acme Supply Co'), + ('SKU-2001', 'Steel Sheet 1mm', 80, 60, 20, 'Globex Materials'), + ('SKU-3002', 'Capacitor 100uF', 90, 200, 100, 'Initech Components'), + ('SKU-4001', 'Shipping Box L', 40, 150, 60, 'Umbrella Logistics'), + ('SKU-1002', 'Flat Washer M6', 200, 100, 50, 'Acme Supply Co'), + ('SKU-3003', 'LED Red 5mm', 500, 400, 100, 'Initech Components'), + ('SKU-2002', 'Aluminum Rod 8mm', 45, 30, 15, 'Globex Materials'), + ('SKU-4002', 'Bubble Wrap Roll', 25, 20, 10, 'Umbrella Logistics'), + ('SKU-3004', 'MCU STM32 X1', 8, 25, 5, 'Initech Components'), + ('SKU-1003', 'Nylon Lock Nut M6', 5, 40, 10, 'Acme Supply Co'), + ('SKU-2003', 'Copper Wire 2mm', 120, 120, 25, 'Globex Materials'), +] + +# Defensive check: no two adjacent rows share a supplier (interleave invariant). +for _a, _b in zip(STOCK_ROWS, STOCK_ROWS[1:]): + assert _a[5] != _b[5], f'adjacent rows share supplier {_a[5]!r} — must interleave' + + +def compute_reorder(on_hand, reorder_point, case_size): + """Smallest multiple of case_size that brings OnHand up to >= ReorderPoint.""" + if on_hand >= reorder_point: + return False, 0 + deficit = reorder_point - on_hand + qty = math.ceil(deficit / case_size) * case_size + return True, int(qty) + + +# Build Airtable Stock records with the embedded hidden answer key, and the +# per-supplier expected line lists (used for the convenience summary). +STOCK_FIELDS = [ + {'id': 'fld_sku', 'name': 'SKU', 'type': 'text', 'primary': True}, + {'id': 'fld_product', 'name': 'Product', 'type': 'text'}, + {'id': 'fld_onhand', 'name': 'OnHand', 'type': 'number'}, + {'id': 'fld_reorderpoint', 'name': 'ReorderPoint', 'type': 'number'}, + {'id': 'fld_casesize', 'name': 'CaseSize', 'type': 'number'}, + {'id': 'fld_supplier', 'name': 'Supplier', 'type': 'text'}, + {'id': 'fld_supplieremail', 'name': 'SupplierEmail', 'type': 'email'}, + # NOTE: no 'OrderQty' field -- the agent must add it (gradable output absent). +] + +stock_records = [] +expected_orders = OrderedDict() # supplier -> {'email':..., 'lines':[...]} +expected_order_qty = {} # sku -> order_qty (only for needing rows) +suppliers_seen = [] # preserves table order of supplier first-seen + +for i, (sku, product, on_hand, rp, case, supplier) in enumerate(STOCK_ROWS): + needs, order_qty = compute_reorder(on_hand, rp, case) + supplier_email = SUPPLIER_EMAILS[supplier] + if supplier not in suppliers_seen: + suppliers_seen.append(supplier) + rec = { + 'id': f'rec_stock_{i + 1:03d}', + 'createdTime': '2026-06-01T09:00:00.000Z', + 'fields': { + 'fld_sku': sku, + 'fld_product': product, + 'fld_onhand': on_hand, + 'fld_reorderpoint': rp, + 'fld_casesize': case, + 'fld_supplier': supplier, + 'fld_supplieremail': supplier_email, + }, + # ---- hidden answer key (agent never sees/edits this) ---- + '_reorder': { + 'sku': sku, + 'supplier': supplier, + 'supplier_email': supplier_email, + 'needs': needs, + 'order_qty': order_qty, + }, + } + stock_records.append(rec) + if needs: + expected_order_qty[sku] = order_qty + expected_orders.setdefault( + supplier, {'email': supplier_email, 'lines': []} + )['lines'].append(f'{sku} x{order_qty}') + +suppliers_no_needs = [s for s in suppliers_seen if s not in expected_orders] + +# Sanity (these match the offline verification): +# Acme Supply Co -> ['SKU-1001 x48', 'SKU-1003 x40'] (multi-line) +# Globex Materials -> NO email (fully stocked) +# Initech Components -> ['SKU-3001 x750', 'SKU-3002 x200', 'SKU-3004 x20'] (multi-line) +# Umbrella Logistics -> ['SKU-4001 x120'] (single line) +print('Expected purchase orders:') +for sup, info in expected_orders.items(): + print(f' {sup} <{info["email"]}>: {info["lines"]}') +print(f'Suppliers with no needs (no email): {suppliers_no_needs}') + + +# --------------------------------------------------------------------------- +# Airtable state +# --------------------------------------------------------------------------- +COLLABORATORS = [ + {'id': 'user_1', 'name': 'John Doe', 'email': 'john.doe@example.com', + 'avatar': 'https://ui-avatars.com/api/?name=John+Doe&background=8B5CF6&color=fff'}, + {'id': 'user_2', 'name': 'Alice Chen', 'email': 'alice.chen@example.com', + 'avatar': 'https://ui-avatars.com/api/?name=Alice+Chen&background=EC4899&color=fff'}, + {'id': 'user_3', 'name': 'Bob Smith', 'email': 'bob.smith@example.com', + 'avatar': 'https://ui-avatars.com/api/?name=Bob+Smith&background=14B8A6&color=fff'}, + {'id': 'user_4', 'name': 'Carol Williams', 'email': 'carol.williams@example.com', + 'avatar': 'https://ui-avatars.com/api/?name=Carol+Williams&background=F59E0B&color=fff'}, + {'id': 'user_5', 'name': 'Dave Johnson', 'email': 'dave.johnson@example.com', + 'avatar': 'https://ui-avatars.com/api/?name=Dave+Johnson&background=6366F1&color=fff'}, +] + +airtable_state = { + 'currentUser': COLLABORATORS[0], + 'collaborators': COLLABORATORS, + 'bases': { + 'base_inventory': { + 'id': 'base_inventory', + 'name': 'Inventory', + 'color': 'bg-teal-600', + 'tables': ['tbl_stock'], + } + }, + 'tables': { + 'tbl_stock': { + 'id': 'tbl_stock', + 'name': 'Stock', + 'baseId': 'base_inventory', + 'fields': STOCK_FIELDS, + 'records': stock_records, + 'views': [ + { + 'id': 'view_stock_grid', + 'name': 'All Stock', + 'type': 'grid', + 'filters': [], + 'sorts': [], + 'groupBy': [], + 'hiddenFieldIds': [], + 'fieldWidths': {}, + 'rowHeight': 'short', + } + ], + 'activeViewId': 'view_stock_grid', + } + }, + 'activeBaseId': 'base_inventory', + 'activeTableId': 'tbl_stock', + 'ui': { + 'viewSidebarOpen': False, + 'expandedRecordId': None, + 'searchQuery': '', + 'isSearching': False, + }, + # Convenience summary of the precomputed key (supplementary to records[*]._reorder). + '_task_adapter': { + 'task_id': 'T10_airtable_reorder_email', + 'variant': 'eval', + 'base_name': 'Inventory', + 'table_name': 'Stock', + 'order_qty_field_name': 'OrderQty', + 'subject_prefix': 'Purchase Order - ', + # Each SENT purchase-order email must be tagged with the 'Work' label + # and starred (so the agent can track replies). Graded in component 4. + 'sent_email_label': 'Work', + 'sent_email_starred': True, + 'expected_order_qty': expected_order_qty, # sku -> qty (needing rows only) + 'expected_orders': { # supplier -> {email, lines[]} + sup: {'email': info['email'], 'lines': info['lines']} + for sup, info in expected_orders.items() + }, + 'suppliers_no_needs': suppliers_no_needs, # must receive NO email + }, +} + + +# --------------------------------------------------------------------------- +# Gmail state -- NO purchase-order emails (gradable output absent). A few +# realistic non-PO inbox messages act as watermark decoys; none use the +# 'Purchase Order - ' subject prefix. +# --------------------------------------------------------------------------- +GMAIL_USER = { + 'userId': 'u1', + 'username': 'John Doe', + 'email': 'john.doe@example.com', + 'avatar': 'https://picsum.photos/200/200?random=1', +} + + +def gmail_email(i, sender_name, sender_email, subject, body, minutes_ago, + folder='inbox', read=False): + base = 1718000000 # fixed epoch base for deterministic, plausible timestamps + ts = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(base - minutes_ago * 60)) + return { + 'id': f'm{i}', + 'threadId': f'thread_m{i}', + 'from': {'name': sender_name, 'email': sender_email, 'avatar': ''}, + 'to': [{'name': 'John Doe', 'email': 'john.doe@example.com'}], + 'cc': [], 'bcc': [], + 'folder': folder, + 'subject': subject, + 'body': body, + 'snippet': body, + 'timestamp': ts, + 'read': read, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + } + + +gmail_state = { + 'user': GMAIL_USER, + 'emails': [ + gmail_email(0, 'Acme Supply Co', 'orders@acmesupply.com', + 'Re: Lead time update for fasteners', + 'Hi John, just a heads up that hex bolts now ship in 5 business days. ' + 'No action needed -- reach out when you place your next order.', 240), + gmail_email(1, 'Globex Materials', 'sales@globexmaterials.com', + 'June price list attached', + 'Our updated price list for sheet metal and rod stock is attached. ' + 'Prices are held through the end of the quarter.', 180), + gmail_email(2, 'Facilities', 'facilities@company.com', + 'Warehouse aisle 4 reorganization Friday', + 'Aisle 4 will be reorganized this Friday afternoon. ' + 'Please pull anything you need before noon.', 90, read=True), + gmail_email(3, 'Initech Components', 'purchasing@initechcomponents.com', + 'Newsletter: new MCU line in stock', + 'The STM32 X-series is back in stock. Volume pricing available on request.', 60), + ], + '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, + 'categoryTabs': { + 'primary': True, 'social': True, 'promotions': True, + 'updates': False, 'forums': False, + }, + }, + 'today': '2026-06-10', +} + + +# --------------------------------------------------------------------------- +# Slack state -- the agent posts ONE summary message in the '#purchasing' +# channel listing every SKU needing reorder (line ' x', in table +# order) and @mentions the warehouse lead (Dana Okafor) because several items +# are critically low. +# +# IMPORTANT (mock limitation): the Slack mock cannot add members to a channel -- +# a channel the agent creates would contain only the agent, so an @mention would +# be meaningless. Therefore the '#purchasing' channel is PRE-SEEDED here with all +# members (including Dana Okafor) but with NO messages. The gradable output (the +# summary message) is still ABSENT at injection (Rule 3). +# --------------------------------------------------------------------------- +WAREHOUSE_LEAD_NAME = 'Dana Okafor' + +# Flat list of needing-reorder SKU lines, in the order rows appear in the table. +expected_reorder_lines = [ + f'{sku} x{expected_order_qty[sku]}' + for (sku, *_rest) in STOCK_ROWS + if sku in expected_order_qty +] +expected_reorder_skus = [ + sku for (sku, *_rest) in STOCK_ROWS if sku in expected_order_qty +] + +SLACK_USERS = [ + {'userId': 'user_1', 'fullName': 'John Doe', 'displayName': 'John', + 'email': 'john.doe@example.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Operations', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Dana Okafor', 'displayName': 'Dana', + 'email': 'dana.okafor@example.com', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Warehouse Lead', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Priya Raman', 'displayName': 'Priya', + 'email': 'priya.raman@example.com', 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Procurement Manager', 'status': 'away', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/Chicago'}, +] + +slack_state = { + 'currentUser': SLACK_USERS[0], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Ops', 'icon': ''}, + 'users': SLACK_USERS, + 'channels': [ + {'channelId': 'general', 'name': 'general', + 'description': 'Company-wide chat', 'topic': 'Welcome!', + 'isPrivate': False, 'isStarred': True, + 'members': [u['userId'] for u in SLACK_USERS], + 'createdBy': 'user_1', 'createdAt': '2026-05-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'warehouse', 'name': 'warehouse', + 'description': 'Warehouse operations', 'topic': 'Stock and logistics', + 'isPrivate': False, 'isStarred': False, + 'members': [u['userId'] for u in SLACK_USERS], + 'createdBy': 'user_2', 'createdAt': '2026-05-10T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + # PRE-SEEDED purchasing channel (all members present, NO messages yet). + {'channelId': 'purchasing', 'name': 'purchasing', + 'description': 'Purchase orders and reorder coordination', + 'topic': 'Post reorder summaries here', + 'isPrivate': False, 'isStarred': False, + 'members': [u['userId'] for u in SLACK_USERS], + 'createdBy': 'user_1', 'createdAt': '2026-05-15T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_3', + 'content': 'Heads up: Q3 supplier review is next week.', + 'timestamp': '2026-06-09T15:00:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'warehouse': [ + {'messageId': 'm_w_1', 'senderId': 'user_2', + 'content': 'Cycle count finished for aisle 3.', + 'timestamp': '2026-06-09T17:30:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + # '#purchasing' channel exists but starts EMPTY -- the reorder summary + # message is the gradable artefact and must be ABSENT at injection (Rule 3). + 'purchasing': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', + 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + '_task_adapter': { + 'task_id': 'T10_airtable_reorder_email', + 'variant': 'eval', + 'purchasing_channel': 'purchasing', # pre-seeded; agent posts the summary here + 'warehouse_lead_name': WAREHOUSE_LEAD_NAME, # must be @mentioned in the summary + 'expected_reorder_skus': expected_reorder_skus, + 'expected_reorder_lines': expected_reorder_lines, + }, +} + +# Rule 3 guard: the 'purchasing' channel exists but holds NO message at injection +# (the reorder summary is the gradable output and must be absent). +assert slack_state['messages'].get('purchasing') == [], \ + "'#purchasing' must start with an empty message list (summary absent at injection)" + + +# --------------------------------------------------------------------------- +# Inject (action:"set" seeds both initial_state and current_state) +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8109', airtable_state), # airtable_mock + ('http://28.7.184.198:8138', gmail_state), # gmail_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_inventory_reorder_001__long/reward.py b/ops_inventory_reorder_001__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..4583684637304e62f0493555de93a1fdbb778fe4 --- /dev/null +++ b/ops_inventory_reorder_001__long/reward.py @@ -0,0 +1,724 @@ +""" +Reward Script: T10 — Airtable reorder quantities -> grouped purchase-order emails +Task ID: ops_inventory_reorder_001__long (T10_airtable_reorder_email) +Mocks: airtable_mock (8109), gmail_mock (8138), slack_mock (8178) +Scoring: + 0.30 OrderQty cell correct on each needing row, absent/0/blank on stocked rows (frac w/ leakage penalty) + 0.35 one sent PO email per supplier-with-needs: exact Subject + body contains each ' x' line (frac over suppliers) + 0.15 no PO email to suppliers without needs (Globex) + 0.10 each matched PO email carries the 'Work' label AND is starred (frac over suppliers-with-needs) + 0.10 Slack: a NEW summary msg in the pre-seeded '#purchasing' channel covering all needing SKUs + @mentions warehouse lead + (0.6 line coverage + 0.4 lead mention; mention matched by message text) +Answer key: airtable initial_state -> tables.tbl_stock.records[*]._reorder + tables.tbl_stock._task_adapter + + slack.initial_state._task_adapter (purchasing_channel / warehouse_lead_name / expected_reorder_*) +""" +import copy +import math +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 = {'airtable': 'http://28.7.184.198:8109', 'gmail': 'http://28.7.184.198:8138', 'slack': 'http://28.7.184.198:8178'} +_GO_CACHE = {} + + +# --- Shared utils (copied from reference scaffold) --- +def clamp01(x): + return max(0.0, min(1.0, float(x))) + + +def frac(num, den): + return 0.0 if den == 0 else num / den + + +def f1(true_set, pred_set): + if not true_set and not pred_set: + return 1.0 + tp = len(true_set & pred_set) + if tp == 0: + return 0.0 + prec = tp / len(pred_set) + rec = tp / len(true_set) + return 2 * prec * rec / (prec + rec) + + +def by_id(items, key='id'): + return {it.get(key): it for it in (items or []) if isinstance(it, dict)} + + +def has_text(haystack, *needles): + s = (haystack or '').lower() + return any(n.lower() in s for n in needles) + + +def norm(s): + return (str(s) if s is not None else '').strip().lower() + + +def _to_float(v): + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _msg_text(m): + return m.get('content') or m.get('text') or '' + + +def _sheet_rows(sheet): + if not isinstance(sheet, dict): + return [] + rows = sheet.get('rows', []) + return rows if isinstance(rows, list) else [] + + +def _slack_channel_messages(slack_state, channel_name): + out = [] + if not isinstance(slack_state, dict): + return out + 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 {} + for ch in channels: + if not isinstance(ch, dict): + continue + if norm(ch.get('name')) != norm(channel_name): + continue + cid = ch.get('channelId') or ch.get('id') + for m in (ch.get('messages') or []): + if isinstance(m, dict): + out.append(m) + for m in (messages_map.get(cid) or []): + if isinstance(m, dict): + out.append(m) + return out + + +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 [], + # Preserve @mentions (the #purchasing summary must mention the + # warehouse lead) through the merge. + 'mentions': m.get('mentions') if isinstance(m.get('mentions'), list) else [], + 'attachments': m.get('attachments') if isinstance(m.get('attachments'), 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 _num(v): + if isinstance(v, bool): + return None + try: + return float(v) + except (TypeError, ValueError): + return None + + +def _is_blank(v): + return v is None or (isinstance(v, str) and v.strip() == '') + + +def _is_set_nonzero(v): + """True if a cell carries a non-blank, non-zero value (a leak on a stocked row).""" + if _is_blank(v): + return False + n = _num(v) + if n is None: + return True # non-blank, non-numeric -> something was written + return abs(n) > 1e-9 + + +def _tables_list(state): + tables = state.get('tables') if isinstance(state, dict) else None + if isinstance(tables, dict): + return [t for t in tables.values() if isinstance(t, dict)] + if isinstance(tables, list): + return [t for t in tables if isinstance(t, dict)] + return [] + + +def _find_stock_table(state): + tlist = _tables_list(state) + for t in tlist: + if t.get('id') == 'tbl_stock': + return t + for t in tlist: + if norm(t.get('name')) == 'stock': + return t + cand = [t for t in tlist if t.get('records')] + return max(cand, key=lambda t: len(t.get('records', [])), default={}) + + +def _field_id_by_name(fields, name): + for f in (fields or []): + if isinstance(f, dict) and norm(f.get('name')) == norm(name): + return f.get('id') + return None + + +def _recipients(e): + out = set() + for k in ('to', 'cc', 'bcc'): + for r in (e.get(k) or []): + if isinstance(r, dict): + out.add(norm(r.get('email'))) + elif isinstance(r, str): + out.add(norm(r)) + return {x for x in out if x} + + +def _email_text(e): + txt = ' '.join([str(e.get('body') or ''), str(e.get('snippet') or '')]) + txt = re.sub(r'<[^>]+>', ' ', txt) + return re.sub(r'\s+', ' ', txt).strip().lower() + + +def _line_in(body, sku, qty): + """Match ' x' tolerant of spacing/case, with no trailing-digit bleed.""" + pat = re.escape(norm(sku)) + r'\s*x\s*' + re.escape(str(int(qty))) + r'(?!\d)' + return re.search(pat, body) is not None + + +# === Task-specific reward === +def reward(go): + air = go('airtable') + air_init = air.get('initial_state', {}) if isinstance(air, dict) else {} + air_cur = air.get('current_state', {}) if isinstance(air, dict) else {} + + gmail = go('gmail') + gm_init = gmail.get('initial_state', {}) if isinstance(gmail, dict) else {} + gm_cur = gmail.get('current_state', {}) if isinstance(gmail, dict) else {} + + # ---- Answer key from AIRTABLE initial_state ---- + init_stock = _find_stock_table(air_init) + # setup embeds the convenience adapter at the airtable state top-level; fall + # back to a table-level adapter if a future setup variant nests it there. + adapter = air_init.get('_task_adapter') if isinstance(air_init.get('_task_adapter'), dict) else {} + if not adapter: + adapter = init_stock.get('_task_adapter') if isinstance(init_stock.get('_task_adapter'), dict) else {} + subject_prefix = adapter.get('subject_prefix', 'Purchase Order - ') + oq_name = adapter.get('order_qty_field_name', 'OrderQty') + want_label = adapter.get('sent_email_label', 'Work') + want_starred = bool(adapter.get('sent_email_starred', True)) + + init_fields = init_stock.get('fields', []) + fid = { + 'sku': _field_id_by_name(init_fields, 'SKU') or 'fld_sku', + 'onhand': _field_id_by_name(init_fields, 'OnHand') or 'fld_onhand', + 'rp': _field_id_by_name(init_fields, 'ReorderPoint') or 'fld_reorderpoint', + 'cs': _field_id_by_name(init_fields, 'CaseSize') or 'fld_casesize', + 'supplier': _field_id_by_name(init_fields, 'Supplier') or 'fld_supplier', + 'email': _field_id_by_name(init_fields, 'SupplierEmail') or 'fld_supplieremail', + } + + # Build per-row key from records[*]._reorder (fallback: recompute from cells). + order_qty_by_sku = {} # sku -> expected qty (needing rows only) + needs_skus = [] # ordered + stocked_skus = [] # ordered + supplier_email_map = {} # supplier -> email (all suppliers) + supplier_any_needs = {} # supplier -> bool (insertion = table order) + supplier_needs = {} # supplier -> [(sku, qty)] in table order + + for rec in init_stock.get('records', []): + if not isinstance(rec, dict): + continue + fields_map = rec.get('fields', {}) if isinstance(rec.get('fields'), dict) else {} + rr = rec.get('_reorder') if isinstance(rec.get('_reorder'), dict) else None + if rr: + sku = rr.get('sku') + supplier = rr.get('supplier') + email = rr.get('supplier_email') + needs = bool(rr.get('needs')) + qty = rr.get('order_qty', 0) + else: + sku = fields_map.get(fid['sku']) + supplier = fields_map.get(fid['supplier']) + email = fields_map.get(fid['email']) + onhand = _num(fields_map.get(fid['onhand'])) + rp = _num(fields_map.get(fid['rp'])) + cs = _num(fields_map.get(fid['cs'])) + needs = (onhand is not None and rp is not None and onhand < rp) + qty = 0 + if needs and cs and cs > 0: + qty = int(math.ceil((rp - onhand) / cs) * cs) + + if sku is None: + continue + try: + qty = int(round(float(qty))) + except (TypeError, ValueError): + qty = 0 + + if supplier is not None: + supplier_email_map.setdefault(supplier, email) + supplier_any_needs.setdefault(supplier, False) + if needs: + order_qty_by_sku[sku] = qty + needs_skus.append(sku) + if supplier is not None: + supplier_any_needs[supplier] = True + supplier_needs.setdefault(supplier, []).append((sku, qty)) + else: + stocked_skus.append(sku) + + suppliers_with_needs = [s for s in supplier_any_needs if supplier_any_needs.get(s)] + suppliers_no_needs = [s for s in supplier_any_needs if not supplier_any_needs.get(s)] + + # ---- CURRENT airtable state: resolve agent-added OrderQty field id ---- + cur_stock = _find_stock_table(air_cur) + cur_fields = cur_stock.get('fields', []) + cur_sku_fid = _field_id_by_name(cur_fields, 'SKU') or fid['sku'] + oq_fid = _field_id_by_name(cur_fields, oq_name) # agent-generated; may be None + + cur_qty_by_sku = {} + for rec in cur_stock.get('records', []): + if not isinstance(rec, dict): + continue + f = rec.get('fields', {}) if isinstance(rec.get('fields'), dict) else {} + sku = f.get(cur_sku_fid) + val = f.get(oq_fid) if oq_fid else None + if sku is not None: + cur_qty_by_sku[norm(sku)] = val + + # ---- Component 1 (0.40): OrderQty correct on needing rows, blank/0 on stocked rows ---- + n_needs = len(needs_skus) + correct = 0 + for sku in needs_skus: + val = cur_qty_by_sku.get(norm(sku)) + cv = _num(val) + if cv is not None and abs(cv - order_qty_by_sku[sku]) < 1e-6: + correct += 1 + leaks = 0 + for sku in stocked_skus: + if _is_set_nonzero(cur_qty_by_sku.get(norm(sku))): + leaks += 1 + c1 = clamp01(frac(correct - leaks, n_needs)) if n_needs else (1.0 if leaks == 0 else 0.0) + s1 = 0.30 * c1 + + # ---- Identify sent purchase-order emails ---- + init_email_ids = {e.get('id') for e in (gm_init.get('emails') or []) if isinstance(e, dict)} + cur_emails = [e for e in (gm_cur.get('emails') or []) if isinstance(e, dict)] + pfx = norm(subject_prefix) + sent_po = [ + e for e in cur_emails + if norm(e.get('subject')).startswith(pfx) + and (norm(e.get('folder')) == 'sent' or e.get('id') not in init_email_ids) + ] + + # Resolve the 'Work' label name -> its label id (Gmail emails carry label IDs). + label_name_to_id = {} + for lab in (gm_cur.get('labels') or gm_init.get('labels') or []): + if isinstance(lab, dict) and lab.get('id'): + label_name_to_id[norm(lab.get('name'))] = lab.get('id') + want_label_id = label_name_to_id.get(norm(want_label)) + + def _has_work_label(e): + labs = e.get('labels') or [] + norm_labs = {norm(x) for x in labs} + # tolerant: match by label id OR by the label name appearing directly + if want_label_id is not None and norm(want_label_id) in norm_labs: + return True + return norm(want_label) in norm_labs + + # ---- Component 2 (0.40): one correct PO email per supplier-with-needs ---- + per_supplier = [] + matched_email_by_supplier = {} # supplier -> the chosen PO email (for label/star check) + for supplier in suppliers_with_needs: + lines = supplier_needs.get(supplier, []) + exp_subj = subject_prefix + supplier + em = supplier_email_map.get(supplier) + cands = [] + for e in sent_po: + subj_match = norm(e.get('subject')) == norm(exp_subj) + recip_match = bool(em) and norm(em) in _recipients(e) + if subj_match or recip_match: + cands.append(e) + if not cands: + per_supplier.append(0.0) + continue + + def _cover(e): + body = _email_text(e) + return sum(1 for (sku, qty) in lines if _line_in(body, sku, qty)) + + best = max(cands, key=_cover) + matched_email_by_supplier[supplier] = best + line_frac = frac(_cover(best), len(lines)) if lines else 1.0 + subj_exact = norm(best.get('subject')) == norm(exp_subj) + s_sup = line_frac if subj_exact else 0.5 * line_frac + if len(cands) > 1: # "exactly one" requirement + s_sup *= 0.7 + per_supplier.append(clamp01(s_sup)) + + c2 = frac(sum(per_supplier), len(suppliers_with_needs)) if suppliers_with_needs else 1.0 + s2 = 0.35 * c2 + + # ---- Component 3 (0.15): no PO email to suppliers without needs ---- + # Gate: this component is a *negative-example guard*; awarding its full + # credit when the agent did literally nothing is a default-credit pitfall + # ("did nothing" trivially implies "did not mis-send to Globex"). Require a + # proof-of-work (at least one PO-prefixed email actually sent) before c3 + # may earn anything; otherwise c3 collapses to 0 so F00 lands at 0.0 + # instead of 0.15. + violations = 0 + for supplier in suppliers_no_needs: + bad_subj = subject_prefix + supplier + em = supplier_email_map.get(supplier) + for e in sent_po: + if norm(e.get('subject')) == norm(bad_subj) or (em and norm(em) in _recipients(e)): + violations += 1 + break + if not sent_po: + c3 = 0.0 + else: + c3 = (1.0 - frac(violations, len(suppliers_no_needs))) if suppliers_no_needs else 1.0 + s3 = 0.15 * c3 + + # ---- Component 4 (0.10): each matched PO email is labeled 'Work' AND starred ---- + # Scored only over the PO emails we actually matched in component 2, as a frac + # over all suppliers-with-needs (a missing/unmatched email earns 0 here too). + tagged_ok = 0 + for supplier in suppliers_with_needs: + e = matched_email_by_supplier.get(supplier) + if e is None: + continue + labeled = _has_work_label(e) + starred = bool(e.get('starred')) if want_starred else True + if labeled and starred: + tagged_ok += 1 + c4 = frac(tagged_ok, len(suppliers_with_needs)) if suppliers_with_needs else 1.0 + s4 = 0.10 * c4 + + # ---- Component 5 (0.10): Slack '#purchasing' summary ---- + # The '#purchasing' channel is PRE-SEEDED (the mock can't add members to a new + # channel, so an agent-created channel would have nobody to @mention). It + # starts EMPTY; the agent posts ONE summary message there that lists every + # needing-reorder SKU and @mentions the warehouse lead. We grade the NEW + # message(s) in that channel. Mentions are matched by TEXT because the mock + # only builds a structured mention when a name is picked from the @ popup; a + # hand-typed '@Dana Okafor' stays plain text. Credit: 0.6 SKU-line coverage + # (frac) + 0.4 warehouse-lead mention. + slack = go('slack') + slack_init = slack.get('initial_state', {}) if isinstance(slack, dict) else {} + slack_cur = slack.get('current_state', {}) if isinstance(slack, dict) else {} + sl_adapter = slack_init.get('_task_adapter') if isinstance(slack_init.get('_task_adapter'), dict) else {} + purch_channel = sl_adapter.get('purchasing_channel') or 'purchasing' + lead_name = sl_adapter.get('warehouse_lead_name') or '' + exp_skus = sl_adapter.get('expected_reorder_skus') if isinstance(sl_adapter.get('expected_reorder_skus'), list) else [] + + # New messages in '#purchasing' (current minus initial by id; channel pre-seeded empty). + purch_init_msgs = _slack_channel_messages(slack_init, purch_channel) + purch_init_ids = {m.get('messageId') or m.get('id') for m in purch_init_msgs if isinstance(m, dict)} + purch_cur_msgs = _slack_channel_messages(slack_cur, purch_channel) + new_purch_msgs = [m for m in purch_cur_msgs + if isinstance(m, dict) and (m.get('messageId') or m.get('id')) not in purch_init_ids] + + def _cover(m): + body = norm(_msg_text(m)) + return sum(1 for sku in exp_skus + if re.search(re.escape(norm(sku)) + r'\s*x\s*' + + re.escape(str(int(order_qty_by_sku.get(sku, 0)))) + r'(?!\d)', body)) + + line_cov = 0.0 + lead_ok = False + best = max(new_purch_msgs, key=_cover) if new_purch_msgs else None + if best is not None: + line_cov = frac(_cover(best), len(exp_skus)) if exp_skus else 1.0 + body = norm(_msg_text(best)) + mention_names = {norm(mm.get('displayName')) for mm in (best.get('mentions') or []) if isinstance(mm, dict)} + # text match (hand-typed @Name) OR structured mention. + lead_ok = bool(lead_name) and (norm(lead_name) in mention_names or norm(lead_name) in body) + s5 = 0.10 * (0.6 * line_cov + 0.4 * (1.0 if lead_ok else 0.0)) + + score = s1 + s2 + s3 + s4 + s5 + + print( + 'DEBUG_T10 ' + f'needs={n_needs} correct={correct} leaks={leaks} oq_fid={oq_fid!r} ' + f'sent_po={len(sent_po)} sup_needs={suppliers_with_needs} per_supplier={[round(x, 3) for x in per_supplier]} ' + f'sup_no_needs={suppliers_no_needs} violations={violations} ' + f'want_label={want_label!r} want_label_id={want_label_id!r} tagged_ok={tagged_ok}/{len(suppliers_with_needs)} ' + f'purch_new_msgs={len(new_purch_msgs)} line_cov={round(line_cov, 3)} lead_ok={int(lead_ok)} ' + f'c1={round(c1, 4)} c2={round(c2, 4)} c3={round(c3, 4)} c4={round(c4, 4)} ' + f'w1={round(s1, 4)} w2={round(s2, 4)} w3={round(s3, 4)} w4={round(s4, 4)} w5={round(s5, 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/ops_license_audit_010__long/.PLACEHOLDER b/ops_license_audit_010__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/ops_license_audit_010__long/.PLACEHOLDER @@ -0,0 +1,5 @@ +This directory is intentionally empty. +It exists only to satisfy start_our_benchmark_test.sh's uniform +'cache_dir// must exist' precheck. Non-mock tasks do not use +cua_gym cache; their evaluators read a vm_file tarball instead. +See docs/0716_迁移执行日志.md § S15 for details. diff --git a/ops_license_audit_010__long/31cc7c4c-5e63-5f56-bdc5-79f24905368d_requirements.txt b/ops_license_audit_010__long/31cc7c4c-5e63-5f56-bdc5-79f24905368d_requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b3a4bc96287b9eebdb2e16aed1319192ebf76e5 --- /dev/null +++ b/ops_license_audit_010__long/31cc7c4c-5e63-5f56-bdc5-79f24905368d_requirements.txt @@ -0,0 +1,5 @@ +requests==2.31.0 +pyyaml==6.0.1 +paramiko==3.4.0 +click==8.1.7 +rpy2==3.5.16 diff --git a/ops_license_audit_010__long/f44856ad-7d1a-5466-adc6-26115b152fb1_license_audit.xlsx b/ops_license_audit_010__long/f44856ad-7d1a-5466-adc6-26115b152fb1_license_audit.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..c4c6cf7755fb9b586c98e233e7cb97abeaf36787 Binary files /dev/null and b/ops_license_audit_010__long/f44856ad-7d1a-5466-adc6-26115b152fb1_license_audit.xlsx differ diff --git a/ops_license_audit_010__long/license_audit_gold.xlsx b/ops_license_audit_010__long/license_audit_gold.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0efb6073252409a605aa5ef11fa020dae650ca4b Binary files /dev/null and b/ops_license_audit_010__long/license_audit_gold.xlsx differ diff --git a/ops_pdf_mail_012__long__cond/.PLACEHOLDER b/ops_pdf_mail_012__long__cond/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/ops_pdf_mail_012__long__cond/.PLACEHOLDER @@ -0,0 +1,5 @@ +This directory is intentionally empty. +It exists only to satisfy start_our_benchmark_test.sh's uniform +'cache_dir// must exist' precheck. Non-mock tasks do not use +cua_gym cache; their evaluators read a vm_file tarball instead. +See docs/0716_迁移执行日志.md § S15 for details. diff --git a/ops_pdf_mail_012__long__cond/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py b/ops_pdf_mail_012__long__cond/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py new file mode 100644 index 0000000000000000000000000000000000000000..b48c427a8c05b22cf22112913ad02b2ee0ba26f8 --- /dev/null +++ b/ops_pdf_mail_012__long__cond/5981635d-b7a8-5429-8425-5716d648733d_fake_smtpd.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +"""Local fake SMTP daemon for task multi_apps_b2d9report. + +Runs on the VM (NOT part of the evaluator). Listens on localhost:2525, accepts +any mail for any recipient, and saves each delivered message verbatim as an +.eml file under /home/user/fake_smtp_mail/. + +Why: + Thunderbird's "Send" workflow requires a real SMTP endpoint to reach + "message accepted by server" state. Pointing at a non-existent host (e.g. + smtp.invalid) causes Thunderbird to surface modal error dialogs that + derail the agent. Pointing at a local always-accepting daemon removes + that failure mode while giving the evaluator a clean file-based signal + (each successful send -> one .eml on disk). + +Design constraints: + * Zero third-party deps — uses only the Python 3 stdlib socket module. + * Portable across Python 3.8..3.13+ (no reliance on the removed + `asyncore` / `smtpd` modules). OSWorld VM ships Python 3.10 today but + we want this script to keep working if the VM ever bumps. + * Silent by default except for a single startup log line. + * Crash-resistant: a broken connection does not bring the daemon down. + +Protocol support: + We implement the tiny subset of SMTP that Thunderbird's outbound worker + uses in "plain, no auth, no STARTTLS, no AUTH" mode: + HELO / EHLO -> 250 + MAIL FROM -> 250 + RCPT TO -> 250 (any recipient accepted) + DATA -> 354, then read until CRLF.CRLF -> 250 + NOOP -> 250 + RSET -> 250 + QUIT -> 221 + anything else -> 502 + EHLO advertises 8BITMIME + SMTPUTF8 + SIZE. No AUTH capability is + advertised, which combined with smtp1.authMethod=1 keeps Thunderbird + from attempting authentication. + +File-naming scheme inside MAIL_DIR: + __<6-hex>.eml + - NNN is a zero-padded monotonic counter (001, 002, ...) so that + lexicographic sort matches send order even within the same second. +""" + +import os +import secrets +import socket +import sys +import threading +import time + +HOST = "127.0.0.1" +PORT = 2525 +MAIL_DIR = "/home/user/fake_smtp_mail" + +_counter_lock = threading.Lock() +_counter = {"n": 0} + + +# ----------------------------------------------------------------------------- +# Persistence +# ----------------------------------------------------------------------------- + +def _save_mail(mailfrom: str, rcpttos: list, data: bytes) -> str: + os.makedirs(MAIL_DIR, exist_ok=True) + + with _counter_lock: + _counter["n"] += 1 + seq = _counter["n"] + + stamp = time.strftime("%Y%m%d_%H%M%S", time.localtime()) + suffix = secrets.token_hex(3) + fname = f"{seq:03d}_{stamp}_{suffix}.eml" + fpath = os.path.join(MAIL_DIR, fname) + + envelope = ( + f"X-Envelope-From: {mailfrom}\r\n" + f"X-Envelope-To: {', '.join(rcpttos)}\r\n" + ).encode("ascii", errors="replace") + + with open(fpath, "wb") as f: + f.write(envelope) + f.write(data) + + return fpath + + +# ----------------------------------------------------------------------------- +# Line-based socket helpers (SMTP is CRLF-terminated lines) +# ----------------------------------------------------------------------------- + +class _LineReader: + """Read CRLF-terminated lines from a blocking socket.""" + + def __init__(self, sock: socket.socket): + self.sock = sock + self.buf = b"" + + def readline(self, max_bytes: int = 1 << 20) -> bytes: + """Return one line including its trailing CRLF (or '' on EOF).""" + while b"\r\n" not in self.buf: + if len(self.buf) > max_bytes: + raise ValueError("line too long") + chunk = self.sock.recv(4096) + if not chunk: + # connection closed; return whatever is buffered + line, self.buf = self.buf, b"" + return line + self.buf += chunk + line, _, rest = self.buf.partition(b"\r\n") + self.buf = rest + return line + b"\r\n" + + def read_until_dot(self, max_bytes: int = 50 << 20) -> bytes: + """Read DATA payload until a line containing only '.'. + + Returns the payload with dot-stuffing undone and the terminator + stripped. Trailing CRLF after the last data line is preserved. + """ + chunks = [] + total = 0 + while True: + line = self.readline() + if not line: + # premature EOF — treat as end of DATA + break + if line == b".\r\n": + break + # SMTP dot-stuffing: client prefixes any line starting with '.' + # with an extra '.', which we must strip. + if line.startswith(b".."): + line = line[1:] + chunks.append(line) + total += len(line) + if total > max_bytes: + raise ValueError("DATA too large") + return b"".join(chunks) + + +# ----------------------------------------------------------------------------- +# Single-session handler +# ----------------------------------------------------------------------------- + +def _send(sock: socket.socket, code: int, text: str) -> None: + sock.sendall(f"{code} {text}\r\n".encode("ascii", errors="replace")) + + +def _send_multi(sock: socket.socket, code: int, lines: list) -> None: + """Send a multi-line SMTP reply (all lines except last prefixed '-').""" + last = len(lines) - 1 + out = [] + for i, line in enumerate(lines): + sep = " " if i == last else "-" + out.append(f"{code}{sep}{line}") + sock.sendall(("\r\n".join(out) + "\r\n").encode("ascii", errors="replace")) + + +def _handle_session(conn: socket.socket, peer) -> None: + try: + reader = _LineReader(conn) + _send(conn, 220, "localhost fake SMTP ready") + + mailfrom = None + rcpttos: list = [] + + while True: + raw = reader.readline() + if not raw: + return # client hung up + + try: + line = raw.rstrip(b"\r\n").decode("utf-8", errors="replace") + except Exception: # noqa: BLE001 + _send(conn, 500, "bad line") + continue + + cmd, _, arg = line.partition(" ") + cmd_up = cmd.upper() + + if cmd_up == "HELO": + _send(conn, 250, "localhost") + elif cmd_up == "EHLO": + _send_multi(conn, 250, [ + "localhost", + "SIZE 52428800", + "8BITMIME", + "SMTPUTF8", + "HELP", + ]) + elif cmd_up == "MAIL": + # "MAIL FROM:" possibly with SIZE=... etc. + addr = _extract_addr(arg) + mailfrom = addr or "" + rcpttos = [] + _send(conn, 250, "OK") + elif cmd_up == "RCPT": + addr = _extract_addr(arg) + if addr is None: + _send(conn, 501, "bad RCPT") + else: + rcpttos.append(addr) + _send(conn, 250, "OK") + elif cmd_up == "DATA": + if mailfrom is None or not rcpttos: + _send(conn, 503, "need MAIL + RCPT first") + continue + _send(conn, 354, "end data with .") + try: + payload = reader.read_until_dot() + except Exception as e: # noqa: BLE001 + _send(conn, 552, f"read error: {e}") + continue + try: + path = _save_mail(mailfrom, rcpttos, payload) + sys.stderr.write(f"[fake_smtpd] saved {path}\n") + sys.stderr.flush() + except Exception as e: # noqa: BLE001 + sys.stderr.write(f"[fake_smtpd] save failed: {e}\n") + _send(conn, 451, "local error storing message") + mailfrom, rcpttos = None, [] + continue + _send(conn, 250, "OK message accepted") + mailfrom, rcpttos = None, [] + elif cmd_up == "RSET": + mailfrom, rcpttos = None, [] + _send(conn, 250, "OK") + elif cmd_up == "NOOP": + _send(conn, 250, "OK") + elif cmd_up == "QUIT": + _send(conn, 221, "bye") + return + elif cmd_up == "VRFY": + _send(conn, 252, "cannot verify") + elif cmd_up == "HELP": + _send(conn, 214, "HELO EHLO MAIL RCPT DATA RSET NOOP QUIT") + else: + _send(conn, 502, f"command not implemented: {cmd_up}") + except (ConnectionResetError, BrokenPipeError, OSError): + pass + except Exception as e: # noqa: BLE001 + sys.stderr.write(f"[fake_smtpd] session {peer} error: {e}\n") + finally: + try: + conn.close() + except Exception: # noqa: BLE001 + pass + + +def _extract_addr(arg: str): + """Parse '' or 'FROM:' / 'TO:' (with optional params). + + Returns the address string, possibly empty (empty return-path is legal + for bounces), or None on parse failure. + """ + if not arg: + return None + # Strip optional 'FROM:' / 'TO:' prefix (case-insensitive), plus spaces + colon = arg.find(":") + if colon != -1 and arg[:colon].upper() in ("FROM", "TO"): + arg = arg[colon + 1 :].lstrip() + # Now expect [params...] + if not arg.startswith("<"): + # tolerate bare address + return arg.split()[0] + end = arg.find(">") + if end == -1: + return None + return arg[1:end] + + +# ----------------------------------------------------------------------------- +# Main loop +# ----------------------------------------------------------------------------- + +def main() -> None: + os.makedirs(MAIL_DIR, exist_ok=True) + + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + srv.bind((HOST, PORT)) + except OSError as e: + sys.stderr.write(f"[fake_smtpd] cannot bind {HOST}:{PORT}: {e}\n") + sys.exit(1) + srv.listen(16) + + sys.stderr.write( + f"[fake_smtpd] listening on {HOST}:{PORT}, mails -> {MAIL_DIR}\n" + ) + sys.stderr.flush() + + try: + while True: + try: + conn, peer = srv.accept() + except KeyboardInterrupt: + break + except OSError as e: + sys.stderr.write(f"[fake_smtpd] accept error: {e}\n") + continue + t = threading.Thread( + target=_handle_session, args=(conn, peer), daemon=True + ) + t.start() + finally: + try: + srv.close() + except Exception: # noqa: BLE001 + pass + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ops_pdf_mail_012__long__cond/c6bdf2ec-0613-5c22-ab89-6843875c6d43_mail_info.xlsx b/ops_pdf_mail_012__long__cond/c6bdf2ec-0613-5c22-ab89-6843875c6d43_mail_info.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..41f2227b7351488d23af3048ab8e2e746a3c45c0 Binary files /dev/null and b/ops_pdf_mail_012__long__cond/c6bdf2ec-0613-5c22-ab89-6843875c6d43_mail_info.xlsx differ diff --git a/ops_pdf_mail_012__long__cond/e2317a9f-f460-57e6-a41d-47fae755c954_weekly_summary.pptx b/ops_pdf_mail_012__long__cond/e2317a9f-f460-57e6-a41d-47fae755c954_weekly_summary.pptx new file mode 100644 index 0000000000000000000000000000000000000000..0b1075a2a480da161f039649ebdcab1b7e6adbbc Binary files /dev/null and b/ops_pdf_mail_012__long__cond/e2317a9f-f460-57e6-a41d-47fae755c954_weekly_summary.pptx differ diff --git a/ops_region_consolidate_002__long/_cua_gym_vm_bridge.sh b/ops_region_consolidate_002__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ops_region_consolidate_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/ops_region_consolidate_002__long/initial_setup.py b/ops_region_consolidate_002__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..31132a266d98be436d250edce4e057bb81b03819 --- /dev/null +++ b/ops_region_consolidate_002__long/initial_setup.py @@ -0,0 +1,727 @@ +""" +Initial Setup: V1 — Multi-source sheet consolidation & sync +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_v1.py +Variant: eval +Mocks: google_sheets_mock,airtable_mock,slack_mock +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +APP_STATES = [('http://28.7.184.198:8145', + {'id': 'workbook_lc_v1', + 'title': 'Master', + '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': 'Master', + 'data': {'A1': {'value': 'Date', + 'formula': 'Date', + 'computed': 'Date', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Rep', + 'formula': 'Rep', + 'computed': 'Rep', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Amount', + 'formula': 'Amount', + 'computed': 'Amount', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}}, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None}, + {'id': 'sheet_2', + 'name': 'Region-East', + 'data': {'A1': {'value': 'Date', + 'formula': 'Date', + 'computed': 'Date', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Rep', + 'formula': 'Rep', + 'computed': 'Rep', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Amount', + 'formula': 'Amount', + 'computed': 'Amount', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'A2': {'value': '2024-03-01', 'formula': '2024-03-01', 'computed': '2024-03-01'}, + 'B2': {'value': 'Lee', 'formula': 'Lee', 'computed': 'Lee'}, + 'C2': {'value': '100', 'formula': '100', 'computed': 100}, + 'A3': {'value': '2024-03-02', 'formula': '2024-03-02', 'computed': '2024-03-02'}, + 'B3': {'value': 'Wu', 'formula': 'Wu', 'computed': 'Wu'}, + 'C3': {'value': '200', 'formula': '200', 'computed': 200}}, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None}, + {'id': 'sheet_3', + 'name': 'Region-West', + 'data': {'A1': {'value': 'Date', + 'formula': 'Date', + 'computed': 'Date', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Sales Rep', + 'formula': 'Sales Rep', + 'computed': 'Sales Rep', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Total', + 'formula': 'Total', + 'computed': 'Total', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'D1': {'value': 'Notes', + 'formula': 'Notes', + 'computed': 'Notes', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'A2': {'value': '2024-03-01', 'formula': '2024-03-01', 'computed': '2024-03-01'}, + 'B2': {'value': 'Xu', 'formula': 'Xu', 'computed': 'Xu'}, + 'C2': {'value': '150', 'formula': '150', 'computed': 150}, + 'D2': {'value': 'n', 'formula': 'n', 'computed': 'n'}, + 'A3': {'value': '2024-03-01', 'formula': '2024-03-01', 'computed': '2024-03-01'}, + 'B3': {'value': '', 'formula': '', 'computed': ''}, + 'C3': {'value': '100', 'formula': '100', 'computed': 100}, + 'D3': {'value': '', 'formula': '', 'computed': ''}}, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None}, + {'id': 'sheet_4', + 'name': 'Region-North', + 'data': {'A1': {'value': 'Day', + 'formula': 'Day', + 'computed': 'Day', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Person', + 'formula': 'Person', + 'computed': 'Person', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Sum', + 'formula': 'Sum', + 'computed': 'Sum', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'A2': {'value': '2024-03-03', 'formula': '2024-03-03', 'computed': '2024-03-03'}, + 'B2': {'value': 'Ann', 'formula': 'Ann', 'computed': 'Ann'}, + 'C2': {'value': '80', 'formula': '80', 'computed': 80}}, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None}, + {'id': 'sheet_5', + 'name': 'Region-South', + 'data': {'A1': {'value': 'Date', + 'formula': 'Date', + 'computed': 'Date', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Rep', + 'formula': 'Rep', + 'computed': 'Rep', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Amount', + 'formula': 'Amount', + 'computed': 'Amount', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'A2': {'value': '2024-03-04', 'formula': '2024-03-04', 'computed': '2024-03-04'}, + 'B2': {'value': 'Bo', 'formula': 'Bo', 'computed': 'Bo'}, + 'C2': {'value': '60', 'formula': '60', 'computed': 60}}, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None}, + {'id': 'sheet_6', + 'name': 'Region-Central', + 'data': {'A1': {'value': 'Date', + 'formula': 'Date', + 'computed': 'Date', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Owner', + 'formula': 'Owner', + 'computed': 'Owner', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Revenue', + 'formula': 'Revenue', + 'computed': 'Revenue', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'A2': {'value': '2024-03-05', 'formula': '2024-03-05', 'computed': '2024-03-05'}, + 'B2': {'value': 'Cy', 'formula': 'Cy', 'computed': 'Cy'}, + 'C2': {'value': '90', 'formula': '90', 'computed': 90}}, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None}, + {'id': 'sheet_7', + 'name': 'Region-Intl', + 'data': {'A1': {'value': 'Date', + 'formula': 'Date', + 'computed': 'Date', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'B1': {'value': 'Rep', + 'formula': 'Rep', + 'computed': 'Rep', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'C1': {'value': 'Amount', + 'formula': 'Amount', + 'computed': 'Amount', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'D1': {'value': 'FX', + 'formula': 'FX', + 'computed': 'FX', + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, + 'A2': {'value': '2024-03-06', 'formula': '2024-03-06', 'computed': '2024-03-06'}, + 'B2': {'value': 'Di', 'formula': 'Di', 'computed': 'Di'}, + 'C2': {'value': '70', 'formula': '70', 'computed': 70}, + 'D2': {'value': 'EUR', 'formula': 'EUR', 'computed': 'EUR'}}, + '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': 'rows_dict', + 'task_id': 'lc_v1', + 'variant': 'eval', + 'task_sheets': {'Master': {'headers': ['Date', 'Rep', 'Amount'], 'rows': []}, + 'Region-East': {'headers': ['Date', 'Rep', 'Amount'], + 'rows': [{'Date': '2024-03-01', 'Rep': 'Lee', 'Amount': 100}, + {'Date': '2024-03-02', 'Rep': 'Wu', 'Amount': 200}], + 'mapping': {'Date': 'Date', 'Rep': 'Rep', 'Amount': 'Amount'}}, + 'Region-West': {'headers': ['Date', 'Sales Rep', 'Total', 'Notes'], + 'rows': [{'Date': '2024-03-01', + 'Sales Rep': 'Xu', + 'Total': 150, + 'Notes': 'n'}, + {'Date': '2024-03-01', 'Rep': 'Lee', 'Total': 100}], + 'mapping': {'Date': 'Date', + 'Rep': 'Sales Rep', + 'Amount': 'Total'}}, + 'Region-North': {'headers': ['Day', 'Person', 'Sum'], + 'rows': [{'Day': '2024-03-03', 'Person': 'Ann', 'Sum': 80}], + 'mapping': {'Date': 'Day', 'Rep': 'Person', 'Amount': 'Sum'}}, + 'Region-South': {'headers': ['Date', 'Rep', 'Amount'], + 'rows': [{'Date': '2024-03-04', 'Rep': 'Bo', 'Amount': 60}], + 'mapping': {'Date': 'Date', 'Rep': 'Rep', 'Amount': 'Amount'}}, + 'Region-Central': {'headers': ['Date', 'Owner', 'Revenue'], + 'rows': [{'Date': '2024-03-05', 'Owner': 'Cy', 'Revenue': 90}], + 'mapping': {'Date': 'Date', + 'Rep': 'Owner', + 'Amount': 'Revenue'}}, + 'Region-Intl': {'headers': ['Date', 'Rep', 'Amount', 'FX'], + 'rows': [{'Date': '2024-03-06', + 'Rep': 'Di', + 'Amount': 70, + 'FX': 'EUR'}], + 'mapping': {'Date': 'Date', 'Rep': 'Rep', 'Amount': 'Amount'}}}, + 'headers_by_sheet': {'Master': ['Date', 'Rep', 'Amount'], + 'Region-East': ['Date', 'Rep', 'Amount'], + 'Region-West': ['Date', 'Sales Rep', 'Total', 'Notes'], + 'Region-North': ['Day', 'Person', 'Sum'], + 'Region-South': ['Date', 'Rep', 'Amount'], + 'Region-Central': ['Date', 'Owner', 'Revenue'], + 'Region-Intl': ['Date', 'Rep', 'Amount', 'FX']}, + 'sheet_names': ['Master', + 'Region-East', + 'Region-West', + 'Region-North', + 'Region-South', + 'Region-Central', + 'Region-Intl']}}), + ('http://28.7.184.198:8109', + {'tables': [{'name': 'Sales', 'fields': ['Date', 'Rep', 'Amount'], 'records': []}]}), + ('http://28.7.184.198:8178', + # Slack workspace. + # Task channel is #ops -- the agent must post the + # "Consolidated {n} rows" line there. The other channels + # (#general / #random / #data-team) plus the prior chatter are purely + # watermark decoration so the workspace doesn't look freshly-empty; + # reward.py only inspects #ops, so these extras do not affect scoring. + # IMPORTANT: #ops MUST start with NO messages -- the reward awards full + # slack credit for any message in #ops, so we never pre-seed it. + # IMPORTANT: #data-team is left without pre-seeded messages on purpose + # (a sheets/data sibling channel should not contain prose that might + # accidentally look like a task artefact). + {'channels': [{'channelId': 'general', + 'name': 'general', + 'description': 'Company-wide announcements and work-based matters', + 'topic': 'Welcome to Acme Corp!', + 'isPrivate': False, + 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_2', + 'createdAt': '2026-05-01T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + {'channelId': 'random', + 'name': 'random', + 'description': 'Non-work banter and watercooler chat', + 'topic': 'Coffee, memes, weekend plans', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_3', + 'createdAt': '2026-05-01T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + {'channelId': 'data-team', + 'name': 'data-team', + 'description': 'Data team coordination', + 'topic': 'Pipelines, dashboards, weekly numbers', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_3'], + 'createdBy': 'user_3', + 'createdAt': '2026-05-15T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + {'channelId': 'ops', + 'name': 'ops', + 'description': '', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1'], + 'createdBy': 'user_1', + 'createdAt': '2026-06-06T08:54:57Z', + 'pinnedMessages': [], + 'unreadCount': 0}], + 'currentUser': {'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'users': [{'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_2', + 'fullName': 'Maya Lindqvist', + 'displayName': 'Maya', + 'email': 'maya.lindqvist@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'People Ops', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'Europe/Stockholm'}, + {'userId': 'user_3', + 'fullName': 'Hiroshi Tanabe', + 'displayName': 'Hiroshi', + 'email': 'hiroshi.tanabe@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Engineering', + 'status': 'away', + 'statusMessage': 'In a meeting', + 'statusEmoji': ':calendar:', + 'timeZone': 'Asia/Tokyo'}, + {'userId': 'user_4', + 'fullName': 'Olivia Becker', + 'displayName': 'Olivia', + 'email': 'olivia.becker@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': 'Marketing', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/Los_Angeles'}], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'messages': {'general': [{'messageId': 'm_g_1', + 'senderId': 'user_2', + 'content': 'Morning everyone -- office is closed next Friday for the company offsite.', + 'timestamp': '2026-06-03T13:02:00Z', + 'reactions': [], + 'isEdited': False, + 'threadId': None, + 'attachments': []}, + {'messageId': 'm_g_2', + 'senderId': 'user_4', + 'content': 'Thanks Maya! Long weekend incoming :tada:', + 'timestamp': '2026-06-03T13:05:00Z', + 'reactions': [{'emoji': '\U0001F389', 'users': ['user_1', 'user_3']}], + 'isEdited': False, + 'threadId': None, + 'attachments': []}], + 'random': [{'messageId': 'm_r_1', + 'senderId': 'user_4', + 'content': 'Anyone tried the new ramen place on 3rd? Verdict?', + 'timestamp': '2026-06-03T18:50:00Z', + 'reactions': [{'emoji': '\U0001F35C', 'users': ['user_3']}], + 'isEdited': False, + 'threadId': None, + 'attachments': []}, + {'messageId': 'm_r_2', + 'senderId': 'user_3', + 'content': "10/10, get the spicy miso. Bring tissues though, it's no joke.", + 'timestamp': '2026-06-03T18:55:00Z', + 'reactions': [{'emoji': '\U0001F605', 'users': ['user_1', 'user_4']}], + 'isEdited': False, + 'threadId': None, + 'attachments': []}], + 'data-team': [], + # IMPORTANT: leave #ops empty; reward awards full slack + # credit for any message in #ops. + 'ops': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + '_task_adapter': {'task_id': 'lc_v1', 'variant': 'eval'}})] + + +for app_url, state in APP_STATES: + resp = requests.post( + f'{app_url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, ( + f'State injection failed for {app_url}: {resp.text}' + ) + print(f'State injected: {app_url} sid={sid}') + +for app_url, _ in APP_STATES: + go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json() + assert go_payload.get('initial_state') is not None, ( + f'initial_state is None after injection for {app_url}' + ) + print(f'Verified initial_state set: {app_url}') + + +# PATCHED_BY: patch_wait_mocks_loaded.py +def launch_gui(command, delay_sec=1.0): + """Launch a GUI command, fully detached from this script. + + Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that + wait_mocks_loaded's CDP phase can verify browser render below. + Idempotent: if the caller already specified a debug port, keep it. + """ + env = os.environ.copy() + env['DISPLAY'] = ':0' + if isinstance(command, str): + _parts = shlex.split(command) + else: + _parts = list(command) + if (_parts and 'google-chrome' in _parts[0] + and not any(p.startswith('--remote-debugging-port') for p in _parts)): + _parts[1:1] = [ + '--no-first-run', + '--no-default-browser-check', + '--remote-debugging-port=1337', + ] + subprocess.Popen( + _parts, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=env, + start_new_session=True, + ) + time.sleep(delay_sec) + + +def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12): + """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style. + + Phase 1 - Backend readiness: + Poll each mock's /state?sid= (preferred) or /go?sid= + (fallback) until it returns 200 with 'stored_state' or + 'initial_state' respectively, or until timeout. + + Phase 2 - Browser render verification (via CDP + Playwright): + Connect to http://localhost:1337 (the --remote-debugging-port + injected by launch_gui above), wait for every open tab to reach + 'networkidle' AND to contain at least 20 DOM elements. This + guarantees the SPA fetched /go?sid= data AND actually painted, + not just that the mock backend is up. + + Fallback: + If Playwright is missing or CDP cannot be reached, sleep for + `render_buffer` seconds as a best-effort delay so the screenshot + loop does not start on a still-blank tab. + """ + import urllib.request as _urlreq + import time as _t + _urls = [p for p, _ in app_states] + _opener = _urlreq.build_opener(_urlreq.ProxyHandler({})) + + # ---- Phase 1: backend readiness ---- + _deadline = _t.time() + timeout + _todo = list(_urls) + while _todo and _t.time() < _deadline: + _rest = [] + for _u in _todo: + _ok = False + for _path, _need in (('/state?sid=', b'stored_state'), + ('/go?sid=', b'initial_state')): + try: + _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5) + if _r.status == 200: + _body = _r.read() + if _need in _body: + _ok = True + break + except Exception: + pass + if _ok: + print(f" {_u}: backend ready") + continue + _rest.append(_u) + _todo = _rest + if _todo: + _t.sleep(2) + _done = len(_urls) - len(_todo) + _pend = f" (pending: {_todo})" if _todo else "" + print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}") + + # ---- Phase 2: browser render verification via CDP ---- + _cdp_ok = False + try: + from playwright.sync_api import sync_playwright + _cdp_dl = _t.time() + max(15.0, _deadline - _t.time()) + with sync_playwright() as _p: + _br = None + while _t.time() < _cdp_dl: + try: + _br = _p.chromium.connect_over_cdp('http://localhost:1337') + break + except Exception: + _t.sleep(0.5) + if _br is None: + print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?") + else: + _n_expected = len(_urls) + _pages = [] + _pg_dl = _t.time() + 15 + _last_count = -1 + _stable_since = None + while _t.time() < _pg_dl: + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + _cnt = len(_pages) + if _n_expected > 0 and _cnt >= _n_expected: + break + if _cnt > 0 and _cnt == _last_count: + if _stable_since is None: + _stable_since = _t.time() + elif _t.time() - _stable_since >= 1.5: + break + else: + _stable_since = None + _last_count = _cnt + _t.sleep(0.5) + _pages = [] + for _c in _br.contexts: + _pages.extend(_c.pages) + if not _pages: + print(" wait_mocks_loaded: CDP connected but no open tabs found") + else: + print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render") + _MIN_ELEMS = 20 + _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap + for _pg in _pages: # bring each to front once to defeat background-tab render throttling + try: + _pg.bring_to_front() + except Exception: + pass + _pending = list(_pages) + while _pending and _t.time() < _verify_dl: + _still = [] + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + try: + _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0") + except Exception: + _n = 0 + if _n >= _MIN_ELEMS: + print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)") + else: + _still.append(_pg) + _pending = _still + if _pending: + _t.sleep(2) + if not _pending: + _cdp_ok = True + else: + for _pg in _pending: + _ttl = "" + try: + _ttl = _pg.title() + except Exception: + pass + print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back") + except ImportError: + print(" wait_mocks_loaded: playwright not installed; skipping CDP phase") + except Exception as _e: + print(f" wait_mocks_loaded: CDP phase error ({_e!r})") + + if not _cdp_ok: + print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep") + _t.sleep(render_buffer) + else: + print(" wait_mocks_loaded: browser render verified, skipping render_buffer") + + +def _open_mock_tabs(app_states, sid_value): + """Open the first mock as the primary Chrome window, the rest as new tabs. + + Uses launch_gui once per URL so that the macOS localizer regex-extract + (which grabs the FIRST quoted URL per call) still works correctly. + """ + _urls = [p for p, _ in app_states] + if not _urls: + return + launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0) + for _u in _urls[1:]: + launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0) + + + +# PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate) +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until every mock serves injected state AND (best-effort) renders.""" + import time as _t + deadline = _t.time() + timeout + pending = dict(mocks) + while pending and _t.time() < deadline: + for name in list(pending): + try: + r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5) + if r.status_code == 200 and r.json().get('initial_state') is not None: + del pending[name] + except Exception: + pass + if pending: + _t.sleep(1.0) + if pending: + print(f'WARN: mocks not ready within {timeout}s: {list(pending)}') + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check, settle 3s') + _t.sleep(3.0) + return + with sync_playwright() as p: + try: + browser = p.chromium.launch(channel='chrome', headless=True, + args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage']) + except Exception as e: + print(f'WARN: could not launch chrome for render check: {e}; settle 3s') + _t.sleep(3.0) + return + try: + for name, url in mocks.items(): + page = browser.new_page() + try: + page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000)) + page.wait_for_function( + "document.body && document.body.innerText.length > 50", + timeout=int(render_timeout * 1000)) + print(f'[{name}] rendered OK') + except Exception as e: + print(f'WARN: [{name}] render check issue: {e}') + finally: + page.close() + finally: + browser.close() + + +# ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render +_open_mock_tabs(APP_STATES, sid) +wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15) +wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12) +print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps') diff --git a/ops_region_consolidate_002__long/reward.py b/ops_region_consolidate_002__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..b18c6e90ce17c58da7a2ff4023847ec7730e5dc0 --- /dev/null +++ b/ops_region_consolidate_002__long/reward.py @@ -0,0 +1,479 @@ +""" +Reward Script: V1 — Multi-source sheet consolidation & sync +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_v1.py +Variant: eval +Mocks: google_sheets_mock,airtable_mock,slack_mock +""" +import copy +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 = {'google_sheets': 'http://28.7.184.198:8145', 'airtable': 'http://28.7.184.198:8109', '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 _to_float(v): + try: + return float(v) + except (TypeError, ValueError): + return 0.0 + + +def _sheet_rows(sheet): + if not isinstance(sheet, dict): + return [] + rows = sheet.get('rows', []) + return rows if isinstance(rows, list) else [] + + +def _sheet_tabs(sheets): + if isinstance(sheets, dict): + return sheets + if isinstance(sheets, list): + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') + if name: + out[name] = sh + return out + return {} + + +def _expected(sheets): + tabs = _sheet_tabs(sheets) + rows = set() + for name, tab in tabs.items(): + if norm(name) == 'master': + continue + mapping = tab.get('mapping', {}) if isinstance(tab, dict) else {} + src_date = mapping.get('Date', 'Date') + src_rep = mapping.get('Rep', 'Rep') + src_amount = mapping.get('Amount', 'Amount') + for r in _sheet_rows(tab): + if not isinstance(r, dict): + continue + rows.add(( + norm(r.get(src_date)), + norm(r.get(src_rep)), + _to_float(r.get(src_amount)), + )) + return rows + + +def _jaccard(a, b): + if not a and not b: + return 1.0 + u = a | b + return (len(a & b) / len(u)) if u else 1.0 + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _parse_cell_id(cell_id): + if not isinstance(cell_id, str) or not cell_id: + return None + idx = 0 + while idx < len(cell_id) and cell_id[idx].isalpha(): + idx += 1 + if idx == 0 or idx >= len(cell_id): + return None + col = 0 + for ch in cell_id[:idx].upper(): + col = col * 26 + (ord(ch) - ord('A') + 1) + try: + row = int(cell_id[idx:]) + except ValueError: + return None + return row, col - 1 + + +def _extract_rows_from_workbook(state): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} + + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') or 'Sheet1' + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + + headers = headers_by_sheet.get(name) + if not headers: + cols = [] + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx != 1: + continue + value = '' + if isinstance(cell, dict): + value = cell.get('value', '') + elif cell is not None: + value = str(cell) + if value is not None and str(value) != '': + cols.append((col_idx, str(value))) + headers = [v for _, v in sorted(cols)] + + if not headers: + continue + + by_row = {} + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx <= 1 or col_idx >= len(headers): + continue + if isinstance(cell, dict): + value = cell.get('value', '') + else: + value = cell + by_row.setdefault(row_idx, {})[headers[col_idx]] = value + + rows = [] + for row_idx in sorted(by_row.keys()): + row = by_row[row_idx] + if not any(str(row.get(h, '')).strip() for h in headers): + continue + rows.append({h: row.get(h, '') for h in headers}) + + out[name] = {'headers': headers, 'rows': rows} + + if not out: + return None + return {'sheets': out} + + +def _materialize_google_sheets(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + maybe_rows = _extract_rows_from_workbook(state) + if maybe_rows is not None: + state['_ui_workbook'] = { + 'sheets': copy.deepcopy(state.get('sheets', [])), + 'title': state.get('title'), + } + state['sheets'] = maybe_rows['sheets'] + + +def _materialize_slack(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, + 'messageId': mid, + 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), + 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward copied from task file === +def reward(go): + gs_initial = go("google_sheets")["initial_state"] + adapter = gs_initial.get("_task_adapter", {}) if isinstance(gs_initial, dict) else {} + # Use the task adapter's source-schema tabs (renamed columns + per-tab mapping), + # which _materialize_google_sheets leaves intact. The materialized "sheets" drop + # the mapping and rename the keys, which makes _expected() mis-read renamed tabs. + sheets_i = adapter.get("task_sheets") or gs_initial.get("sheets", {}) + master = go("google_sheets")["current_state"]["sheets"].get("Master", {}) + air = go("airtable")["current_state"] + slack = go("slack")["current_state"] + + expected = _expected(sheets_i) + got_master = {(norm(r.get("Date") or r.get("date")), + norm(r.get("Rep") or r.get("rep")), + float(r.get("Amount") or r.get("amount") or 0)) + for r in master.get("rows", [])} + + recs = [] + # for t in air.get("tables", []): + # print(t) + # if norm(t.get("name")) == "sales": + # recs = t.get("records", []) + # print('got master') + # got_air = {(norm(r.get("fields", {}).get("Date")), + # norm(r.get("fields", {}).get("Rep")), + # float(r.get("fields", {}).get("Amount", 0))) for r in recs} + + col_to_fid = {} + tables = air.get("tables", {}) + + # Bug 1 + 2: tables is a dict; the data table is the one in the base named "Sales". + sales_base_ids = {bid for bid, b in air.get("bases", {}).items() + if norm(b.get("name")) == "sales"} + for t in tables.values(): + if not isinstance(t, dict) or not t.get("records"): + continue + if t.get("baseId") in sales_base_ids or norm(t.get("name")) == "sales": + recs = t["records"] + # Bug 3: recover Date/Rep/Amount -> field-id from the header row. + for r in recs: + inv = {norm(v): fid for fid, v in r.get("fields", {}).items()} + if {"date", "rep", "amount"} <= set(inv): + col_to_fid = {"Date": inv["date"], "Rep": inv["rep"], "Amount": inv["amount"]} + break + break + + got_air = set() + for r in recs: + f = r.get("fields", {}) + date = f.get(col_to_fid.get("Date")) + rep = f.get(col_to_fid.get("Rep")) + if norm(date) == "date" and norm(rep) == "rep": + continue # skip the header row itself + got_air.add((norm(date), norm(rep), _to_float(f.get(col_to_fid.get("Amount"))))) + print('got air', got_air) + print('expected', expected) + chan = [m for ch in slack.get("channels", []) if norm(ch.get("name")) == "ops" + for m in ch.get("messages", [])] + def _ops_text(m): + t = m.get('text') if m.get('text') is not None else m.get('content', '') + return (t or '').lower() + slack_ok = 1.0 if any( + 'consolidat' in _ops_text(m) and 'row' in _ops_text(m) + and any(c.isdigit() for c in _ops_text(m)) for m in chan) else 0.0 + + print('expected ', expected) + print('got_master', got_master) + jac_master = _jaccard(expected, got_master) + jac_air = _jaccard(expected, got_air) + jac_master = 1.0 if expected == got_master else 0.0 + jac_air = 1.0 if expected == got_air else 0.0 + s_master = 0.5 * jac_master + s_air = 0.45 * jac_air + s_slack = 0.05 * slack_ok + score = s_master + s_air + s_slack + + print( + 'DEBUG_V1 ' + f'expected={len(expected)} got_master={len(got_master)} got_air={len(got_air)} ' + f'jac_master={round(jac_master, 4)} jac_air={round(jac_air, 4)} slack_ok={int(slack_ok)} ' + f'w_master={round(s_master, 4)} w_air={round(s_air, 4)} ' + f'w_slack={round(s_slack, 4)} total={round(score, 4)}' + ) + + return clamp01(score) + + +# try: +score = float(reward(go)) +# except Exception as exc: +# print(f'ERROR: reward() raised {exc!r}') +# score = 0.0 + +score = clamp01(score) +print(f'\nREWARD: {round(score, 4)}') + +""" + +python3 tools/replay_reward.py --task-dir results_mock_apps_selfhost_jun17_2/kimi/round_1/pyautogui/screenshot/Kimi-K2.6/google_sheets_mock,airtable_mock,slack_mock/82fb3407-d6fa-57f4-b798-cd776748fd98 -v + +""" \ No newline at end of file diff --git a/qa_pr_mergeable_003/_cua_gym_vm_bridge.sh b/qa_pr_mergeable_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/qa_pr_mergeable_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/qa_pr_mergeable_003/initial_setup.py b/qa_pr_mergeable_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..06913d93dcf5df6f5cfcce03fbf9924b219a3570 --- /dev/null +++ b/qa_pr_mergeable_003/initial_setup.py @@ -0,0 +1,365 @@ +""" +Initial Setup: se_pr_jira_slack_gate_b92 +Task ID: qa_pr_mergeable_003 +Domain: mock_websites +Mocks: github_mock, jira_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a release engineer. Your tools for this task are: the GitHub repositories, the Jira project board, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): GitHub repo with 0 issue(s) and 2 PR(s); Jira Kanban project with issues KAN-1(Done), KAN-3(In Progress), KAN-4(In Progress); Slack workspace with channels #general, #engineering, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: KAN-3 (PR #7) moved to In Review (+0.45); slack_new_msg (+0.1); verdict names PR #7 as ready (+0.2); explains #8 is blocked (+0.25). 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 = { + "github_mock": "http://28.7.184.198:8136", + "jira_mock": "http://28.7.184.198:8153", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8136' + +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 = { 'github_mock': { 'currentUser': { 'id': 'u1', + 'username': 'octocat', + 'name': 'The Octocat', + 'email': 'octocat@github.com', + 'avatar': ''}, + 'users': [ { 'id': 'u1', + 'username': 'octocat', + 'name': 'The Octocat', + 'email': 'octocat@github.com', + 'avatar': ''}, + { 'id': 'u2', + 'username': 'hubot', + 'name': 'Hubot', + 'email': 'hubot@github.com', + 'avatar': ''}], + 'repos': [ { 'id': 'r1', + 'ownerId': 'u1', + 'name': 'hello-world', + 'description': 'Sample repo', + 'language': 'Python', + 'stars': 12, + 'forks': 3, + 'watchers': 5, + 'isPrivate': False, + 'defaultBranch': 'main', + 'topics': [], + 'hasWiki': True, + 'hasIssues': True, + 'updatedAt': '2026-06-01T00:00:00Z', + 'createdAt': '2026-01-01T00:00:00Z'}], + 'branches': [ { 'id': 'b1', + 'repoId': 'r1', + 'name': 'main', + 'lastCommitId': 'abc123'}], + 'files': [], + 'commits': [], + 'issues': [], + 'pullRequests': [ { 'id': 'pr7', + 'repoId': 'r1', + 'number': 7, + 'title': 'Add retry logic to webhook dispatcher', + 'description': '', + 'baseBranch': 'main', + 'compareBranch': 'feature', + 'status': 'open', + 'isDraft': False, + 'authorId': 'u1', + 'assignees': [], + 'labels': [], + 'milestone': None, + 'mergeStrategy': 'merge', + 'mergedAt': None, + 'mergedBy': None, + 'createdAt': '2026-06-01T00:00:00Z', + 'closedAt': None, + 'comments': [], + 'reviewers': [{'userId': 'u2', 'state': 'approved'}], + 'checks': [ { 'name': 'ci/build', + 'status': 'success'}, + { 'name': 'ci/test', + 'status': 'success'}]}, + { 'id': 'pr8', + 'repoId': 'r1', + 'number': 8, + 'title': 'Refactor auth middleware', + 'description': '', + 'baseBranch': 'main', + 'compareBranch': 'feature', + 'status': 'open', + 'isDraft': False, + 'authorId': 'u1', + 'assignees': [], + 'labels': [], + 'milestone': None, + 'mergeStrategy': 'merge', + 'mergedAt': None, + 'mergedBy': None, + 'createdAt': '2026-06-01T00:00:00Z', + 'closedAt': None, + 'comments': [], + 'reviewers': [], + 'checks': [ { 'name': 'ci/build', + 'status': 'success'}, + { 'name': 'ci/test', + 'status': 'failure'}]}], + 'wiki': [], + 'actions': [], + 'notifications': [], + 'labels': [], + 'milestones': [], + 'discussions': [], + 'releases': []}, + 'jira_mock': { 'currentUser': { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + 'users': [ { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + { 'id': 'u2', + 'name': 'Jane Doe', + 'email': 'jane@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u2'}, + { 'id': 'u3', + 'name': 'John Smith', + 'email': 'john@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u3'}, + { 'id': 'u4', + 'name': 'Sarah Lee', + 'email': 'sarah@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u4'}], + 'projects': [ { 'id': 'p1', + 'key': 'KAN', + 'name': 'Kanban Project', + 'leadId': 'u1', + 'category': 'Software', + 'icon': 'https://picsum.photos/64/64?random=p1'}], + 'sprints': [ { 'id': 's1', + 'projectId': 'p1', + 'name': 'Sprint 1', + 'goal': 'Stabilize core', + 'startDate': '2026-06-01T12:00:00.000Z', + 'endDate': '2026-06-15T12:00:00.000Z', + 'state': 'active'}], + 'issues': [ { 'id': 'i1', + 'key': 'KAN-1', + 'projectId': 'p1', + 'summary': 'Set up project', + 'description': '', + 'type': 'Task', + 'status': 'Done', + 'priority': 'Low', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u1', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}, + { 'id': 'i3', + 'key': 'KAN-3', + 'projectId': 'p1', + 'summary': 'Webhook dispatcher reliability', + 'description': '', + 'type': 'Story', + 'status': 'In Progress', + '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': 'i4', + 'key': 'KAN-4', + 'projectId': 'p1', + 'summary': 'Auth middleware refactor', + 'description': '', + 'type': 'Story', + 'status': 'In Progress', + 'priority': 'Medium', + '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'}], + 'comments': [], + 'workflows': [ { 'id': 'w1', + 'name': 'Software Workflow', + 'transitions': [ { 'from': 'To Do', + 'to': ['In Progress']}, + { 'from': 'In Progress', + 'to': [ 'In Review', + 'To Do', + 'Done']}, + { 'from': 'In Review', + 'to': ['Done', 'In Progress']}, + { 'from': 'Done', + 'to': ['In Progress', 'To Do']}]}], + 'notifications': []}, + 'slack_mock': { 'currentUser': { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'workspace': { 'workspaceId': 'ws_1', + 'workspaceName': 'Acme Corp', + 'icon': ''}, + 'users': [ { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_2', + 'fullName': 'Sarah Johnson', + 'displayName': 'Sarah', + 'email': 'sarah.johnson@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_3', + 'fullName': 'Mike Chen', + 'displayName': 'Mike', + 'email': 'mike.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_4', + 'fullName': 'Lisa Park', + 'displayName': 'Lisa', + 'email': 'lisa.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}], + 'channels': [ { 'channelId': 'general', + 'name': 'general', + 'description': 'general channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + { 'channelId': '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': 'which of PR #7 / #8 can ' + 'we merge?', + '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_pr_mergeable_003/reward.py b/qa_pr_mergeable_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..279c9342467ad485e192f651b4add76d9212eb4e --- /dev/null +++ b/qa_pr_mergeable_003/reward.py @@ -0,0 +1,103 @@ +""" +Reward Script: se_pr_jira_slack_gate_b92 +Task ID: qa_pr_mergeable_003 +Domain: mock_websites +Mocks: github_mock, jira_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.45] KAN-3 (PR #7) moved to In Review + - [0.1] slack_new_msg + - [0.2] verdict names PR #7 as ready + - [0.25] explains #8 is blocked +""" +import re +import sys + +import requests + +MOCK_URLS = { + "github_mock": "http://28.7.184.198:8136", + "jira_mock": "http://28.7.184.198:8153", + "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 i3 status == 'In Review' +c0_iss = next((i for i in (cur('jira_mock').get('issues') or []) if i.get('id') == 'i3'), None) +if c0_iss and c0_iss.get('status') == 'In Review': + print('PASS: KAN-3 (PR #7) moved to In Review (0.45)') + total += 0.45 +else: + print('FAIL: KAN-3 (PR #7) moved to In Review (got ' + str(c0_iss.get('status') if c0_iss else 'missing') + ')') + +# c1: new message by user_1 in #engineering +c1_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c1_seed = set(SEED.get('slack_mock:engineering', [])) +c1_new = [m for m in c1_msgs if m.get('messageId') not in c1_seed and m.get('senderId') == 'user_1'] +c1_blob = _lc(' '.join((m.get('content') or '') for m in c1_new)) +if c1_new: + print('PASS: new message by user_1 in #engineering (0.1)') + total += 0.1 +else: + print('FAIL: no new user_1 message in #engineering') + +# c2: slack #engineering contains (verdict names PR #7 as ready) +c2_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c2_seed = set(SEED.get('slack_mock:engineering', [])) +c2_blob = _lc(' '.join((m.get('content') or '') for m in c2_msgs if m.get('messageId') not in c2_seed and m.get('senderId') == 'user_1')) +if all(t in c2_blob for t in ['#7']): + print('PASS: verdict names PR #7 as ready (0.2)') + total += 0.2 +else: + print('FAIL: verdict names PR #7 as ready') + +# c3: slack #engineering contains (explains #8 is blocked) +c3_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c3_seed = set(SEED.get('slack_mock:engineering', [])) +c3_blob = _lc(' '.join((m.get('content') or '') for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1')) +if any(t in c3_blob for t in ['#8 is blocked', '#8 blocked', '8 is blocked', 'failing', 'no approval', 'not approved']): + print('PASS: explains #8 is blocked (0.25)') + total += 0.25 +else: + print('FAIL: explains #8 is blocked') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/qa_pr_mergeable_003/reward_label.json b/qa_pr_mergeable_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..964847db7c104bcf20c55a83475e8d8b7a573f51 --- /dev/null +++ b/qa_pr_mergeable_003/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/7de46c0e-2c81-5326-8689-2ad8412cc844/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:45", + "label": { + "task_id": "qa_pr_mergeable_003", + "domain": "mock_websites", + "summary": "验证 JIRA 中 KAN-3 是否移至 In Review,并检查 Slack #engineering 频道中 user_1 的新消息是否提及 PR #7 已就绪及 PR #8 被阻塞", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "github_mock", + "jira_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1: KAN-3 (PR #7) moved to In Review", + "weight": 0.45, + "description": "检查 JIRA 中 issue KAN-3(内部 id 为 i3)的状态是否已更新为 In Review", + "check_logic": "从 jira_mock 的 current_state.issues 列表中查找 id == 'i3' 的 issue,判断其 status 字段是否等于 'In Review'", + "pass_condition": "c0_iss 存在且 c0_iss.get('status') == 'In Review'" + }, + { + "name": "Component 2: slack_new_msg", + "weight": 0.1, + "description": "检查 Slack #engineering 频道中是否有 user_1 发送的新消息", + "check_logic": "获取 slack_mock current_state.messages.engineering,排除 SEED 中已有的消息(messageId 不在 seed 中),筛选 senderId == 'user_1' 的消息,判断列表是否非空", + "pass_condition": "存在至少一条 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息" + }, + { + "name": "Component 3: verdict names PR #7 as ready", + "weight": 0.2, + "description": "检查 Slack #engineering 中 user_1 的新消息内容是否提到 PR #7", + "check_logic": "将 #engineering 中 user_1 的所有新消息内容转为小写后拼接为字符串 c2_blob,使用 all(t in c2_blob for t in ['#7']) 判断是否包含子串 '#7'", + "pass_condition": "c2_blob 包含 '#7'" + }, + { + "name": "Component 4: explains #8 is blocked", + "weight": 0.25, + "description": "检查 Slack #engineering 中 user_1 的新消息内容是否解释 PR #8 被阻塞", + "check_logic": "将 #engineering 中 user_1 的所有新消息内容转为小写后拼接为字符串 c3_blob,使用 any() 判断是否包含任一关键词:'#8 is blocked'、'#8 blocked'、'8 is blocked'、'failing'、'no approval'、'not approved'", + "pass_condition": "c3_blob 包含上述任一子串" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数直接相加得到 total,最终通过 min(total, 1.0) 将总分钳制在 1.0 上限,再使用 round(..., 4) 保留四位小数作为最终 REWARD", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并 sys.exit(0),输出 REWARD: 0.0", + "从任一 mock 服务(github_mock、jira_mock、slack_mock)拉取 current_state 失败:打印 CRITICAL 并 sys.exit(0),输出 REWARD: 0.0", + "KAN-3 状态不是 In Review 或 issue 缺失:Component 1 不得分", + "#engineering 中无 user_1 新消息:Component 2 不得分", + "user_1 新消息拼接内容中不包含 '#7':Component 3 不得分", + "user_1 新消息拼接内容中不包含任何阻塞相关关键词:Component 4 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后依次向 github_mock、jira_mock、slack_mock 请求当前状态并缓存到 STATES 字典,任一请求失败也直接返回 0.0。评分分为四部分:第一,在 jira_mock 的 issues 中查找 id 为 'i3' 的 issue,若其 status 为 'In Review' 则加 0.45;第二,在 slack_mock #engineering 频道中排除 SEED 初始消息后,检查是否存在 senderId 为 'user_1' 的新消息,存在则加 0.1;第三,将 user_1 在 #engineering 的所有新消息内容小写拼接,若包含 '#7' 则加 0.2;第四,同一消息内容若包含 '#8 is blocked'、'failing'、'no approval'、'not approved' 等任一关键词则加 0.25。各组件得分累加后,通过 min(total, 1.0) 防止超分,最后四舍五入到小数点后四位输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 看是 `se_pr_jira_slack_gate_b92`,但用户文件路径中包含 `7de46c0e-2c81-5326-8689-2ad8412cc844`,docstring 中也写了 Task ID: 7de46c0e-2c81-5326-8689-2ad8412cc844。根据要求\"从文件 docstring 中提取的任务 ID\",docstring 中明确写了 `Task ID: 7de46c0e-2c81-5326-8689-2ad8412cc844`,所以 task_id 应该是这个 UUID。不过等等,docstring 第一行是 `Reward Script: se_pr_jira_slack_gate_b92`,然后第三行是 `Task ID: 7de46c0e-2c81-5326-8689-2ad8412cc844`。要求说\"如 se_review_006\",但这里 docstring 明确给了 Task ID 字段,所以应该用 `7de46c0e-2c81-5326-8689-2ad8412cc844`。但是等等,通常 task_id 可能是 se_pr_jira_slack_gate_b92?让我再看要求:\"从文件 docstring 中提取的任务 ID,如 se_review_006;若无法确定则填 null\"。docstring 中有 `Task ID: 7de46c0e-2c81-5326-8689-2ad8412cc844`,所以应该用这个。\n\n2. **Domain**: docstring 中 `Domain: mock_websites`\n\n3. **Summary**: 一句话概括。这个脚本验证 JIRA 中 KAN-3 (PR #7) 是否移动到 In Review,以及 Slack #engineering 频道中 user_1 是否发送了新消息,消息中是否提到 PR #7 已就绪,以及是否解释 PR #8 被阻塞。\n\n4. **is_placeholder**: false,因为脚本有实际的检查逻辑。\n\n5. **data_sources**: `github_mock`, `jira_mock`, `slack_mock`, `/tmp/task_web_sid`\n\n6. **scoring_components**:\n - Component 1: KAN-3 (PR #7) moved to In Review, weight 0.45\n - check_logic: 从 jira_mock 的 current_state 中查找 issues 列表里 id 为 'i3' 的 issue,检查其 status 是否等于 'In Review'\n - pass_condition: c0_iss 存在且 c0_iss.get('status') == 'In Review'\n - Component 2: slack_new_msg, weight 0.1\n - check_logic: 从 slack_mock 的 current_state.messages.engineering 中获取消息,排除 SEED 中已有的消息(messageId 不在 seed 中),且 senderId 为 'user_1',存在这样的新消息则通过\n - pass_condition: c1_new 列表非空(存在 messageId 不在 seed 中且 senderId 为 'user_1' 的消息)\n - Component 3: verdict names PR #7 as ready, weight 0.2\n - check_logic: 从 slack_mock #engineering 中筛选出 user_1 发送的新消息(排除 seed),将所有内容转为小写拼接成字符串,检查是否包含 '#7'\n - pass_condition: c2_blob 包含 '#7'\n - Component 4: explains #8 is blocked, weight 0.25\n - check_logic: 同上,检查小写拼接后的字符串是否包含任一关键词:'#8 is blocked', '#8 blocked', '8 is blocked', 'failing', 'no approval', 'not approved'\n - pass_condition: c3_blob 包含上述任一子串\n\n7. **total_max_score**: 1.0\n\n8. **score_aggregation**: 各组件分数相加,最后用 min(total, 1.0) 钳制到上限 1.0,再 round 到 4 位小数。\n\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并退出,REWARD: 0.0\n - 从任一 mock 服务拉取状态失败:打印 CRITICAL 并退出,REWARD: 0.0\n - 各组件检查失败时仅不加分,不会提前退出(除了前面的 critical)\n\n10. **scoring_logic_explanation**: 详细中文解释,按执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0\n - 然后向 github_mock、jira_mock、slack_mock 发送请求获取当前状态,失败则返回 0.0\n - 检查 jira_mock 中 issue id 为 i3(KAN-3)的状态是否为 'In Review',通过加 0.45\n - 检查 slack_mock #engineering 频道中是否有 user_1 发送的新消息(排除 seed 消息),通过加 0.1\n - 检查 slack_mock #engineering 中 user_1 的新消息内容(小写拼接后)是否包含 '#7',通过加 0.2\n - 检查 slack_mock #engineering 中 user_1 的新消息内容(小写拼接后)是否包含 '#8 is blocked' 等关键词,通过加 0.25\n - 汇总分数,用 min(total, 1.0) 限制上限,四舍五入到 4 位小数输出\n\n11. **confidence**: 1.0\n\n等等,我需要再仔细看看 c2 和 c3 的逻辑。c2 和 c3 都检查 user_1 的新消息,但 c2 的 blob 是 `_lc(' '.join(...))`,c3 也是。注意 c2 的条件是 `all(t in c2_blob for t in ['#7'])`,这实际上就是 `['#7']` 中所有元素都在 c2_blob 中,等价于 `'#7' in c2_blob`。c3 是 `any(...)`。\n\n另外注意 c1 检查的是新消息(排除 seed),c2 和 c3 也是排除 seed 的。但 c1 要求 senderId == 'user_1',c2 和 c3 也要求 senderId == 'user_1'。\n\n还有一个细节:c1 的 pass condition 是 c1_new 非空,但 c1_blob 也计算了,只是没用于条件判断。实际上 c1 只要有新消息就加分,不管内容。\n\nc2 和 c3 检查的是所有 user_1 新消息拼接后的内容。\n\n让我确认一下 task_id。docstring 中:\n```\nReward Script: se_pr_jira_slack_gate_b92\nTask ID: 7de46c0e-2c81-5326-8689-2ad8412cc844\n```\n要求说\"从文件 docstring 中提取的任务 ID,如 se_review_006\"。这里 docstring 明确有 \"Task ID: 7de46c0e-2c81-5326-8689-2ad8412cc844\",所以应该用 UUID。虽然文件名中也有这个 UUID,但 docstring 明确标注了 Task ID。\n\ndomain 是 mock_websites。\n\nis_placeholder: false\n\ndata_sources: 脚本从 /tmp/task_web_sid 读取会话 ID,从 github_mock、jira_mock、slack_mock 获取状态。虽然 github_mock 获取了状态,但评分中并没有使用 github_mock 的数据。不过 data_sources 应该列出脚本获取状态的数据源。\n\nscoring_components 的 weight 就是 docstring 和代码中显式给出的:0.45, 0.1, 0.2, 0.25。\n\nfailure_modes:\n- /tmp/task_web_sid 读取失败或为空\n- mock 状态获取失败(任一)\n- 各检查项失败(不加分)\n\nscore_aggregation: 各组件分数相加,最终用 min(total, 1.0) 钳制到上限,再 round(..., 4)。\n\nconfidence: 1.0\n\n确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我再检查一下 c0 的 issue id。代码中是 `i.get('id') == 'i3'`,但 docstring 说是 KAN-3。代码中检查的是 id 为 'i3' 的 issue。\n\nc2 的 check_logic: `all(t in c2_blob for t in ['#7'])` - 虽然用 all,但列表只有一个元素 '#7'。\n\nc3 的 check_logic: `any(t in c3_blob for t in ['#8 is blocked', '#8 blocked', '8 is blocked', 'failing', 'no approval', 'not approved'])`\n\n好的,开始构造 JSON。\n\n注意:所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\nsummary 用中文。\n\nscoring_logic_explanation 用中文。\n\ncheck_logic 和 pass_condition 中涉及代码标识符的保留原样。\n\n让我再确认一下 data_sources。代码中确实请求了 github_mock,但评分没用到。不过 \"脚本从哪些数据源/mock 服务/文件获取状态\",所以应该包括 github_mock。\n\n最终输出应该是一个合法的 JSON。 {\"task_id\":\"7de46c0e-2c81-5326-8689-2ad8412cc844\",\"domain\":\"mock_websites\",\"summary\":\"验证 JIRA 中 KAN-3 是否移至 In Review,并检查 Slack #engineering 频道中 user_1 的新消息是否提及 PR #7 已就绪及 PR #8 被阻塞\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"github_mock\",\"jira_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 1: KAN-3 (PR #7) moved to In Review\",\"weight\":0.45,\"description\":\"检查 JIRA 中 issue KAN-3(内部 id 为 i3)的状态是否已更新为 In Review\",\"check_logic\":\"从 jira_mock 的 current_state.issues 列表中查找 id == 'i3' 的 issue,判断其 status 字段是否等于 'In Review'\",\"pass_condition\":\"c0_iss 存在且 c0_iss.get('status') == 'In Review'\"},{\"name\":\"Component 2: slack_new_msg\",\"weight\":0.1,\"description\":\"检查 Slack #engineering 频道中是否有 user_1 发送的新消息\",\"check_logic\":\"获取 slack_mock current_state.messages.engineering,排除 SEED 中已有的消息(messageId 不在 seed 中),筛选 senderId == 'user_1' 的消息,判断列表是否非空\",\"pass_condition\":\"存在至少一条 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息\"},{\"name\":\"Component 3: verdict names PR #7 as ready\",\"weight\":0.2,\"description\":\"检查 Slack #engineering 中 user_1 的新消息内容是否提到 PR #7\",\"check_logic\":\"将 #engineering 中 user_1 的所有新消息内容转为小写后拼接为字符串 c2_blob,使用 all(t in c2_blob for t in ['#7']) 判断是否包含子串 '#7'\",\"pass_condition\":\"c2_blob 包含 '#7'\"},{\"name\":\"Component 4: explains #8 is blocked\",\"weight\":0.25,\"description\":\"检查 Slack #engineering 中 user_1 的新消息内容是否解释 PR #8 被阻塞\",\"check_logic\":\"将 #engineering 中 user_1 的所有新消息内容转为小写后拼接为字符串 c3_blob,使用 any() 判断是否包含任一关键词:'#8 is blocked'、'#8 blocked'、'8 is blocked'、'failing'、'no approval'、'not approved'\",\"pass_condition\":\"c3_blob 包含上述任一子串\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数直接相加得到 total,最终通过 min(total, 1.0) 将总分钳制在 1.0 上限,再使用 round(..., 4) 保留四位小数作为最终 REWARD\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并 sys.exit(0),输出 REWARD: 0.0\",\"从任一 mock 服务(github_mock、jira_mock、slack_mock)拉取 current_state 失败:打印 CRITICAL 并 sys.exit(0),输出 REWARD: 0.0\",\"KAN-3 状态不是 In Review 或 issue 缺失:Component 1 不得分\",\"#engineering 中无 user_1 新消息:Component 2 不得分\",\"user_1 新消息拼接内容中不包含 '#7':Component 3 不得分\",\"user_1 新消息拼接内容中不包含任何阻塞相关关键词:Component 4 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后依次向 github_mock、jira_mock、slack_mock 请求当前状态并缓存到 STATES 字典,任一请求失败也直接返回 0.0。评分分为四部分:第一,在 jira_mock 的 issues 中查找 id 为 'i3' 的 issue,若其 status 为 'In Review' 则加 0.45;第二,在 slack_mock #engineering 频道中排除 SEED 初始消息后,检查是否存在 senderId 为 'user_1' 的新消息,存在则加 0.1;第三,将 user_1 在 #engineering 的所有新消息内容小写拼接,若包含 '#7' 则加 0.2;第四,同一消息内容若包含 '#8 is blocked'、'failing'、'no approval'、'not approved' 等任一关键词则加 0.25。各组件得分累加后,通过 min(total, 1.0) 防止超分,最后四舍五入到小数点后四位输出。\",\"confidence\":1.0}" +} diff --git a/raw/evaluation_examples/OSWorker/README.md b/raw/evaluation_examples/OSWorker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..732f618f6f849a10a43f2ed2e65caf542e101fe1 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/README.md @@ -0,0 +1,324 @@ +# OSWorker Benchmark Task Suite + +The canonical OSWorker release contains **100 realistic desktop tasks** spanning +**10 high-level job families** and **17 operational tracks**. The suite is +deliberately cross-application: 99% of tasks require more than one application, +with a mean of 3.26 and a median of 3 applications per task. Evaluators check a +mean of 4.86 task milestones, providing substantially richer verification than +a single final-state assertion. + +## 📊 Benchmark Tasks Overview + +

+ OSWorker Benchmark distributions by job family, applications per task, most frequent applications, and evaluator checkpoints +

+ +

+ Figure 1. Coverage across job families, application breadth, frequently used applications, and evaluator depth. +

+ +The figure groups the benchmark into 10 reader-facing job families; the +directory and task-id organization below uses the finer-grained 17-track +vocabulary. Slack, Gmail, Google Sheets, Salesforce, and Google Calendar are the +most frequent applications, while the long tail covers productivity, +engineering, finance, design, and compliance workflows. + +The rest of this document is the normative specification for **task ids**, +**task-config fields**, and the external **cache layout**. Task configurations +are distributed with the repository. `osworker_cache/`, which contains runtime +assets and evaluator scripts, is supplied separately and is not tracked in Git. +Before running the benchmark, ensure that the cache contains a same-named +subdirectory for every task id in `osworker_benchmark_full.json`. + +## Non-negotiable naming rules: exact agreement in four locations and a derivable domain + +For a given task, the names in the following **four locations must match exactly**, including case: + +``` +id in meta == examples filename (without .json) == "id" inside config == cache subdirectory name +``` + +- Meta: `osworker_benchmark_full.json`, with the structure `{track: [task_id, ...]}` +- Task: `examples/{track}/{task_id}.json` +- Cache: `{cache_dir}/{task_id}/` (defaults to `osworker_cache/` and contains `initial_setup.py` / `reward.py` / `_cua_gym_vm_bridge.sh`) + +**Fifth rule: `domain` == the first segment of the id (the track).** Therefore, `ar_aging_001` must be under `examples/ar/`, +its cache must be at `osworker_cache/ar_aging_001/`, and it must be listed under the `"ar"` key in meta. +Every location can therefore be derived from the id without consulting a lookup table. + +Each id must be globally unique; domain-based disambiguation is not allowed. The runner's retry logic locates results at +`**/{domain}/{task_id}/result.txt`, so same-named tasks would overwrite each other. + +## Directory structure + +``` +evaluation_examples/OSWorker/ +├── README.md +├── osworker_benchmark_full.json # meta, {track: [id...]}, 17 tracks / 100 tasks +└── examples/{track}/{id}.json # active tasks, in one-to-one correspondence with meta +``` + +The corresponding external cache is located at `osworker_cache/{id}/`. When retiring a task, remove it from `examples/`, meta, +and the external cache at the same time. If it is re-enabled, restore it with its original id. + +## id grammar + +``` +task_id := "_" "_" * + +track := controlled vocabulary (see below), [a-z][a-z0-9]{1,7} +capability := 1-4 snake_case words, [a-z][a-z0-9]*(_[a-z0-9]+){0,3} +seq := exactly 3 digits, increasing within (not within track_capability) +modifier := "__v" | "__long" | "__cond" +``` + +The character set is restricted to `[a-z0-9_]`. **Uppercase letters, Chinese characters, spaces, `-`, `.`, and `,` are prohibited.** + +| Component | Rule | Examples | +|---|---|---| +| `track` | Business-role or capability track, selected from the controlled vocabulary | `ae` `csm` `ar` | +| `capability` | What the task tests, expressed as a verb-object or noun phrase | `forecast` `email_to_crm_case` | +| `seq` | Three-digit serial number within the track; increases monotonically and is never reused | `001` `042` | +| `__vN` | Variant N, a rewrite of the same underlying task | `__v1` `__v2` | +| `__long` | Long-horizon task; see the criteria below | | +| `__cond` | Conditional task whose prompt contains branches that require different paths depending on the condition | | + +### Criteria for `__long` + +A task is long-horizon if it meets **any** of the following criteria: + +1. **Coordination across three or more applications** — data must be read and written while moving between multiple applications or tabs +2. **Repetition of the same operation across multiple objects** — for example, "apply the same edit to five files in sequence" or "create one ticket for every record" +3. **A single operation chain exceeding approximately 20 steps** + +Do not classify a task from the length of its instruction. A long instruction may simply provide detailed background and need not imply many actual operation steps. + +Modifiers begin with a **double underscore** `__`, distinguishing them from the single underscores in the main id. As a result, `ar_payment_002` and +`ar_payment_002__v1` can be split unambiguously with a regular expression. Append multiple modifiers in this order: `__vN` → `__long` → `__cond`. + +Complete examples: + +``` +ae_pipeline_review_004 # Task 4 in the AE track, a pipeline review +csops_incident_command_004 # Task 4 in the CS Ops track, incident command +calc_income_statement_001__long # Task 1 in the Calc track, batch editing five files +ops_pdf_mail_012__long__cond # Task 12 in the Ops track, long-horizon + conditional branch +``` + +## Controlled vocabulary for tracks + +Register a new track in this table before using it to prevent synonymous abbreviations such as `recruit` and `recruiting` from coexisting. +The numbers in parentheses are the current task counts. + +| track | Meaning | track | Meaning | +|---|---|---|---| +| `ae` | Account Executive, sales (4) | `pm` | Product / Project Manager (3) | +| `am` | Account Manager, customer renewals (4) | `qa` | Quality Assurance / code review (4) | +| `ar` | Accounts Receivable, receivables / reconciliation (12) | `recruit` | Recruiting (8) | +| `csm` | Customer Success Manager (5) | `sdr` | Sales Development Rep (6) | +| `csops` | Customer Support Ops (6) | `sre` | Site Reliability / on-call (3) | +| `hr` | Human Resources (9) | `ops` | General business operations (12) | +| `itops` | IT support / system administration / access control (4) | `calc` | LibreOffice Calc batch spreadsheet operations (5) | +| `mktg` | Marketing (11) | `img` | GIMP batch image processing (2) | +| `fin` | Expense reimbursement (2) | | | + +The first 13 tracks are organized by **business role**. The remaining four (`ops` / `calc` / `img` / `fin`) cover scenarios without a clear role. +`ops` is the catch-all track: small categories containing a single task, such as the former one-task categories for document conversion, transcripts, and license auditing, must be merged into +`ops`. Do not create a new track for a single task. + +**Do not introduce opaque numbers such as `profNN`.** Historical identifiers such as `prof13` and `prof26` were internal role numbers +that conveyed no information to readers. During the 2026-08 renaming, they were assigned to the tracks above according to the role stated in each task prompt. + +## id freezing policy + +**Once a task has been added to meta and run, its id is frozen.** To change the task prompt, publish a new `__vN` variant +instead of changing the id in place. Keep the id unchanged when retiring a task, and restore it unchanged if the task is re-enabled. + +The reason is that **id is the primary key across runs.** Renaming prevents `get_unfinished_tasks()` from recognizing historical results, +forces the entire suite to rerun from scratch, and causes analysis scripts for historical runs to miss every path because they still use the old id. +The gamedev suite under `evaluation_examples/democua` has already encountered this problem; see the README in that directory. + +### One-time renaming (2026-08) + +When this specification was introduced, all 100 active tasks underwent a **one-time renaming** that normalized five historical forms to the grammar above: + +| Previous form | Count | Current form | +|---|---|---| +| Bare uuid (`054e615f-1839-…`) | 46 | Assigned to tracks according to task semantics | +| uuid + `_5` (upstream long tasks, including one malformed uuid) | 9 | `calc_*__long` / `img_*__long` / `ops_*__long` | +| `c0nd…` (the first four uuid characters rewritten) | 3 | `fin_*__long__cond` / `ops_*__long__cond` | +| `profNN_*` (opaque role number) | 14 | Assigned to tracks according to the role stated in the task prompt | +| Semantic ids with disordered seq values | 28 | Resequenced contiguously from 001 within each track | + +This was **an exception, not a precedent**. As a consequence, all earlier run result directories use the old ids and cannot be resumed directly. +The historical id mapping was a one-time migration artifact and is not distributed with the active task set. + +**The renaming deliberately left two categories of external references untouched.** Their paths embed old ids but point to off-site resources: + +- Hugging Face URLs in 12 task configs, such as + `…/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-…_5/source_file/IncomeStatement2_1.xlsx` +- The `trajectory` fields in the same 12 tasks + +Changing either category would immediately produce 404 errors. **Any bulk id-renaming operation must therefore update fields precisely at the JSON-structure level +and must never perform a full-text string replacement over a config.** + +In addition, `evaluation_examples/democua/osworker_benchmark_democua` (33 tasks) contains tasks from the +same source as this directory, each paired with a recorded demo. Those tasks were renamed alongside this +migration, so their ids match the ids used here. + +## task config format + +Task configs are stored at `examples/{track}/{id}.json`. **Only four fields are actually consumed at runtime**: `id`, `instruction`, +`config`, and `evaluator`. Inherited tasks additionally use native OSWorld fields such as `snapshot`, `related_apps`, and `proxy`. +`app_type` / `difficulty` / `_source` / `instruction_zh` / `persona` / `context` have no runtime readers and are purely metadata. +The metadata may therefore be reorganized freely, but **the names and types of the four fields above must not change**. + +```json +{ + "id": "ae_pipeline_review_004", + "domain": "ae", + "app_type": "salesforce_mock,google_sheets_mock,slack_mock", + "difficulty": "medium", + "instruction": "English task description; this is exactly what the agent sees", + "instruction_zh": "Optional Chinese-language reference translation", + + "config": [], + "evaluator": {}, + + "_provenance": { + "pipeline": "cua_gym", + "generated_at": "2026-06-24T20:59:28", + "adversarial_rounds": 1, + "persona": null, + "context": null + } +} +``` + +| Field | Required | Description | +|---|---|---| +| `id` | Yes | See "Non-negotiable naming rules"; must match the filename, meta entry, and cache directory name | +| `domain` | Yes | == containing directory name == first id segment (track) | +| `app_type` | No | Comma-separated applications actually used by the task. **Its responsibility differs from `domain`**: `domain` answers "how is this categorized?", while `app_type` answers "which applications are used?" | +| `instruction` | Yes | **Must be a string.** `desktop_env.py` directly accesses `task_config["instruction"]`; changing it to an object causes a crash | +| `instruction_zh` | No | Chinese-language reference translation | +| `difficulty` | No | `easy` / `medium` / `hard` | +| `config` | Yes | Array of setup steps | +| `evaluator` | Yes | Scoring definition | +| `_provenance` | No | Generation-process metadata. **Replaces the scattered `_source` / `source` / `generated_at` / `adversarial_rounds` / `persona` / `context` fields** | + +`domain` and `app_type` originally overlapped semantically because both stored application combinations. The 2026-08 renaming established distinct responsibilities: +`domain` was narrowed to the track, while `app_type` exclusively carries application information. The 12 inherited tasks that originally lacked `app_type` +were populated from their previous directory names during the renaming so that application information would not disappear with those directories. + +The leading underscore in `_provenance` indicates that it is not task-prompt content and does not affect scoring, making it immediately distinguishable from prompt fields. + +## cache directory format + +The cache path is `osworker_cache/{task_id}/`. The three-file set retains its existing names because renaming it would require synchronized updates to 264 `local_path` occurrences in configs, +and the benefit would not justify the risk: + +``` +osworker_cache/{task_id}/ +├── initial_setup.py # initialization inside the VM +├── reward.py # scoring inside the VM +├── _cua_gym_vm_bridge.sh # VM bridge +├── assets/ # task assets +│ ├── IncomeStatement2.xlsx +│ └── gold/ # reference answers +│ └── IncomeStatement2_1.xlsx +└── _meta/ + └── reward_label.json # generation audit; not used at runtime +``` + +Asset names follow three rules: + +1. **Do not use a uuid prefix.** Existing prefixes such as `_IncomeStatement2_1.xlsx` serve no purpose: + each file is already inside its `{task_id}/` directory, so cross-task filename collisions cannot occur. +2. **Store all reference answers under `assets/gold/`**, retiring the two coexisting `_gt1_` and `_gold_` suffix conventions. +3. **Keep only one copy of each asset.** Existing cases include `photo_1.png` and `_photo_1.png` coexisting despite having identical content. + +Subdirectories are safe: `_upload_cache_file_setup` resolves a relative `local_path` with `os.path.join(cache_dir, local_path)`, +so hierarchical paths such as `assets/gold/x.xlsx` are supported natively. **No runtime code changes are required**; only the corresponding +`local_path` in the config must be updated at the same time. + +**Do not store task prompts in the cache directory.** The sole authoritative copy of a task prompt is `examples/{track}/{id}.json`. +See the first item under "Pending work" below for the rationale. + +## Validation rules + +After adding or modifying a task, verify all of the following: + +1. `config["id"]` == filename without `.json` +2. `config["domain"]` == containing directory name +3. **The first id segment (track) == containing directory name** — the location is derivable from the id +4. Every id in meta has a corresponding JSON file under `examples/{track}/` +5. Every id in meta has a corresponding subdirectory in the cache directory +6. The id matches `^[a-z][a-z0-9]{1,7}(_[a-z0-9]+){1,4}_\d{3}(__v\d+)?(__long)?(__cond)?$` +7. `track` appears in the controlled vocabulary above — the regular expression cannot reject opaque numbers such as `prof13`, so the table must be checked +8. Within each track, seq values are contiguous from 001 and do not repeat +9. Every id in the task set is globally unique + +Rules 4 and 5 are **hard constraints**. `scripts/osworker_benchmark/start_osworker_benchmark_test.sh` validates them at startup +and fails fast if either is violated. The remaining rules are enforced through review. + +## Current compliance status + +The active task set contains 100 tasks. Its ids are globally unique, and its naming, tracks, and `config.domain` values are all 100% compliant. +Of these tasks, 45 include `__long`, and 3 include `__cond`. + +Before the 2026-08 renaming, the `examples/` tree contained the following deviations: 20 `profNN_*` tasks, 2 uses of the `_v2` form, +`pm_002` without a capability, 1 malformed uuid, and 55 `config.domain` values that did not match their directory names. All have been corrected. + +## Completed cleanup + +### 38 obsolete task-prompt copies (deleted) + +The cache directories for 19 tasks previously contained two copies of each prompt, `task.json` and `{task_id}.json`. +Comparison against the authoritative versions under `examples/` confirmed that they could be deleted safely: + +- **28 copies** from 14 active tasks differed only in the mock endpoint IP: the authoritative versions use `mock-host.example`, + while the copies still used the retired `old-mock-host.example` + +The substantive content of the key `id` / `instruction` / `config` / `evaluator` fields had no differences; every copy was verified individually before deletion. + +The cause is worth preserving: the scope of `sync_mock_endpoints_v2.py` includes `initial_setup.py` / `reward.py` / +`_cua_gym_vm_bridge.sh` and task JSON files under `examples/`, but **task-prompt copies in cache directories are a blind spot**. +Consequently, none of the endpoint migrations updated those copies. This is the origin of the rule prohibiting task prompts in cache directories. + +### 7 `__pycache__` directories (deleted) + +`.gitignore` already contained `__pycache__/` rules on lines 14 and 283, but these directories had been tracked before the rules took effect. +gitignore rules do not affect tracked files, so the directories had to be deleted explicitly. + +### domain regrouping (2026-08) + +Before regrouping, **49 domains contained 100 tasks, and 39 of those domains (80%) contained only one task**. The median was 1 task, +while the largest domain, `mock_websites`, contained 21. The names also mixed four styles. The longest domain name had 76 characters and contained commas +(`democua_hubspot_marketing_mock,google_docs_mock,google_drive_mock,slack_mock`), +which make paths inconvenient to use with both glob and shell. + +The root cause was that three classification dimensions occupied the same level: application combinations (30), individual applications (11), and scenarios (8). + +The taxonomy has now been normalized to **17 tracks**, each containing 2–12 tasks, with a median of 4. `config.domain` was synchronized according to the rules above +so that all 100 values match their directory names, and `app_type` was populated for the 12 inherited tasks. + +## Pending work + +The following deviations **have not yet been addressed**. They are hygiene issues and do not affect benchmark scores. + +| Issue | Count | Description | +|---|---|---| +| Duplicate assets (approximately 5.8 MB) | 10 | In the `img_brightness_001__long` and `img_contrast_002__long` directories, `photo_N.png` and `_photo_N.png` have identical MD5 hashes. **Retention has been confirmed; no action will be taken** | +| Assets with meaningless uuid prefixes | Most | See rule 1 under "cache directory format" | +| Coexisting `_gt1_` / `_gold_` reference-answer naming conventions | — | Should be standardized under `assets/gold/` | +| Assets not collected under the `assets/` subdirectory | — | See "cache directory format"; the config's `local_path` must be updated at the same time | +| Four coexisting config schemas | 100 | One schema each for 42 / 33 / 13 / 12 tasks; `_provenance` has not yet been implemented. See "task config format" | +| Excessive variety in cache file combinations | 100 | The standard three-file set covers 88/100 tasks; the remaining 12 are `.PLACEHOLDER`-style inherited OSWorld tasks | + +Note that the "cache directory format" and "task config format" sections describe the **target state**. Only the id and +domain portions have currently been implemented; the cache layout and config schema have not yet been remediated. diff --git a/raw/evaluation_examples/OSWorker/examples/ae/ae_contract_signature_001.json b/raw/evaluation_examples/OSWorker/examples/ae/ae_contract_signature_001.json new file mode 100644 index 0000000000000000000000000000000000000000..5569b49c67d8e0834a7e6020ac22dda37816483f --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ae/ae_contract_signature_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "The Globex Platform Expansion deal just closed-won, so let's get the order form out for signature. In Salesforce, find the closed-won Globex opportunity and confirm the customer contact. Then add a row to the Notion 'Contracts' tracker with Customer 'Globex Corporation', Deal 'Globex Platform Expansion', Amount 120000, and Status 'Sent'. Create a DocuSign envelope titled for the Globex Platform Expansion order form addressed only to that contact as the signer, and send it. Once it's sent, log the envelope on the Salesforce opportunity and drop a note in the Slack #deal-desk channel with the customer, the deal amount, and that we're awaiting signature. Only do this for the deal that actually closed-won.", + "instruction_zh": "Globex Platform Expansion 交易刚刚已成交,请将订单表格发出以供签署。在 Salesforce 中,找到已成交的 Globex 商机并确认客户联系人。然后在 Notion 的 'Contracts' 追踪表中添加一行,Customer 填 'Globex Corporation',Deal 填 'Globex Platform Expansion',Amount 填 120000,Status 填 'Sent'。创建一个 DocuSign 信封,标题设为 Globex Platform Expansion 订单表格,并且只将该联系人添加为签署人,然后发送。发送后,将该信封记录到 Salesforce 商机中,并在 Slack 的 #deal-desk 频道中发布一条备注,内容包括客户名称、交易金额以及我们正在等待签署。仅对实际已成交的交易执行此操作。", + "id": "ae_contract_signature_001", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:10:09.906202", + "adversarial_rounds": "1", + "domain": "ae", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ae/ae_deal_handoff_002__long.json b/raw/evaluation_examples/OSWorker/examples/ae/ae_deal_handoff_002__long.json new file mode 100644 index 0000000000000000000000000000000000000000..9485a8711fef5604c324494e7ddace1f6d9bc01a --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ae/ae_deal_handoff_002__long.json @@ -0,0 +1,77 @@ +{ + "id": "ae_deal_handoff_002__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nToday is 2026-06-29. Sales just closed a batch of deals -- hand off every qualifying opportunity in Salesforce to the delivery team. An opportunity qualifies only if its stage is Closed Won AND it is NOT already owned by 'Delivery Lead' (opps still in Negotiation or already owned by Delivery Lead should be skipped). For every qualifying opportunity, first reassign its Owner to 'Delivery Lead' in Salesforce. Then classify by amount and take these actions:\n - Tier-1 (amount >= $100,000): also log a follow-up Task titled 'Kickoff - ' on the opportunity's Activity Timeline; add a Trello card 'Handoff: ' to the 'Delivery Queue' list of the 'Delivery Handoffs' board with the 'Tier-1' label and a due date of 2026-07-02; apply the 'Handoff' label to the account contact's inbound email in Gmail; and send that contact a kickoff email with subject 'Kickoff for '.\n - Tier-2 ($25,000..$99,999): add a Trello card 'Handoff: ' with the 'Tier-2' label and a due date of 2026-07-04. No task, no email.\n - Tier-3 (< $25,000): add a Trello card 'Handoff: ' with the 'Tier-3' label and a due date of 2026-07-06. No task, no email.\nFinally, post a one-line summary to the Slack '#delivery' channel that includes how many opportunities you handed off, and pin that message.", + "app_type": "salesforce_mock,trello_mock,gmail_mock,slack_mock", + "domain": "ae", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/ae/ae_pipeline_hygiene_003.json b/raw/evaluation_examples/OSWorker/examples/ae/ae_pipeline_hygiene_003.json new file mode 100644 index 0000000000000000000000000000000000000000..da02f1d3a9a3989046a90219d2cb5ed695de34b4 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ae/ae_pipeline_hygiene_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "It's the end-of-month pipeline review. Go through my Salesforce opportunities and find the open deals whose close date is before 2026-06-20, then push each of those overdue close dates out to 2026-07-31. Capture only those overdue open deals (with their old and new close dates, amounts and owner) in the Notion 'Pipeline Hygiene' table; if draft rows for opportunities are already present, fill the overdue rows instead of adding new ones. Check DocuSign for the closed-won Hooli deal and note whether its agreement is fully signed yet. Then email my manager a recap of what you rescheduled, and post a forecast summary in Slack #sales with the total open pipeline and a flag on any closed-won deal still waiting on signature. Leave the on-track and closed deals alone.", + "instruction_zh": "现在是月末 pipeline 审查。梳理我的 Salesforce opportunities,找出 close date 早于 2026-06-20 的 open deals,然后将这些逾期的 close dates 全部推迟到 2026-07-31。只将这些逾期 open deals(连同其旧和新的 close dates、amounts 与 owner)记录到 Notion 的 'Pipeline Hygiene' 表格中;如果表格中已经有 opportunity 草稿行,请填写逾期交易对应的行,不要新增行。在 DocuSign 中查看那笔 Hooli 的 closed-won 交易,并注明其协议是否已完全签署。随后给我经理发送一封邮件,汇总你所重新安排的内容;并在 Slack #sales 中发布一份预测摘要,列明 total open pipeline,同时标记出所有仍在等待签署的 closed-won 交易。不要动那些 on-track 和 closed 的交易。", + "id": "ae_pipeline_hygiene_003", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:02:45.641003", + "adversarial_rounds": "1", + "domain": "ae", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ae/ae_pipeline_review_004__long.json b/raw/evaluation_examples/OSWorker/examples/ae/ae_pipeline_review_004__long.json new file mode 100644 index 0000000000000000000000000000000000000000..74c352d1c699606c12d47c205e4d855f4147821c --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ae/ae_pipeline_review_004__long.json @@ -0,0 +1,77 @@ +{ + "id": "ae_pipeline_review_004__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nThe 'Pipeline Review' Google Sheet lists opportunities (rows 2+: OppName, Account, Amount, Stage, CloseDate). For each row, find the matching Salesforce Opportunity by name and bring Salesforce into line with the sheet's decision rules: if Stage is 'Closed Won', set the Salesforce opportunity stage to 'Closed Won' AND create a follow-up Task on that opportunity with Subject 'Kickoff: ' and Status 'Not Started' AND reassign the opportunity's Owner to 'Morgan Avery'; if Stage is 'Closed Lost', set the SF stage to 'Closed Lost' (no task, owner unchanged); if Stage is 'Negotiation' AND Amount >= 50000, set SF stage to 'Negotiation' and create a Task 'Exec review: ' (owner unchanged); all other rows: leave the SF opportunity unchanged. Skip any sheet row whose OppName has no matching Salesforce opportunity. When finished, create a new Slack channel named 'backup', then export the Salesforce Opportunities report to CSV and export the 'Pipeline Review' Google Sheet to CSV, and upload BOTH CSV files into the 'backup' channel as a backup of the synced pipeline.", + "app_type": "salesforce_mock,google_sheets_mock,slack_mock", + "domain": "ae", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/am/am_renewal_contract_001.json b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_contract_001.json new file mode 100644 index 0000000000000000000000000000000000000000..9301221e1ba6325b08a22e0840a14f5efd1b810b --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_contract_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "We're ready to send Globex Corp their renewal paperwork. Open the 'Renewal Brief – Globex Corp' page in Notion to get the terms, then in DocuSign prepare and send a renewal agreement envelope for Globex using those terms — David Okafor is the signer and our finance mailbox finance@vertexcloud.example.com should be CC'd. Once it's out for signature, post in the #deal-desk Slack channel so finance and legal know the Globex renewal envelope has been sent.", + "instruction_zh": "我们已准备好向 Globex Corp 发送续约文件。请在 Notion 中打开 'Renewal Brief – Globex Corp' 页面获取条款,然后在 DocuSign 中使用这些条款为 Globex 准备并发送一份续约协议信封——David Okafor 是签署人,并抄送我们的财务邮箱 finance@vertexcloud.example.com。信封发出待签后,请在 #deal-desk Slack 频道中发布消息,以便财务和法律团队知晓 Globex 续约信封已发送。", + "id": "am_renewal_contract_001", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:07:44.741238", + "adversarial_rounds": "1", + "domain": "am", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/am/am_renewal_hubspot_004__long.json b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_hubspot_004__long.json new file mode 100644 index 0000000000000000000000000000000000000000..6da753f6223a354d074a70ff21baaef31c605774 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_hubspot_004__long.json @@ -0,0 +1,77 @@ +{ + "id": "am_renewal_hubspot_004__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (HubSpot, Gmail, and Google Calendar). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nAssume today is Monday, May 4, 2026. Run renewal outreach in HubSpot. A deal QUALIFIES for renewal outreach only if ALL of these hold: its stage is 'Closed Won', its dealType is 'existing_business', its closeDate is between 2025-05-01 and 2025-07-31 inclusive (i.e. it renews ~1 year out this summer), and its amount is >= 10000.\n\nFor EVERY qualifying deal, complete all six of the following. Some of these controls are not on the main screen -- you may need to open a record, select a row, or open an editor to find them.\n (1) In HubSpot, append a new line to the deal's Description: 'Renewal outreach sent 2026-05-04.' (keep the existing text).\n (2) In HubSpot, reassign that deal's owner (the 'Assigned To' field) from 'Admin User' to 'Renewals Team'.\n (3) In Gmail, send an email to the deal's primary contact (companies[].name -> contacts whose companyId matches -> first such contact's email) with Subject 'Renewal: ' and a body containing the company name, the original amount formatted as $#,##0, and the original closeDate.\n (4) In Gmail, apply the existing 'Renewals' label to that email you just sent.\n (5) In Google Calendar, create an event titled 'Renewal call: ' on 2026-05-11 (any time).\n (6) On that calendar event, add the deal's primary contact email as a guest.\n\nSkip every non-qualifying deal entirely (wrong stage, new_business, out-of-window closeDate, or amount < 10000): do not edit its description or owner, do not email its contact, and do not create a calendar event for it.", + "app_type": "hubspot_mock,gmail_mock,google_calendar_mock", + "domain": "am", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/am/am_renewal_outreach_002.json b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_outreach_002.json new file mode 100644 index 0000000000000000000000000000000000000000..83b83690402aaa51ec1ff09fa48f885185b7411a --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_outreach_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "Account: Northwind Traders — their renewal closes July 15, 2026 and I want to get ahead of it. Please log a renewal check-in task on the Northwind renewal in Salesforce due July 1, send their VP Operations Karen Walsh a short, friendly email with the exact subject \"Northwind Traders renewal call before July 15\" proposing a renewal call before the renewal date, and then drop a note in our #customer-success Slack channel so the CS team knows the outreach is underway.", + "instruction_zh": "客户:Northwind Traders — 他们的续约将于 July 15, 2026 到期,我想提前跟进。请在 Salesforce 中为 Northwind 的续约记录创建一项续约检查任务,截止日期设为 July 1;给他们的 VP Operations Karen Walsh 发送一封简短友好的邮件,邮件主题必须准确写为 \"Northwind Traders renewal call before July 15\",提议在续约日期前安排一次续约通话;然后在我们的 #customer-success Slack 频道中发一条消息,让 CS 团队知道 outreach 已启动。", + "id": "am_renewal_outreach_002", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:09:26.735740", + "adversarial_rounds": "1", + "domain": "am", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/am/am_renewal_tracker_003.json b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_tracker_003.json new file mode 100644 index 0000000000000000000000000000000000000000..c0991e5df57174f6ee737c0aa010707f4f412414 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/am/am_renewal_tracker_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "I'm doing my quarterly renewal review. In Salesforce, go through our open renewal opportunities and find every account whose renewal closes within the next 90 days — today is June 24, 2026. For each qualifying renewal, add a row to the 'Renewal Tracker 2026' database in Notion with the account name, its annual contract value (ARR), the renewal date, a risk level based on our standard probability cutoffs, and the current sales stage. Skip anything that renews after the 90-day window or is already closed.", + "instruction_zh": "我正在做季度续费回顾。在 Salesforce 中,梳理我们未关闭的续费商机,找出所有预计在未来 90 天内关闭的客户——今天是 June 24, 2026。对于每个符合条件的续费,在 Notion 的 'Renewal Tracker 2026' 数据库中添加一行,填入 account name、annual contract value (ARR)、renewal date、基于我们 standard probability cutoffs 的 risk level,以及 current sales stage。跳过所有超出 90 天窗口期的续费,以及已关闭的条目。", + "id": "am_renewal_tracker_003", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:06:55.995384", + "adversarial_rounds": "1", + "domain": "am", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_aging_001.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_aging_001.json new file mode 100644 index 0000000000000000000000000000000000000000..aa56796c131beba6ad9a1b2d2a0c28793ca35fb6 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_aging_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "I need an AR aging snapshot for the finance review, using today (2026-07-01) as the as-of date. In the 'AR Invoice Ledger' Google Sheet, build a summary block below the data that totals all outstanding (unpaid, i.e. any invoice whose Status is not 'Paid') invoices into four aging buckets by their Due Date relative to 2026-07-01: 'current' (not yet due — due date on or after 2026-07-01), '1-30 days overdue' (1 to 30 days past due), '31-60 days overdue' (31 to 60 days past due), and '60+ days overdue' (more than 60 days past due). Write each bucket's total amount and the overall total outstanding. Then in Slack #finance post the three overdue customers with the largest outstanding balances (ranked by dollar amount, with their amounts) and the total outstanding.", + "id": "ar_aging_001", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T17:34:27.555402", + "adversarial_rounds": "1", + "domain": "ar", + "_source": "minicua", + "instruction_zh": "我需要一份用于财务审查的应收账款账龄快照,以今天(2026-07-01)为截至日期。在 'AR Invoice Ledger' Google Sheet 中,于数据下方构建一个汇总区块,按到期日相对于 2026-07-01 将所有未结清(未付款,即状态不是 'Paid')的发票分为四个账龄区间:\"current\"(尚未到期——到期日在 2026-07-01 当天或之后)、\"1-30 days overdue\"(逾期 1 至 30 天)、\"31-60 days overdue\"(逾期 31 至 60 天)和 \"60+ days overdue\"(逾期超过 60 天),并汇总每个区间的金额。写出每个区间的总金额以及未结清总额。然后在 Slack #finance 频道发布逾期金额最大的三家客户(按金额排序,并附上各自的金额)以及未结清总额。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_approval_002.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_approval_002.json new file mode 100644 index 0000000000000000000000000000000000000000..2d349ffc021858b343bc7fa5eb380de3e4d162c6 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_approval_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "The AE on the Hooli deal is asking for a 20% discount, which is over our 15% limit and needs sign-off. Pull the list price and proposed price from the Salesforce opportunity and post a structured approval request in Slack #finance-approvals with the customer, original amount, adjusted amount, discount %, and who's requesting it.", + "id": "ar_approval_002", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T17:39:12.548622", + "adversarial_rounds": "1", + "domain": "ar", + "_source": "minicua", + "instruction_zh": "Hooli 交易的 AE 要求 20% 的折扣,这超出了我们 15% 的限额,需要审批。请从 Salesforce 商机中拉取标价和拟议价格,并在 Slack #finance-approvals 发布一份结构化的审批请求,包含客户、原始金额、调整后金额、折扣百分比以及申请人。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_billing_exception_012__long.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_billing_exception_012__long.json new file mode 100644 index 0000000000000000000000000000000000000000..fb317590ca12fce9019767d660316f70f3d43c78 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_billing_exception_012__long.json @@ -0,0 +1,77 @@ +{ + "id": "ar_billing_exception_012__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nThe 'Billing Exceptions' Google Sheet (tab 'Exceptions', rows 2+: Customer, Exception Type, Amount, Invoice #) lists customers the billing system flagged this week. Work through every row and take the corrective action that its Exception Type calls for, but ONLY when the item is not already in the target state (verify current state first and skip anything already resolved):\n- 'Duplicate charge': refund the matching Stripe payment (match by customer and amount). If that payment has already been refunded, leave it alone.\n- 'Churn - downgrade': cancel the matching Stripe subscription for that customer at the END of the current billing period (do NOT cancel it immediately). If it is already set to cancel at period end (or already canceled), leave it alone.\n- 'Payment received': in QuickBooks, record payment on the invoice whose number is in the Invoice # column so it becomes Paid. If it is already Paid, leave it alone.\n- 'On hold' or 'Under review': do NOT act on these rows -- they are pending and must be left untouched.\nSkip any row whose customer has no matching Stripe payment/subscription or QuickBooks invoice.\n\nWhen you have handled every actionable row, add a new tab named 'Reconciliation Summary' to the 'Billing Exceptions' sheet and record how many exceptions you resolved (a count). Finally, post a one-line summary of the reconciliation to the Slack '#finance' channel and pin that message.", + "app_type": "stripe_dashboard_mock,quickbooks_mock,google_sheets_mock,slack_mock", + "domain": "ar", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_closeout_006.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_closeout_006.json new file mode 100644 index 0000000000000000000000000000000000000000..da6bead1ea4f320430388275f4007769e47e6f81 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_closeout_006.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Finance Operations / Accounts Receivable specialist executing the full contract-to-cash escalation pipeline for the month-end AR close. Process the following three Closed-Won deals, each requiring different branches:\n\nDEAL A — Salesforce OPP-7741 'Cobalt Freight — Enterprise' (Account 'Cobalt Freight LLC', Amount '$95,000', Payment Terms 'Net 30', AE 'Tom Reyes'). DocuSign envelope 'MSA — Cobalt Freight (OPP-7741)' status = 'Completed'. Discount applied = 22% (over the 15% approval threshold). Invoice action: add row to Google Sheets 'Invoice Ledger' tab 'FY26 Invoices': INV-7741 | 'Cobalt Freight LLC' | '$95,000' | 'Net 30' | 'Draft' | 'Salesforce OPP-7741' | '2026-07-01'. Because discount > 15%, post to Slack #finance-approvals: 'APPROVAL NEEDED: OPP-7741 Cobalt Freight LLC — 22% discount on $95,000 invoice INV-7741 exceeds 15% threshold. AE: Tom Reyes. Envelope signed.'\n\nDEAL B — HubSpot D-7742 'Verdant Health — Platform' (Account 'Verdant Health Co.', Amount '$41,000', Payment Terms 'Net 45', AE 'Lena Park'). DocuSign envelope 'MSA — Verdant Health (D-7742)' status = 'Sent' (NOT completed). Invoice action: add row INV-7742 | 'Verdant Health Co.' | '$41,000' | 'Net 45' | 'Draft' | 'HubSpot D-7742' | '2026-07-01'. Send Gmail from ar@saas-co.com to 'contracts@verdant-health.co' Subject 'Action required: Please sign MSA — Verdant Health (D-7742)' body 'Your MSA for the Verdant Health platform (Deal D-7742, $41,000, Net 45) is awaiting signature. Envelope: MSA — Verdant Health (D-7742).' Post to Slack #finance-ar: 'Reminder: MSA — Verdant Health (D-7742) unsigned; Gmail nudge sent to contracts@verdant-health.co. AE: Lena Park. $41,000 Net 45.' (Discount 0% — no approval post.)\n\nDEAL C — Salesforce OPP-7743 'Sable Robotics — Pilot+' (Account 'Sable Robotics', Amount '$18,000', Payment Terms 'Net 60', AE 'Tom Reyes'). DocuSign envelope 'MSA — Sable Robotics (OPP-7743)' status = 'Completed'. Invoice adjustment recorded = +$3,000 manual credit applied (invoice adjustment over the $2,000 approval threshold). Invoice action: add row INV-7743 | 'Sable Robotics' | '$21,000' | 'Net 60' | 'Draft' | 'Salesforce OPP-7743' | '2026-07-01'. Because adjustment > $2,000, post to Slack #finance-approvals: 'APPROVAL NEEDED: OPP-7743 Sable Robotics — $3,000 invoice adjustment on $18,000 base (INV-7743, total $21,000) exceeds $2,000 threshold. AE: Tom Reyes. Envelope signed.'\n\nFinally, in Google Docs create a document titled 'AR Closeout — 2026-07-01' with three bold sections '1. Signed & Awaiting Approval', '2. Unsigned & Reminded', '3. Summary'. Section 1 lists OPP-7741 (22% discount) and OPP-7743 ($3,000 adjustment) with their Slack approval message text. Section 2 lists D-7742 (unsigned, reminded). Section 3 states: '3 deals processed; 2 approval posts to #finance-approvals; 1 Gmail reminder sent; 3 invoice rows added to Invoice Ledger.' Ignore distractor deal OPP-7740 'Cobalt Freight — Trial' (Stage 'Closed Lost') which must NOT be processed.", + "instruction_zh": "和", + "id": "ar_closeout_006", + "app_type": "mock_websites", + "generated_at": "2026-07-02T07:51:23.680011", + "adversarial_rounds": "1", + "domain": "ar", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_invoice_003.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_invoice_003.json new file mode 100644 index 0000000000000000000000000000000000000000..1fca53a5238e682d7958f021b4a5e53d89758ee6 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_invoice_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "The 'Acme Corp - Platform License' opportunity just closed. In Salesforce, open that Closed-Won opportunity to read the amount, Close Date, and payment terms, then add a new invoice row to the 'AR Invoice Ledger' Google Sheet using the opportunity's Close Date as the invoice Issue Date and computing the Due Date from the Net 30 terms, and let the account executive know in Slack #finance that the invoice has been issued.", + "id": "ar_invoice_003", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T17:52:04.464484", + "adversarial_rounds": "1", + "domain": "ar", + "_source": "minicua", + "instruction_zh": "“Acme Corp - Platform License” 商机刚刚成交。在 Salesforce 中打开该 Closed-Won 商机,读取金额、成交日期和付款条款,然后在 “AR Invoice Ledger” Google Sheet 中新增一行发票记录,以商机的成交日期作为开票日期,并根据 Net 30 条款计算到期日,最后在 Slack #finance 频道通知客户经理发票已开具。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_payment_alert_010__long.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_payment_alert_010__long.json new file mode 100644 index 0000000000000000000000000000000000000000..1d4c65366db57cca7f6b291255d0a89fe5eea653 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_payment_alert_010__long.json @@ -0,0 +1,77 @@ +{ + "id": "ar_payment_alert_010__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYour Gmail inbox holds the overnight payment alerts from the billing system (from 'Billing System'). Each alert names one customer, an amount, and (for payment receipts) an invoice number. Work through every alert email and take the corrective action that its alert type calls for, but ONLY when the item is not already in the target state (verify current state first and skip anything already resolved):\n- 'Duplicate charge': refund the matching Stripe payment (match by customer and amount). If that payment has already been refunded, leave it alone.\n- 'Chargeback opened': in Stripe, submit dispute evidence on the matching dispute for that customer so it moves out of the needs-response state. If the dispute is no longer awaiting a response, leave it alone.\n- 'Payment received': in QuickBooks, record payment on the invoice whose number is in the alert so it becomes Paid. If it is already Paid, leave it alone.\n- 'Under investigation': do NOT act on these alerts -- they are pending and must be left untouched.\nSkip any alert whose customer has no matching Stripe payment/dispute or QuickBooks invoice.\n\nFor every alert you actually acted on: in Gmail, apply the matching status label to that alert email -- 'Refunded' for a refund, 'Disputed' for a chargeback, 'Reconciled' for a recorded payment -- and reply to the customer (their email address is in the alert). Do not label or reply to alerts you left untouched or skipped.\n\nWhen you have handled every actionable alert, post a one-line summary of the cleanup (including how many alerts you resolved) to the Slack '#billing-ops' channel and pin that message.", + "app_type": "stripe_dashboard_mock,quickbooks_mock,gmail_mock,slack_mock", + "domain": "ar", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_remittance_008__long.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_remittance_008__long.json new file mode 100644 index 0000000000000000000000000000000000000000..b86ed20714e5df9ec12227e897ff001127137320 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_remittance_008__long.json @@ -0,0 +1,77 @@ +{ + "id": "ar_remittance_008__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (QuickBooks, Google Sheets, and Gmail). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nAssume today is April 30, 2026. FIRST, read the remittance email in Gmail: it names two invoices whose payments just cleared by wire. Record those payments in QuickBooks so each of those two invoices becomes status 'Paid' (use the 'Receive payment' action on the invoice). THEN build an Accounts Receivable aging report from the remaining QuickBooks open invoices into the 'AR Aging' tab of the Google Sheet. Consider only invoices whose status is 'Sent' or 'Overdue' (skip Paid/Draft -- including the two you just marked paid). For each, compute days overdue = today - dueDate. Bucket into: Current (not yet due, days<=0), '1-30', '31-60', '61-90', '90+'. In the sheet, fill columns Customer, InvoiceNumber, Total, DueDate, DaysOverdue, Bucket -- one row per qualifying invoice, sorted by DaysOverdue descending (most overdue first). Then below the rows add a summary block: a row per bucket label in column A and the SUM of Total for that bucket in column C, in this fixed bucket order (Current, 1-30, 31-60, 61-90, 90+), and a final 'Grand Total' row with the sum of all qualifying invoice totals in column C.", + "app_type": "quickbooks_mock,google_sheets_mock,gmail_mock", + "domain": "ar", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_signature_005.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_signature_005.json new file mode 100644 index 0000000000000000000000000000000000000000..2813e1b52c9b8c1e01c53f1e92687a74880a7e50 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_signature_005.json @@ -0,0 +1,79 @@ +{ + "instruction": "Do a signature sweep on this week's contracts. For the three DocuSign envelopes 'Stark Industries SOW', 'Oscorp License Agreement', and 'Tyrell Corp MSA', check each one's status. For any that aren't completed, send the signer a signing reminder by Gmail, then post a roundup in Slack #finance listing which contracts are signed and which are still outstanding.", + "id": "ar_signature_005", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T17:57:37.678050", + "adversarial_rounds": "1", + "domain": "ar", + "_source": "minicua", + "instruction_zh": "对本周的合同做一次签名排查。针对三个 DocuSign 信封 'Stark Industries SOW'、'Oscorp License Agreement' 和 'Tyrell Corp MSA',逐一检查它们的状态。如有未完成的,通过 Gmail 向签署人发送签署提醒,然后在 Slack #finance 发布一份汇总,列出哪些合同已签署、哪些仍未完成。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/ar/ar_stripe_reconcile_011__long.json b/raw/evaluation_examples/OSWorker/examples/ar/ar_stripe_reconcile_011__long.json new file mode 100644 index 0000000000000000000000000000000000000000..7d77aa29afbe7133bfba24b54f58db72e91ec0ce --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/ar/ar_stripe_reconcile_011__long.json @@ -0,0 +1,77 @@ +{ + "id": "ar_stripe_reconcile_011__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nReconcile all successfully captured Stripe payments in May 2026 (status = \"Succeeded\"). For each such payment, check whether a matching transaction (same amount and same date) already exists in QuickBooks under expenses. If yes, mark its Status as \"Matched\". If no, mark its Status as \"Unmatched\" AND create the missing expense in QuickBooks. Then, in the Recon tab of the Google Sheet, add one row per May payment with columns Payment (the payment description), StripeAmount, QBAmount, and Status. Note: Status reflects the QB state BEFORE your edits — an expense you create during this task is \"Unmatched\", not \"Matched\". QBAmount reflects the FINAL QB amount after your edits (for Unmatched rows, equal to StripeAmount). At the bottom of the sheet, compute the totals for StripeAmount and QBAmount.\n\nFinally, send an email to finance@company.com with subject \"Summary of May Payments\". The email body should follow this format (amounts in USD with two decimals):\n\ntotals:\nStripeAmount = \nQBAmount = \n\nIf there are unmatched payments, list them as: \"Unmatched payments:\" followed by one line per payment in the form \" = \". If everything matched, write a single line: \"No unmatched payments.\"", + "app_type": "stripe_dashboard_mock,quickbooks_mock,google_sheets_mock,gmail_mock", + "domain": "ar", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/calc/calc_boomerang_sales_004__long.json b/raw/evaluation_examples/OSWorker/examples/calc/calc_boomerang_sales_004__long.json new file mode 100644 index 0000000000000000000000000000000000000000..5cfc847bf5367844b7e15666ec203325e7a3b473 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/calc/calc_boomerang_sales_004__long.json @@ -0,0 +1,124 @@ +{ + "id": "calc_boomerang_sales_004__long", + "snapshot": "libreoffice_calc", + "instruction": "I have 5 files named 'BoomerangSales_1.xlsx' to 'BoomerangSales_5.xlsx' in the 'source_file' folder on the Desktop. Please open each file in order, perform the operation, save it, and click the close button in the top-right corner to close the file. The operation is as follows: Sort the data according to column A in an ascending order and then create a line chart with the \"Date Time\" column on the X-axis and quantity on the Y-axis.", + "source": "SheetCopilot@5", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/source_file/BoomerangSales_1.xlsx", + "path": "/home/user/Desktop/source_file/BoomerangSales_1.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/source_file/BoomerangSales_2.xlsx", + "path": "/home/user/Desktop/source_file/BoomerangSales_2.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/source_file/BoomerangSales_3.xlsx", + "path": "/home/user/Desktop/source_file/BoomerangSales_3.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/source_file/BoomerangSales_4.xlsx", + "path": "/home/user/Desktop/source_file/BoomerangSales_4.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/source_file/BoomerangSales_5.xlsx", + "path": "/home/user/Desktop/source_file/BoomerangSales_5.xlsx" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5", + "related_apps": [ + "libreoffice_calc" + ], + "evaluator": { + "postconfig": [], + "func": "compare_table_multiple", + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/target_file/6_BoomerangSales_gt1_1.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/target_file/6_BoomerangSales_gt1_2.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/target_file/6_BoomerangSales_gt1_3.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/target_file/6_BoomerangSales_gt1_4.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/3a7c8185-25c1-4941-bd7b-96e823c9f21f_5/target_file/6_BoomerangSales_gt1_5.xlsx" + ], + "dest": [ + "6_BoomerangSales_gt1_1.xlsx", + "6_BoomerangSales_gt1_2.xlsx", + "6_BoomerangSales_gt1_3.xlsx", + "6_BoomerangSales_gt1_4.xlsx", + "6_BoomerangSales_gt1_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/BoomerangSales_1.xlsx", + "/home/user/Desktop/source_file/BoomerangSales_2.xlsx", + "/home/user/Desktop/source_file/BoomerangSales_3.xlsx", + "/home/user/Desktop/source_file/BoomerangSales_4.xlsx", + "/home/user/Desktop/source_file/BoomerangSales_5.xlsx" + ], + "dest": [ + "local_BoomerangSales_1.xlsx", + "local_BoomerangSales_2.xlsx", + "local_BoomerangSales_3.xlsx", + "local_BoomerangSales_4.xlsx", + "local_BoomerangSales_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "options": { + "rules": [ + { + "type": "sheet_data", + "sheet_idx0": 0, + "sheet_idx1": "EI0" + }, + { + "type": "chart", + "sheet_idx0": 0, + "sheet_idx1": "EI0", + "chart_props": [ + "type" + ] + } + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "calc", + "app_type": "democua_libreoffice_calc_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/calc/calc_employee_roles_003__long.json b/raw/evaluation_examples/OSWorker/examples/calc/calc_employee_roles_003__long.json new file mode 100644 index 0000000000000000000000000000000000000000..96188b7bc47d77f80c81bb95648a6ab7fe933345 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/calc/calc_employee_roles_003__long.json @@ -0,0 +1,116 @@ +{ + "id": "calc_employee_roles_003__long", + "snapshot": "libreoffice_calc", + "instruction": "I have 5 files named 'Employee_Roles_and_Ranks_1.xlsx' to 'Employee_Roles_and_Ranks_5.xlsx' in the 'source_file' folder on the Desktop. Please open each file in order, perform the operation, save it, and click the close button in the top-right corner to close the file. The operation is as follows: The information are mixed in one field. Help me split them and fill in the columns of First Name, Last Name and Rank. Finish the work and don't touch the original data.", + "source": "https://www.youtube.com/shorts/uzPo_CPCHH8", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/source_file/Employee_Roles_and_Ranks_1.xlsx", + "path": "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_1.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/source_file/Employee_Roles_and_Ranks_2.xlsx", + "path": "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_2.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/source_file/Employee_Roles_and_Ranks_3.xlsx", + "path": "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_3.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/source_file/Employee_Roles_and_Ranks_4.xlsx", + "path": "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_4.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/source_file/Employee_Roles_and_Ranks_5.xlsx", + "path": "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_5.xlsx" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/37608790-6147-45d0-9f20-1137bb35703d_5", + "related_apps": [ + "libreoffice calc" + ], + "evaluator": { + "postconfig": [], + "func": "compare_table_multiple", + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/target_file/Employee_Roles_and_Ranks_gold_1.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/target_file/Employee_Roles_and_Ranks_gold_2.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/target_file/Employee_Roles_and_Ranks_gold_3.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/target_file/Employee_Roles_and_Ranks_gold_4.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/37608790-6147-45d0-9f20-1137bb35703d_5/target_file/Employee_Roles_and_Ranks_gold_5.xlsx" + ], + "dest": [ + "Employee_Roles_and_Ranks_gold_1.xlsx", + "Employee_Roles_and_Ranks_gold_2.xlsx", + "Employee_Roles_and_Ranks_gold_3.xlsx", + "Employee_Roles_and_Ranks_gold_4.xlsx", + "Employee_Roles_and_Ranks_gold_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_1.xlsx", + "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_2.xlsx", + "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_3.xlsx", + "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_4.xlsx", + "/home/user/Desktop/source_file/Employee_Roles_and_Ranks_5.xlsx" + ], + "dest": [ + "local_Employee_Roles_and_Ranks_1.xlsx", + "local_Employee_Roles_and_Ranks_2.xlsx", + "local_Employee_Roles_and_Ranks_3.xlsx", + "local_Employee_Roles_and_Ranks_4.xlsx", + "local_Employee_Roles_and_Ranks_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "options": { + "rules": [ + { + "type": "sheet_data", + "sheet_idx0": 0, + "sheet_idx1": "EI0" + } + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "calc", + "app_type": "democua_libreoffice_calc_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/calc/calc_income_statement_001__long.json b/raw/evaluation_examples/OSWorker/examples/calc/calc_income_statement_001__long.json new file mode 100644 index 0000000000000000000000000000000000000000..562b1414ee21cc26668a0a40f9df24ac58c7b695 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/calc/calc_income_statement_001__long.json @@ -0,0 +1,121 @@ +{ + "id": "calc_income_statement_001__long", + "snapshot": "libreoffice_calc", + "instruction": "I have 5 files named 'IncomeStatement2_1.xlsx' to 'IncomeStatement2_5.xlsx' in the 'source_file' folder on the Desktop. Please open each file in order, perform the operation, save it, and click the close button in the top-right corner to close the file. The operation is as follows: Help me fill in the Gross profit column by subtracting all the available expenses including discounts, allowances, material and labor charges, and overhead from the actual sale, i.e., the sales after deducting the returns. Then under column A named \"Year_Profit\" in a new sheet \"Sheet2\", display the Year Column in Sheet 1 as text appended by a \"_\" with the corresponding integer digits of Gross Profit value.", + "source": "SheetCopilot@92", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/source_file/IncomeStatement2_1.xlsx", + "path": "/home/user/Desktop/source_file/IncomeStatement2_1.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/source_file/IncomeStatement2_2.xlsx", + "path": "/home/user/Desktop/source_file/IncomeStatement2_2.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/source_file/IncomeStatement2_3.xlsx", + "path": "/home/user/Desktop/source_file/IncomeStatement2_3.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/source_file/IncomeStatement2_4.xlsx", + "path": "/home/user/Desktop/source_file/IncomeStatement2_4.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/source_file/IncomeStatement2_5.xlsx", + "path": "/home/user/Desktop/source_file/IncomeStatement2_5.xlsx" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/035f41ba-6653-43ab-aa63-c86d449d62e5_5", + "related_apps": [ + "libreoffice_calc" + ], + "evaluator": { + "postconfig": [], + "func": "compare_table_multiple", + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/target_file/5_IncomeStatement2_gt1_1.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/target_file/5_IncomeStatement2_gt1_2.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/target_file/5_IncomeStatement2_gt1_3.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/target_file/5_IncomeStatement2_gt1_4.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/035f41ba-6653-43ab-aa63-c86d449d62e5_5/target_file/5_IncomeStatement2_gt1_5.xlsx" + ], + "dest": [ + "5_IncomeStatement2_gt1_1.xlsx", + "5_IncomeStatement2_gt1_2.xlsx", + "5_IncomeStatement2_gt1_3.xlsx", + "5_IncomeStatement2_gt1_4.xlsx", + "5_IncomeStatement2_gt1_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/IncomeStatement2_1.xlsx", + "/home/user/Desktop/source_file/IncomeStatement2_2.xlsx", + "/home/user/Desktop/source_file/IncomeStatement2_3.xlsx", + "/home/user/Desktop/source_file/IncomeStatement2_4.xlsx", + "/home/user/Desktop/source_file/IncomeStatement2_5.xlsx" + ], + "dest": [ + "local_IncomeStatement2_1.xlsx", + "local_IncomeStatement2_2.xlsx", + "local_IncomeStatement2_3.xlsx", + "local_IncomeStatement2_4.xlsx", + "local_IncomeStatement2_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "options": { + "rules": [ + { + "type": "sheet_data", + "sheet_idx0": "RNSheet1", + "sheet_idx1": "ENSheet1" + }, + { + "type": "sheet_data", + "sheet_idx0": "RNSheet2", + "sheet_idx1": "ENSheet2" + } + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "calc", + "app_type": "democua_libreoffice_calc_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/calc/calc_sales_rep_002__long.json b/raw/evaluation_examples/OSWorker/examples/calc/calc_sales_rep_002__long.json new file mode 100644 index 0000000000000000000000000000000000000000..a0592095eca762b0166abece7cb6cc5670a25d20 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/calc/calc_sales_rep_002__long.json @@ -0,0 +1,116 @@ +{ + "id": "calc_sales_rep_002__long", + "snapshot": "libreoffice_calc", + "instruction": "I have 5 files named 'SalesRep_1.xlsx' to 'SalesRep_5.xlsx' in the 'source_file' folder on the Desktop. Please open each file in order, perform the operation, save it, and click the close button in the top-right corner to close the file. The operation is as follows: Create a table with two column headers (\"Month\" and \"Total\") in a new sheet named \"Sheet2\" to show the total sales for all months. Do not add any months that are not already present in Sheet1.", + "source": "SheetCopilot@152", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/source_file/SalesRep_1.xlsx", + "path": "/home/user/Desktop/source_file/SalesRep_1.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/source_file/SalesRep_2.xlsx", + "path": "/home/user/Desktop/source_file/SalesRep_2.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/source_file/SalesRep_3.xlsx", + "path": "/home/user/Desktop/source_file/SalesRep_3.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/source_file/SalesRep_4.xlsx", + "path": "/home/user/Desktop/source_file/SalesRep_4.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/source_file/SalesRep_5.xlsx", + "path": "/home/user/Desktop/source_file/SalesRep_5.xlsx" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/26a8440e-c166-4c50-aef4-bfb77314b46b_5", + "related_apps": [ + "libreoffice_calc" + ], + "evaluator": { + "postconfig": [], + "func": "compare_table_multiple", + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/target_file/3_SalesRep_gt1_1.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/target_file/3_SalesRep_gt1_2.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/target_file/3_SalesRep_gt1_3.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/target_file/3_SalesRep_gt1_4.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/26a8440e-c166-4c50-aef4-bfb77314b46b_5/target_file/3_SalesRep_gt1_5.xlsx" + ], + "dest": [ + "3_SalesRep_gt1_1.xlsx", + "3_SalesRep_gt1_2.xlsx", + "3_SalesRep_gt1_3.xlsx", + "3_SalesRep_gt1_4.xlsx", + "3_SalesRep_gt1_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/SalesRep_1.xlsx", + "/home/user/Desktop/source_file/SalesRep_2.xlsx", + "/home/user/Desktop/source_file/SalesRep_3.xlsx", + "/home/user/Desktop/source_file/SalesRep_4.xlsx", + "/home/user/Desktop/source_file/SalesRep_5.xlsx" + ], + "dest": [ + "local_SalesRep_1.xlsx", + "local_SalesRep_2.xlsx", + "local_SalesRep_3.xlsx", + "local_SalesRep_4.xlsx", + "local_SalesRep_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "options": { + "rules": [ + { + "type": "sheet_data", + "sheet_idx0": "RNSheet2", + "sheet_idx1": "ENSheet2" + } + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "calc", + "app_type": "democua_libreoffice_calc_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/calc/calc_student_grades_005__long.json b/raw/evaluation_examples/OSWorker/examples/calc/calc_student_grades_005__long.json new file mode 100644 index 0000000000000000000000000000000000000000..9d31128d8f641afaf21bfa68c39cc490d54d5a8d --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/calc/calc_student_grades_005__long.json @@ -0,0 +1,116 @@ +{ + "id": "calc_student_grades_005__long", + "snapshot": "libreoffice_calc", + "instruction": "I have 5 files named 'Student_Grades_and_Remarks_1.xlsx' to 'Student_Grades_and_Remarks_5.xlsx' in the 'source_file' folder on the Desktop. Please open each file in order, perform the operation, save it, and click the close button in the top-right corner to close the file. The operation is as follows: According to the scale table shown above, calculate and give each student a grade in the table below. Finish the work and don't touch irrelevant regions, even if they are blank.", + "source": "https://www.youtube.com/shorts/d7U1S_IsTVM", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/source_file/Student_Grades_and_Remarks_1.xlsx", + "path": "/home/user/Desktop/source_file/Student_Grades_and_Remarks_1.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/source_file/Student_Grades_and_Remarks_2.xlsx", + "path": "/home/user/Desktop/source_file/Student_Grades_and_Remarks_2.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/source_file/Student_Grades_and_Remarks_3.xlsx", + "path": "/home/user/Desktop/source_file/Student_Grades_and_Remarks_3.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/source_file/Student_Grades_and_Remarks_4.xlsx", + "path": "/home/user/Desktop/source_file/Student_Grades_and_Remarks_4.xlsx" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/source_file/Student_Grades_and_Remarks_5.xlsx", + "path": "/home/user/Desktop/source_file/Student_Grades_and_Remarks_5.xlsx" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/d681960f-7bc3-4286-9913-a8812ba3261a_5", + "related_apps": [ + "libreoffice calc" + ], + "evaluator": { + "postconfig": [], + "func": "compare_table_multiple", + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/target_file/Student_Grades_and_Remarks_gold_1.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/target_file/Student_Grades_and_Remarks_gold_2.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/target_file/Student_Grades_and_Remarks_gold_3.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/target_file/Student_Grades_and_Remarks_gold_4.xlsx", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench/resolve/main/libreoffice_calc_long/d681960f-7bc3-4286-9913-a8812ba3261a_5/target_file/Student_Grades_and_Remarks_gold_5.xlsx" + ], + "dest": [ + "Student_Grades_and_Remarks_gold_1.xlsx", + "Student_Grades_and_Remarks_gold_2.xlsx", + "Student_Grades_and_Remarks_gold_3.xlsx", + "Student_Grades_and_Remarks_gold_4.xlsx", + "Student_Grades_and_Remarks_gold_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/Student_Grades_and_Remarks_1.xlsx", + "/home/user/Desktop/source_file/Student_Grades_and_Remarks_2.xlsx", + "/home/user/Desktop/source_file/Student_Grades_and_Remarks_3.xlsx", + "/home/user/Desktop/source_file/Student_Grades_and_Remarks_4.xlsx", + "/home/user/Desktop/source_file/Student_Grades_and_Remarks_5.xlsx" + ], + "dest": [ + "local_Student_Grades_and_Remarks_1.xlsx", + "local_Student_Grades_and_Remarks_2.xlsx", + "local_Student_Grades_and_Remarks_3.xlsx", + "local_Student_Grades_and_Remarks_4.xlsx", + "local_Student_Grades_and_Remarks_5.xlsx" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "options": { + "rules": [ + { + "type": "sheet_data", + "sheet_idx0": 0, + "sheet_idx1": "EI0" + } + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "calc", + "app_type": "democua_libreoffice_calc_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/csops/csops_email_to_crm_case_001.json b/raw/evaluation_examples/OSWorker/examples/csops/csops_email_to_crm_case_001.json new file mode 100644 index 0000000000000000000000000000000000000000..94cb4c2b25b0566dfbfb3dfcdc5a00e6b9f0d4c4 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/csops/csops_email_to_crm_case_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "An urgent customer email is sitting unread in the support inbox. Please log it in the CRM as a support case against the right customer account, set the Salesforce Case priority to High and status to Working, get it to the colleague who owns that relationship, and send the customer a brief acknowledgement so they know we're on it.", + "instruction_zh": "支持收件箱中有一封未读的紧急客户邮件。请在 CRM 中将其登记为关联至正确客户账户的支持案例,将 Salesforce Case 的 priority 设为 High、status 设为 Working,转交给负责该客户关系的同事,并向客户发送一封简短的确认回复,让对方知道我们正在处理。", + "id": "csops_email_to_crm_case_001", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:20:24.659435", + "adversarial_rounds": "1", + "domain": "csops", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/csops/csops_inbox_triage_006__long.json b/raw/evaluation_examples/OSWorker/examples/csops/csops_inbox_triage_006__long.json new file mode 100644 index 0000000000000000000000000000000000000000..700dcc8a1cc5c5fda1d2ffe2461c73f59c4d5c34 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/csops/csops_inbox_triage_006__long.json @@ -0,0 +1,77 @@ +{ + "id": "csops_inbox_triage_006__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (Gmail, Trello, Google Calendar, and Slack). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nAssume today is Tuesday, June 16, 2026. Triage the support inbox into the 'Support' Trello board. Each genuine support email must become ONE card placed in the list matching its component -- 'Bug', 'Billing', 'Feature Request', or 'Account' -- with the card title equal to the email Subject exactly. Classify each email's priority by severity keyword in the body: 'urgent'/'production down' -> red 'P1'; 'broken'/'error'/'cannot' -> orange 'P2'; everything else -> yellow 'P3'.\n\nApply the priority both in Gmail and on the Trello card. In Gmail, apply the matching priority label ('P1', 'P2', or 'P3') to each genuine support email -- the Label button only appears in the toolbar after you select an email with its checkbox. On the Trello card, set the same priority label and a due date from the SLA: P1 = today +1 day, P2 = today +3 days, P3 = today +7 days (due at 17:00 local). The Trello label and due-date controls are inside the card's detail view -- open the card to reach them.\n\nDo NOT create cards (or apply Gmail labels) for newsletters, auto-replies, thank-you notes, or emails whose thread already has a later reply saying it is resolved -- archive all of those instead.\n\nFor each P1 (urgent) ticket only, also create a Google Calendar event titled 'Follow-up: ' on the P1 due date.\n\nFinally, post a one-line summary to the Slack #support channel stating how many support tickets you triaged, and pin that message to the channel (the pin option is in the message's hover '...' more-actions menu).", + "app_type": "gmail_mock,trello_mock,google_calendar_mock,slack_mock", + "domain": "csops", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/csops/csops_incident_command_004__long.json b/raw/evaluation_examples/OSWorker/examples/csops/csops_incident_command_004__long.json new file mode 100644 index 0000000000000000000000000000000000000000..81f4bba03e17d8d45393eb68a97b168c0e8ca3b2 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/csops/csops_incident_command_004__long.json @@ -0,0 +1,77 @@ +{ + "id": "csops_incident_command_004__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (ServiceNow, Microsoft Teams, Google Calendar, and Gmail). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou are the incident commander working the overnight incident queue in ServiceNow. Assign each new incident to the on-call engineer for its service, and set the incident to In Progress. The on-call rota is in a Gmail note; before assigning, check Google Calendar for anyone on PTO this week -- if the primary on-call for a service is on PTO, assign their backup instead. Only work new incidents; leave incidents that are already In Progress, Resolved, or Closed, and skip low-priority (Planning) items.\n\nFor every P1 incident, also post a bridge message naming the incident in the Microsoft Teams 'incidents' channel, and create a Google Calendar event titled exactly 'Bridge: ' dated today (2026-04-30).\n\nOne incident does not name its service or owner and its service is not in the rota. Do not guess: read the Microsoft Teams 'incidents' channel history -- the owner was already asked about and answered there -- and assign it to the engineer named in that reply.", + "app_type": "ServiceNow_mock,microsoft_teams_mock,google_calendar_mock,gmail_mock", + "domain": "csops", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/csops/csops_p1_incident_002.json b/raw/evaluation_examples/OSWorker/examples/csops/csops_p1_incident_002.json new file mode 100644 index 0000000000000000000000000000000000000000..e7c8fa69a88ed1e7a0382276ddd232a31ecc5104 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/csops/csops_p1_incident_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "In Slack #incidents, Contoso Bank has explicitly declared a customer P1: their VP of IT says production SSO login is completely down since 14:05 UTC, about 4,000 users are locked out, and executive banking operations are blocked. Stand up the full incident record across our tools: create a top-urgency Jira defect for the Contoso SSO outage and assign it to Raj Patel, escalate the existing Contoso Salesforce case to Critical/Escalated, publish a company-readable Notion incident summary with impact, timeline, owner, and next update time, then reply in the Slack P1 thread with the Jira key and the incident record so everyone works from one source of truth.", + "instruction_zh": "Slack #incidents 中 Contoso Bank 已明确声明客户 P1:其 VP of IT 表示生产 SSO 登录自 14:05 UTC 起完全不可用,约 4,000 名用户被锁定,且高管银行业务受阻。请在各工具中建立完整事件记录:为 Contoso SSO 故障创建最高紧急度的 Jira 缺陷并分配给 Raj Patel,将现有 Contoso Salesforce case 升级为 Critical/Escalated,发布一份全公司可读的 Notion 事件摘要,包含影响、时间线、负责人和下一次更新时间,然后在 Slack P1 线程中回复 Jira key 和 incident record,让所有人基于单一事实来源开展工作。", + "id": "csops_p1_incident_002", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:26:51.888520", + "adversarial_rounds": "1", + "domain": "csops", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/csops/csops_sla_queue_triage_003.json b/raw/evaluation_examples/OSWorker/examples/csops/csops_sla_queue_triage_003.json new file mode 100644 index 0000000000000000000000000000000000000000..1b404071c512ba32cf96af3f09181264ecdc1352 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/csops/csops_sla_queue_triage_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "It is the start-of-day support SLA triage for the existing Salesforce, Gmail, Jira, Notion, and Slack mocks. Use Gmail only as context. In Salesforce, triage the five open cases and make only the two breached cases Escalated: case-1 / case 00001001 for Helios Retail, \"Checkout payment declined for all EU cards\", must have status Escalated and owner Marcus Reid (user-3); case-2 / case 00001002 for Brightwave Media, \"Reports export to CSV produces empty file\", must have status Escalated and owner Priya Nair (user-2). Do not escalate the on-track cases case-3, case-4, or case-5. Because the Brightwave CSV export issue is a reproducible product defect, create a new Jira issue in the Support Engineering project (SUP) with type Bug, priority High, assignee Raj Patel (u_eng), and a summary or description that explicitly names Brightwave Media and the empty/0-byte CSV export problem. In Notion, under the existing Daily Triage page in the Support Ops workspace, create a database named Support SLA Tracker with columns for Customer or Account, Case Number, Priority, SLA Status, Owner, and Action, and add one row for each of the five open Salesforce cases. Mark the Helios Retail and Brightwave Media rows as SLA Status Breached; the Nimbus Co, Orbit Labs, and Contoso Bank rows must not be marked Breached. In Slack, post a new message in the #support channel that mentions both breached customers or problems, states that the breached cases were escalated, and references the new Jira/SUP engineering ticket. The task is complete when those exact Salesforce ownership/status updates, the Jira bug, the Notion tracker, and the #support digest are all present.", + "instruction_zh": "这是一次工作日开始时的支持 SLA 队列分诊,涉及现有 Salesforce、Gmail、Jira、Notion 和 Slack mock。Gmail 只作为上下文参考。在 Salesforce 中分诊 5 个未结 case,只把两个已经违反 SLA 的 case 升级为 Escalated:Helios Retail 的 case-1 / case 00001001「Checkout payment declined for all EU cards」必须设为 status Escalated,并分配给 Marcus Reid(user-3);Brightwave Media 的 case-2 / case 00001002「Reports export to CSV produces empty file」必须设为 status Escalated,并分配给 Priya Nair(user-2)。不要把仍在正常 SLA 内的 case-3、case-4 或 case-5 升级为 Escalated。由于 Brightwave 的 CSV 导出空文件/0 字节问题是可复现的产品缺陷,请在 Jira 的 Support Engineering 项目(SUP)中新建一个 issue:type 为 Bug,priority 为 High,assignee 为 Raj Patel(u_eng),summary 或 description 需要明确写出 Brightwave Media 以及 CSV 导出空文件/0 字节问题。在 Notion 的 Support Ops workspace 里,在现有 Daily Triage 页面下创建名为 Support SLA Tracker 的数据库,字段至少包括 Customer 或 Account、Case Number、Priority、SLA Status、Owner、Action,并为 5 个未结 Salesforce case 各添加一行。Helios Retail 和 Brightwave Media 两行的 SLA Status 标为 Breached;Nimbus Co、Orbit Labs、Contoso Bank 三行不能标为 Breached。在 Slack 的 #support 频道发布一条新消息,提到两个违反 SLA 的客户或问题,说明这些 breached case 已经升级,并引用新建的 Jira/SUP 工程 ticket。完成标准是上述 Salesforce 状态和负责人、Jira bug、Notion tracker、以及 #support 摘要都已经存在。", + "id": "csops_sla_queue_triage_003", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:24:17.219241", + "adversarial_rounds": "1", + "domain": "csops", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/csops/csops_ticket_queue_005__long.json b/raw/evaluation_examples/OSWorker/examples/csops/csops_ticket_queue_005__long.json new file mode 100644 index 0000000000000000000000000000000000000000..4b12b561789bbd550e37cafafc29b565662cf10c --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/csops/csops_ticket_queue_005__long.json @@ -0,0 +1,77 @@ +{ + "id": "csops_ticket_queue_005__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (Zendesk, Slack, Gmail, and Google Sheets). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou are the support lead triaging the overnight ticket queue in Zendesk. Set a priority on each new ticket and route it per the SLA policy. The policy is NOT repeated here: read it in the Slack #support-ops channel (see the pinned message, and check your direct messages for any clarification) and apply it.\n\nIf a ticket does not give you enough information to set its priority confidently, do not guess -- post a question in Slack #support-ops asking for the missing detail, and leave that ticket unset.\n\nRecord what you did in the 'Triage Log' tab of the Google Sheet: one row per triaged ticket with columns Ticket, Priority, Escalated (yes/no). Then email a wrap-up to the team: in Gmail, send a message to support-team@northgate.com with the exact subject 'Overnight triage summary - 2026-04-30' and a one-line body stating how many tickets you triaged and how many you escalated to Tier 2. Finally, post a one-line summary to Slack #support-ops and pin it.", + "app_type": "Zendesk_mock,slack_mock,gmail_mock,google_sheets_mock", + "domain": "csops", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/fin/fin_expense_claim_001__long__cond.json b/raw/evaluation_examples/OSWorker/examples/fin/fin_expense_claim_001__long__cond.json new file mode 100644 index 0000000000000000000000000000000000000000..75c4e6af1b21e056cf820670e0ea232278ab24e7 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/fin/fin_expense_claim_001__long__cond.json @@ -0,0 +1,114 @@ +{ + "id": "fin_expense_claim_001__long__cond", + "snapshot": "thunderbird", + "instruction": "Please help me submit a reimbursement for the invoices in \"Desktop/invoices/\". The company's reimbursement system is already open in Chrome — check the instructions on the homepage for the correct process.\n\nThe two invoices have a combined total of ¥605. The expense category is \"Transportation\" and the description is \"Taxi fares for client visits on May 12-13\". Any additional information or documents you may need can also be found in that folder.\n\nUpload both invoice files and fill in all required fields, then submit.", + "source": "authors", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa01-eea1-49a3-bc2e-c0ndbr020001/oa_server.py", + "path": "/home/user/oa_server.py" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa01-eea1-49a3-bc2e-c0ndbr020001/invoice_1.pdf", + "path": "/home/user/Desktop/invoices/invoice_1.pdf" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa01-eea1-49a3-bc2e-c0ndbr020001/invoice_2.pdf", + "path": "/home/user/Desktop/invoices/invoice_2.pdf" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa01-eea1-49a3-bc2e-c0ndbr020001/mentor_id_and_approval_code.xlsx", + "path": "/home/user/Desktop/invoices/mentor_id_and_approval_code.xlsx" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": [ + "mkdir", + "-p", + "/home/user/oa_data" + ] + } + }, + { + "type": "execute", + "parameters": { + "command": [ + "sh", + "-c", + "nohup python3 /home/user/oa_server.py --user li_ming --role intern --port 8765 >/home/user/oa_server.log 2>&1 & disown; sleep 3" + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "google-chrome", + "http://localhost:8765/" + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/invoices" + ] + } + } + ], + "trajectory": "trajectories/", + "related_apps": [ + "google-chrome", + "os" + ], + "evaluator": { + "postconfig": [ + { + "type": "command", + "parameters": { + "command": [ + "sh", + "-c", + "tar -czf /home/user/cond_oa_artifacts.tar.gz -C /home/user oa_data 2>/dev/null; ls -la /home/user/cond_oa_artifacts.tar.gz" + ], + "stdout": "cond_oa_artifacts.ls" + } + } + ], + "func": "evaluate_oa_role_condition", + "result": { + "type": "vm_file", + "path": "/home/user/cond_oa_artifacts.tar.gz", + "dest": "cond_oa_artifacts.tar.gz" + }, + "expected": {}, + "options": { + "branch": "branch02", + "expected_amount": 605, + "expected_category": "Transportation", + "expected_description_keywords": [ + "taxi", + "client" + ], + "expected_portal": "intern", + "expected_invoice_count": 2, + "expected_mentor_id": "EMP-20190315", + "expected_dept_approval_code": "DEPT-2026-0517" + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "fin", + "app_type": "democua_condition" +} diff --git a/raw/evaluation_examples/OSWorker/examples/fin/fin_expense_claim_002__long__cond.json b/raw/evaluation_examples/OSWorker/examples/fin/fin_expense_claim_002__long__cond.json new file mode 100644 index 0000000000000000000000000000000000000000..89294e788dc3d9897d375a2179ac6b7efea897d3 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/fin/fin_expense_claim_002__long__cond.json @@ -0,0 +1,118 @@ +{ + "id": "fin_expense_claim_002__long__cond", + "snapshot": "thunderbird", + "instruction": "Please help me submit a reimbursement for the invoices in \"Desktop/invoices/\". The company's reimbursement system is already open in Chrome — check the instructions on the homepage for the correct process.\n\nThe two invoices have a combined total of ¥1,105. The expense category is \"Transportation\" and the description is \"Taxi fares for client visits on May 12-13\".\n\nUpload both invoice files and fill in all required fields. If the system asks for additional documents or information, you can find them in the invoices folder. Then submit.", + "source": "authors", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa02-eea1-49a3-bc2e-c0ndbr020001/oa_server.py", + "path": "/home/user/oa_server.py" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa02-eea1-49a3-bc2e-c0ndbr020001/invoice_1.pdf", + "path": "/home/user/Desktop/invoices/invoice_1.pdf" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa02-eea1-49a3-bc2e-c0ndbr020001/invoice_2.pdf", + "path": "/home/user/Desktop/invoices/invoice_2.pdf" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa02-eea1-49a3-bc2e-c0ndbr020001/justification.txt", + "path": "/home/user/Desktop/invoices/justification.txt" + }, + { + "url": "https://huggingface.co/datasets/faker-w/ubuntu_osworld_file_cache/resolve/main/multi_apps/c0ndoa02-eea1-49a3-bc2e-c0ndbr020001/manager_approval.pdf", + "path": "/home/user/Desktop/invoices/manager_approval.pdf" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": [ + "mkdir", + "-p", + "/home/user/oa_data" + ] + } + }, + { + "type": "execute", + "parameters": { + "command": [ + "sh", + "-c", + "nohup python3 /home/user/oa_server.py --user zhang_wei --role employee --port 8765 >/home/user/oa_server.log 2>&1 & disown; sleep 3" + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "google-chrome", + "http://localhost:8765/" + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/invoices" + ] + } + } + ], + "trajectory": "trajectories/", + "related_apps": [ + "google-chrome", + "os" + ], + "evaluator": { + "postconfig": [ + { + "type": "command", + "parameters": { + "command": [ + "sh", + "-c", + "tar -czf /home/user/cond_oa_artifacts.tar.gz -C /home/user oa_data 2>/dev/null; ls -la /home/user/cond_oa_artifacts.tar.gz" + ], + "stdout": "cond_oa_artifacts.ls" + } + } + ], + "func": "evaluate_oa_amount_condition", + "result": { + "type": "vm_file", + "path": "/home/user/cond_oa_artifacts.tar.gz", + "dest": "cond_oa_artifacts.tar.gz" + }, + "expected": {}, + "options": { + "branch": "branch02", + "expected_amount": 1105, + "expected_category": "Transportation", + "expected_description_keywords": [ + "taxi", + "client" + ], + "expected_invoice_count": 2, + "expected_justification": true, + "expected_approval_report": true, + "amount_threshold": 1000 + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "fin", + "app_type": "democua_condition" +} diff --git a/raw/evaluation_examples/OSWorker/examples/img/img_brightness_001__long.json b/raw/evaluation_examples/OSWorker/examples/img/img_brightness_001__long.json new file mode 100644 index 0000000000000000000000000000000000000000..39e267cd27e70372506346294128dfc2123374b6 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/img/img_brightness_001__long.json @@ -0,0 +1,106 @@ +{ + "id": "img_brightness_001__long", + "snapshot": "gimp", + "instruction": "There are several photos in the 'source_file' folder on the Desktop. For each photo, please open it with GIMP, reduce its brightness, then export and overwrite the original file, close the image in GIMP, and proceed to the next one.", + "source": "https://www.quora.com/How-do-I-edit-a-photo-in-GIMP", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/source_file/photo_1.png", + "path": "/home/user/Desktop/source_file/photo_1.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/source_file/photo_2.png", + "path": "/home/user/Desktop/source_file/photo_2.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/source_file/photo_3.png", + "path": "/home/user/Desktop/source_file/photo_3.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/source_file/photo_4.png", + "path": "/home/user/Desktop/source_file/photo_4.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/source_file/photo_5.png", + "path": "/home/user/Desktop/source_file/photo_5.png" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5", + "related_apps": [ + "gimp" + ], + "evaluator": { + "func": "check_brightness_decrease_and_structure_sim_multiple", + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/photo_1.png", + "/home/user/Desktop/source_file/photo_2.png", + "/home/user/Desktop/source_file/photo_3.png", + "/home/user/Desktop/source_file/photo_4.png", + "/home/user/Desktop/source_file/photo_5.png" + ], + "dest": [ + "local_photo_1.png", + "local_photo_2.png", + "local_photo_3.png", + "local_photo_4.png", + "local_photo_5.png" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/target_file/photo_1.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/target_file/photo_2.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/target_file/photo_3.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/target_file/photo_4.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/7a4deb26-d57d-4ea9-9a73-630f66a7b568_5/target_file/photo_5.png" + ], + "dest": [ + "photo_1.png", + "photo_2.png", + "photo_3.png", + "photo_4.png", + "photo_5.png" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "img", + "app_type": "democua_gimp_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/img/img_contrast_002__long.json b/raw/evaluation_examples/OSWorker/examples/img/img_contrast_002__long.json new file mode 100644 index 0000000000000000000000000000000000000000..077cae68633d31e919eaba88b64816cf8f0b4832 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/img/img_contrast_002__long.json @@ -0,0 +1,106 @@ +{ + "id": "img_contrast_002__long", + "snapshot": "gimp", + "instruction": "There are several photos in the 'source_file' folder on the Desktop. For each photo, please open it with GIMP, boost its contrast to make the main subject stand out more, then export and overwrite the original file, close the image in GIMP, and proceed to the next one.", + "source": "https://www.reddit.com/r/GIMP/comments/12e57w8/how_to_use_gimp_to_exaggerate_contrast/", + "config": [ + { + "type": "download", + "parameters": { + "files": [ + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/source_file/photo_1.png", + "path": "/home/user/Desktop/source_file/photo_1.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/source_file/photo_2.png", + "path": "/home/user/Desktop/source_file/photo_2.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/source_file/photo_3.png", + "path": "/home/user/Desktop/source_file/photo_3.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/source_file/photo_4.png", + "path": "/home/user/Desktop/source_file/photo_4.png" + }, + { + "url": "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/source_file/photo_5.png", + "path": "/home/user/Desktop/source_file/photo_5.png" + } + ] + } + }, + { + "type": "launch", + "parameters": { + "command": [ + "nautilus", + "/home/user/Desktop/source_file" + ] + } + } + ], + "trajectory": "trajectories/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5", + "related_apps": [ + "gimp" + ], + "evaluator": { + "func": "check_contrast_increase_and_structure_sim_multiple", + "result": { + "type": "vm_file", + "multi": true, + "path": [ + "/home/user/Desktop/source_file/photo_1.png", + "/home/user/Desktop/source_file/photo_2.png", + "/home/user/Desktop/source_file/photo_3.png", + "/home/user/Desktop/source_file/photo_4.png", + "/home/user/Desktop/source_file/photo_5.png" + ], + "dest": [ + "local_photo_1.png", + "local_photo_2.png", + "local_photo_3.png", + "local_photo_4.png", + "local_photo_5.png" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + }, + "expected": { + "type": "cloud_file", + "multi": true, + "path": [ + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/target_file/photo_1.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/target_file/photo_2.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/target_file/photo_3.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/target_file/photo_4.png", + "https://huggingface.co/datasets/Selecting/long_repetitive_bench_test/resolve/main/gimp_long/f723c744-e62c-4ae6-98d1-750d3cd7d79d_5/target_file/photo_5.png" + ], + "dest": [ + "photo_1.png", + "photo_2.png", + "photo_3.png", + "photo_4.png", + "photo_5.png" + ], + "gives": [ + 0, + 1, + 2, + 3, + 4 + ] + } + }, + "proxy": false, + "fixed_ip": false, + "possibility_of_env_change": "low", + "domain": "img", + "app_type": "democua_gimp_long" +} diff --git a/raw/evaluation_examples/OSWorker/examples/itops/itops_access_approval_001.json b/raw/evaluation_examples/OSWorker/examples/itops/itops_access_approval_001.json new file mode 100644 index 0000000000000000000000000000000000000000..45494484f29f6ea289ee26dfb51d45da9c678b86 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/itops/itops_access_approval_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Business Systems Administrator at Meridian Labs (a 600-person B2B SaaS company). A single access request ticket just landed in Jira and you need to verify the requester's department in Workday, then record the approval result in the access control Google Sheet.\n\nStep 1 — In Jira (jira_mock), open the 'IT Access Requests' project (projectKey='IAR') and read ticket IAR-312. Its summary is 'Access request: Salesforce read-only for onboarding rep' and its description reads: '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).'\n\nStep 2 — In Workday (workday_mock), look up the employee Tom Becker (employeeId='E-10482'). Confirm his Department field. It should read 'Sales Operations'. If the department is 'Sales Operations', this request is policy-compliant (Salesforce read-only is allowed for Sales Operations).\n\nStep 3 — In Google Sheets (google_sheets_mock), open the 'Access Control Register' workbook and the 'Approvals' sheet. Add a new row at the next available row (currently row 4) with these exact values:\n- Column A (Request ID): 'IAR-312'\n- Column B (Date): '2026-07-01'\n- Column C (Requester): 'Tom Becker'\n- Column D (System): 'Salesforce'\n- Column E (Access Level): 'Read-only'\n- Column F (Department): 'Sales Operations'\n- Column G (Manager Approval): 'Approved'\n- Column H (SysAdmin Decision): 'Approved'\n- Column I (Notes): 'Department verified in Workday (E-10482). Read-only access compliant for Sales Operations.'\n\nDo NOT modify the 3 existing rows (rows 1-3) in the Approvals sheet. Only add the one new row described above. Do NOT post any Slack message for this easy task.", + "instruction_zh": "标签中输出最终译文。 \n你是 Meridian Labs(一家 600 人的 B2B SaaS 公司)的业务系统管理员。一张单独的访问申请工单刚刚到达 Jira,你需要在 Workday 中核实申请人的部门,然后将审批结果记录到访问控制 Google Sheet 中。\n\n步骤 1 — 在 Jira(jira_mock)中,打开 \"IT Access Requests\" 项目(projectKey='IAR'),并读取工单 IAR-312。其摘要为 \"Access request: Salesforce read-only for onboarding rep\",描述内容为:\"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).\"\n\n步骤 2 — 在 Workday(workday_mock)中,查找员工 Tom Becker(employeeId='E-10482')。确认他的 Department 字段。该字段应显示为 \"Sales Operations\"。如果部门是 \"Sales Operations\",则该申请符合策略(Sales Operations 允许使用 Salesforce 只读权限)。\n\n步骤 3 — 在 Google Sheets(google_sheets_mock)中,打开 \"Access Control Register\" 工作簿和 \"Approvals\" 工作表。在下一个可用行(当前为第 4 行)添加一行,填入以下精确值:\n- A 列(Request ID):'IAR-312'\n- B 列(Date):'2026-07-01'\n- C 列(Requester):'Tom Becker'\n- D 列(System):'Salesforce'\n- E 列(Access Level):'Read-only'\n- F 列(Department):'Sales Operations'\n- G 列(Manager Approval):'Approved'\n- H 列(SysAdmin Decision):'Approved'\n- I 列(Notes):'Department verified in Workday (E-10482). Read-only access compliant for Sales Operations.'\n\n请勿修改 Approvals 工作表中已有的 3 行(第 1–3 行)。仅添加上述一行新记录。请勿为此简单任务发送任何 Slack 消息。", + "id": "itops_access_approval_001", + "app_type": "mock_websites", + "generated_at": "2026-07-02T06:14:06.740864", + "adversarial_rounds": "1", + "domain": "itops", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/itops/itops_access_log_003.json b/raw/evaluation_examples/OSWorker/examples/itops/itops_access_log_003.json new file mode 100644 index 0000000000000000000000000000000000000000..f05525c6d4262c67701c212f9a8f49d415d2f160 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/itops/itops_access_log_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are an IT Help Desk / Access Request Manager at Northwind Corp. A Slack access request has just come in and you need to log it in the access audit tracker.\n\nStep 1 — In Slack (slack_mock), open the #it-access-requests channel. Read the most recent message (messageId='msg-req-001') posted by Maya Chen. The message reads:\n'@it-helpdesk Access request: App=Salesforce, Requester=Maya Chen (maya.chen@northwind.io), Manager Approval=Approved by Daniel Okafor (d.okafor@northwind.io). Need read-only CRM access for Q3 sales support.'\n\nStep 2 — In Google Sheets (google_sheets_mock), open the 'Access Audit Log' workbook and the 'Access Log' sheet. Add a new row at the next available row (currently row 5) with these exact values:\n- Column A (Request ID): 'ACC-2026-0701-001'\n- Column B (Date): '2026-07-01'\n- Column C (Requester): 'Maya Chen'\n- Column D (Email): 'maya.chen@northwind.io'\n- Column E (App): 'Salesforce'\n- Column F (Access Level): 'Read-only'\n- Column G (Manager): 'Daniel Okafor'\n- Column H (Approval): 'Approved'\n- Column I (Status): 'Logged'\n\nDo NOT modify the 4 existing rows (rows 1-4) in the Access Log sheet. Only add the one new row described above. Do NOT create a Jira ticket for this easy task.", + "instruction_zh": "你是 Northwind Corp 的 IT 服务台/访问请求管理员。一条 Slack 访问请求刚刚提交,你需要将其记录到访问审计追踪表中。\n\n步骤 1 — 在 Slack(slack_mock)中,打开 #it-access-requests 频道。阅读 Maya Chen 发布的最新的消息(messageId='msg-req-001')。消息内容为:\n'@it-helpdesk Access request: App=Salesforce, Requester=Maya Chen (maya.chen@northwind.io), Manager Approval=Approved by Daniel Okafor (d.okafor@northwind.io). Need read-only CRM access for Q3 sales support.'\n\n步骤 2 — 在 Google Sheets(google_sheets_mock)中,打开 'Access Audit Log' 工作簿和 'Access Log' 工作表。在下一个可用行(当前为第 5 行)添加一行,填入以下准确值:\n- A 列(Request ID):'ACC-2026-0701-001'\n- B 列(Date):'2026-07-01'\n- C 列(Requester):'Maya Chen'\n- D 列(Email):'maya.chen@northwind.io'\n- E 列(App):'Salesforce'\n- F 列(Access Level):'Read-only'\n- G 列(Manager):'Daniel Okafor'\n- H 列(Approval):'Approved'\n- I 列(Status):'Logged'\n\n请勿修改 'Access Log' 工作表中已有的 4 行数据(第 1-4 行)。仅添加上述一行新数据。请勿为此简单任务创建 Jira 工单。", + "id": "itops_access_log_003", + "app_type": "mock_websites", + "generated_at": "2026-07-02T03:58:50.050847", + "adversarial_rounds": "1", + "domain": "itops", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/itops/itops_access_ticket_004.json b/raw/evaluation_examples/OSWorker/examples/itops/itops_access_ticket_004.json new file mode 100644 index 0000000000000000000000000000000000000000..65434cadebffa8c33fc1c3a89f7e882eb7d902fc --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/itops/itops_access_ticket_004.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are an IT Help Desk / Access Request Manager at Northwind Corp. You need to process two access requests that came in via Slack, create Jira tickets for each, log them in the access audit tracker, write a short internal note in a Google Doc, and notify the requesters by email.\n\nStep 1 — In Slack (slack_mock), open the #it-access-requests channel and read the two most recent access request messages:\n- msg-req-101 from Priya Nair (priya.nair@northwind.io): 'Access request: App=Tableau, Requester=Priya Nair, Manager Approval=Approved by Sara Kim (s.kim@northwind.io). Need analyst access to the Q3 finance dashboards.'\n- msg-req-102 from Leo Tran (leo.tran@northwind.io): 'Access request: App=Salesforce, Requester=Leo Tran, Manager Approval=Approved by Daniel Okafor (d.okafor@northwind.io). Need edit access to the accounts module for the new sales campaign.'\n\nStep 2 — In Jira (jira_mock), create one ticket per request in the 'IT Help Desk' project (projectKey='ITHD'):\nFor Priya Nair:\n- Summary: 'Access request: Tableau analyst access for Priya Nair'\n- Description: 'Requester: Priya Nair (priya.nair@northwind.io). App: Tableau. Requested access: Analyst. Manager approval: Sara Kim (s.kim@northwind.io), Approved. Purpose: Q3 finance dashboards.'\n- Issue type: 'Access Request'\n- Priority: 'Medium'\n- Assignee: 'it-helpdesk'\nFor Leo Tran:\n- Summary: 'Access request: Salesforce edit access for Leo Tran'\n- Description: 'Requester: Leo Tran (leo.tran@northwind.io). App: Salesforce. Requested access: Edit (accounts module). Manager approval: Daniel Okafor (d.okafor@northwind.io), Approved. Purpose: New sales campaign.'\n- Issue type: 'Access Request'\n- Priority: 'High'\n- Assignee: 'it-helpdesk'\nRecord the resulting ticket keys (e.g. ITHD-101, ITHD-102).\n\nStep 3 — In Google Sheets (google_sheets_mock), open the 'Access Audit Log' workbook and the 'Access Log' sheet. Add a new row for each request after the last existing row (sheet currently has a header row and 4 existing rows; next available row is row 6):\nFor Priya Nair (row 6): A='ACC-2026-0701-101', B='2026-07-01', C='Priya Nair', D='priya.nair@northwind.io', E='Tableau', F='Analyst', G='Sara Kim', H='Approved', I='Ticket Created', J='ITHD-101'\nFor Leo Tran (row 7): A='ACC-2026-0701-102', B='2026-07-01', C='Leo Tran', D='leo.tran@northwind.io', E='Salesforce', F='Edit', G='Daniel Okafor', H='Approved', I='Ticket Created', J='ITHD-102'\n(Note: the sheet has a 10th column J titled 'Jira Ticket' already present.)\n\nStep 4 — In Google Docs (google_docs_mock), open the document titled 'Access Request Notes'. Add a new bullet under the '2026-07-01' heading:\n'- Processed 2 access requests (Tableau/Priya Nair, Salesforce/Leo Tran). Both manager-approved. Jira tickets ITHD-101 and ITHD-102 created. SLA target: provision within 24h.'\nIf the '2026-07-01' heading does not exist, create it as a Heading 2 first.\n\nStep 5 — In Gmail (gmail_mock), send an email to each requester confirming the ticket:\nTo priya.nair@northwind.io, Subject 'Access request received: Tableau (ITHD-101)', Body 'Hi Priya,\\n\\nWe received your Tableau access request and created Jira ticket ITHD-101. Your manager Sara Kim has approved it. We will provision analyst access to the Q3 finance dashboards within 24 hours.\\n\\nIT Help Desk'\nTo leo.tran@northwind.io, Subject 'Access request received: Salesforce (ITHD-102)', Body 'Hi Leo,\\n\\nWe received your Salesforce access request and created Jira ticket ITHD-102. Your manager Daniel Okafor has approved it. We will provision edit access to the accounts module within 24 hours.\\n\\nIT Help Desk'\n\nDo NOT create tickets for any other Slack messages in the channel. Do NOT modify the 4 existing rows in the Access Log sheet.", + "instruction_zh": "你是 Northwind Corp 的 IT 服务台/访问请求管理员。你需要处理两条通过 Slack 提交的访问请求,分别为其创建 Jira 工单,在访问审计追踪表中记录,在 Google Doc 中撰写一条简短的内部备注,并通过邮件通知请求人。\n\n步骤 1 — 在 Slack(slack_mock)中,打开 #it-access-requests 频道,阅读两条最新的访问请求消息:\n- 来自 Priya Nair(priya.nair@northwind.io)的 msg-req-101:\"Access request: App=Tableau, Requester=Priya Nair, Manager Approval=Approved by Sara Kim (s.kim@northwind.io). Need analyst access to the Q3 finance dashboards.\"\n- 来自 Leo Tran(leo.tran@northwind.io)的 msg-req-102:\"Access request: App=Salesforce, Requester=Leo Tran, Manager Approval=Approved by Daniel Okafor (d.okafor@northwind.io). Need edit access to the accounts module for the new sales campaign.\"\n\n步骤 2 — 在 Jira(jira_mock)中,在 \"IT Help Desk\" 项目(projectKey='ITHD')下为每个请求创建一张工单:\n针对 Priya Nair:\n- 摘要:\"Access request: Tableau analyst access for Priya Nair\"\n- 描述:\"Requester: Priya Nair (priya.nair@northwind.io). App: Tableau. Requested access: Analyst. Manager approval: Sara Kim (s.kim@northwind.io), Approved. Purpose: Q3 finance dashboards.\"\n- 问题类型:\"Access Request\"\n- 优先级:\"Medium\"\n- 经办人:\"it-helpdesk\"\n针对 Leo Tran:\n- 摘要:\"Access request: Salesforce edit access for Leo Tran\"\n- 描述:\"Requester: Leo Tran (leo.tran@northwind.io). App: Salesforce. Requested access: Edit (accounts module). Manager approval: Daniel Okafor (d.okafor@northwind.io), Approved. Purpose: New sales campaign.\"\n- 问题类型:\"Access Request\"\n- 优先级:\"High\"\n- 经办人:\"it-helpdesk\"\n记录生成的工单编号(例如 ITHD-101、ITHD-102)。\n\n步骤 3 — 在 Google Sheets(google_sheets_mock)中,打开 \"Access Audit Log\" 工作簿和 \"Access Log\" 工作表。在最后一行现有数据之后为每个请求添加新行(工作表当前有 1 行标题和 4 行现有数据;下一个可用行是第 6 行):\n针对 Priya Nair(第 6 行):A='ACC-2026-0701-101',B='2026-07-01',C='Priya Nair',D='priya.nair@northwind.io',E='Tableau',F='Analyst',G='Sara Kim',H='Approved',I='Ticket Created',J='ITHD-101'\n针对 Leo Tran(第 7 行):A='ACC-2026-0701-102',B='2026-07-01',C='Leo Tran',D='leo.tran@northwind.io',E='Salesforce',F='Edit',G='Daniel Okafor',H='Approved',I='Ticket Created',J='ITHD-102'\n(注意:工作表已有第 10 列 J,标题为 \"Jira Ticket\"。)\n\n步骤 4 — 在 Google Docs(google_docs_mock)中,打开标题为 \"Access Request Notes\" 的文档。在 \"2026-07-01\" 标题下添加一个新项目符号:\n\"- Processed 2 access requests (Tableau/Priya Nair, Salesforce/Leo Tran). Both manager-approved. Jira tickets ITHD-101 and ITHD-102 created. SLA target: provision within 24h.\"\n如果 \"2026-07-01\" 标题不存在,请先将其创建为二级标题。\n\n步骤 5 — 在 Gmail(gmail_mock)中,向每位请求人发送一封确认工单的邮件:\n收件人 priya.nair@northwind.io,主题 \"Access request received: Tableau (ITHD-101)\",正文 \"Hi Priya,\\n\\nWe received your Tableau access request and created Jira ticket ITHD-101. Your manager Sara Kim has approved it. We will provision analyst access to the Q3 finance dashboards within 24 hours.\\n\\nIT Help Desk\"\n收件人 leo.tran@northwind.io,主题 \"Access request received: Salesforce (ITHD-102)\",正文 \"Hi Leo,\\n\\nWe received your Salesforce access request and created Jira ticket ITHD-102. Your manager Daniel Okafor has approved it. We will provision edit access to the accounts module within 24 hours.\\n\\nIT Help Desk\"\n\n请勿为频道中的其他 Slack 消息创建工单。请勿修改 Access Log 工作表中的 4 行现有数据。", + "id": "itops_access_ticket_004", + "app_type": "mock_websites", + "generated_at": "2026-07-02T04:05:27.211226", + "adversarial_rounds": "2", + "domain": "itops", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/itops/itops_field_change_002.json b/raw/evaluation_examples/OSWorker/examples/itops/itops_field_change_002.json new file mode 100644 index 0000000000000000000000000000000000000000..bf3652fea8e9376518039535b9a1054d2ec3a277 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/itops/itops_field_change_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Business Systems Administrator at Meridian Labs. The sales operations team has requested a change to a Salesforce picklist value and a follow-up field-help text update in HubSpot. You must apply the configuration change in Salesforce, document it in the change runbook in Google Docs, log it in the changes tracker sheet, and notify the requester in Slack.\n\nStep 1 — In Salesforce (salesforce_mock), open the 'Lead' object configuration and locate the 'Lead Source' picklist. It currently contains these values: 'Web', 'Referral', 'Event', 'Partner', 'Outbound'. Add a new picklist value 'Webinar' (label exactly 'Webinar', API name 'Webinar') so the picklist now reads: 'Web', 'Referral', 'Event', 'Partner', 'Outbound', 'Webinar'. Do not remove or rename any existing value.\n\nStep 2 — In HubSpot (hubspot_mock), open the 'Contact' object and locate the 'Lifecycle Stage' property description field. Update its help text (description) from 'Indicates the stage of the contact in the marketing/sales funnel.' to 'Indicates the stage of the contact in the marketing/sales funnel. Webinar-attended contacts should be set to MQL.' Save the property.\n\nStep 3 — In Google Docs (google_docs_mock), open the document titled 'Configuration Change Runbook'. Under the 'Q3 2026 Changes' heading add a new bullet:\n'- CHG-2026-0701: Added Salesforce Lead Source picklist value \"Webinar\" (Lead object). Updated HubSpot Contact \"Lifecycle Stage\" help text to note Webinar-attended -> MQL. Requested by Sales Ops (Linda Hess). Verified by sysadmin.'\nIf the 'Q3 2026 Changes' heading does not exist, create it as a Heading 2 first.\n\nStep 4 — In Google Sheets (google_sheets_mock), open the 'Config Changes' workbook and the 'Change Log' sheet. Add a new row at the next available row (currently row 4) with these exact values:\n- Column A (Change ID): 'CHG-2026-0701'\n- Column B (Date): '2026-07-01'\n- Column C (System): 'Salesforce + HubSpot'\n- Column D (Object): 'Lead Source picklist / Lifecycle Stage property'\n- Column E (Change Summary): 'Added Webinar to Salesforce Lead Source; updated HubSpot Lifecycle Stage help text'\n- Column F (Requested By): 'Linda Hess'\n- Column G (Status): 'Completed'\n\nStep 5 — In Slack (slack_mock), open the #sysadmin-updates channel and post exactly this message:\n'Change completed: CHG-2026-0701. Added \"Webinar\" to the Salesforce Lead Source picklist and updated the HubSpot Lifecycle Stage help text (Webinar-attended -> MQL). Logged in Config Changes tracker and Configuration Change Runbook. Verified by sysadmin. @l.hess please confirm on your side.'\n\nDo NOT modify any other Salesforce picklist, HubSpot property, or runbook heading. Only the described changes are in scope.", + "instruction_zh": "标签中输出最终译文。 \n你是 Meridian Labs 的业务系统管理员。销售运营团队请求修改 Salesforce 的一个 picklist 值,并在 HubSpot 中跟进更新字段帮助文本。你必须在 Salesforce 中应用该配置变更,在 Google Docs 的变更运行手册中记录,在变更跟踪表格中登记,并在 Slack 中通知请求人。\n\n步骤 1 — 在 Salesforce(salesforce_mock)中,打开 'Lead' 对象配置,找到 'Lead Source' picklist。该 picklist 当前包含以下值:'Web'、'Referral'、'Event'、'Partner'、'Outbound'。添加一个新的 picklist 值 'Webinar'(标签必须完全为 'Webinar',API 名称为 'Webinar'),使 picklist 变为:'Web'、'Referral'、'Event'、'Partner'、'Outbound'、'Webinar'。请勿删除或重命名任何现有值。\n\n步骤 2 — 在 HubSpot(hubspot_mock)中,打开 'Contact' 对象,找到 'Lifecycle Stage' 属性的描述字段。将其帮助文本(描述)从 'Indicates the stage of the contact in the marketing/sales funnel.' 更新为 'Indicates the stage of the contact in the marketing/sales funnel. Webinar-attended contacts should be set to MQL.'。保存该属性。\n\n步骤 3 — 在 Google Docs(google_docs_mock)中,打开标题为 'Configuration Change Runbook' 的文档。在 'Q3 2026 Changes' 标题下添加一个新项目符号:\n'- CHG-2026-0701: Added Salesforce Lead Source picklist value \"Webinar\" (Lead object). Updated HubSpot Contact \"Lifecycle Stage\" help text to note Webinar-attended -> MQL. Requested by Sales Ops (Linda Hess). Verified by sysadmin.'\n如果 'Q3 2026 Changes' 标题不存在,请先将其创建为 Heading 2。\n\n步骤 4 — 在 Google Sheets(google_sheets_mock)中,打开 'Config Changes' 工作簿和 'Change Log' 工作表。在下一个可用行(当前为第 4 行)添加一行,填入以下精确值:\n- A 列(Change ID):'CHG-2026-0701'\n- B 列(Date):'2026-07-01'\n- C 列(System):'Salesforce + HubSpot'\n- D 列(Object):'Lead Source picklist / Lifecycle Stage property'\n- E 列(Change Summary):'Added Webinar to Salesforce Lead Source; updated HubSpot Lifecycle Stage help text'\n- F 列(Requested By):'Linda Hess'\n- G 列(Status):'Completed'\n\n步骤 5 — 在 Slack(slack_mock)中,打开 #sysadmin-updates 频道,并准确发布以下消息:\n'Change completed: CHG-2026-0701. Added \"Webinar\" to the Salesforce Lead Source picklist and updated the HubSpot Lifecycle Stage help text (Webinar-attended -> MQL). Logged in Config Changes tracker and Configuration Change Runbook. Verified by sysadmin. @l.hess please confirm on your side.'\n\n请勿修改任何其他 Salesforce picklist、HubSpot 属性或运行手册标题。仅上述描述的变更在范围内。", + "id": "itops_field_change_002", + "app_type": "mock_websites", + "generated_at": "2026-07-02T06:16:35.390677", + "adversarial_rounds": "1", + "domain": "itops", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_campaign_001.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_campaign_001.json new file mode 100644 index 0000000000000000000000000000000000000000..d0329b47bd6b1ac8ea29887413f5d18472fae749 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_campaign_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "We're launching the 'Summer Product Webinar' campaign. In Airtable, create a new record in the 'Campaigns' table with target audience 'Mid-market SaaS marketers', channels 'Email + LinkedIn', and launch date 2026-07-20. Then in Asana, create three execution tasks under the 'Q3 Campaigns' project — 'Draft webinar landing page', 'Build email sequence', and 'Design social assets' — and post a kickoff note in Slack #marketing.", + "id": "mktg_campaign_001", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T16:48:49.218385", + "adversarial_rounds": "1", + "domain": "mktg", + "_source": "minicua", + "instruction_zh": "我们要启动\"Summer Product Webinar\"活动。在 Airtable 的\"Campaigns\"表格中新建一条记录,目标受众为\"Mid-market SaaS marketers\",渠道为\"Email + LinkedIn\",启动日期为 2026-07-20。然后在 Asana 的\"Q3 Campaigns\"项目下创建三个执行任务——\"Draft webinar landing page\"、\"Build email sequence\"和\"Design social assets\"——并在 Slack #marketing 发布一条启动通知。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_campaign_create_004.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_campaign_create_004.json new file mode 100644 index 0000000000000000000000000000000000000000..7079dbb591109414618ca52df4a756044846a0cc --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_campaign_create_004.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Marketing Campaign Manager. Create a new campaign record and its execution task. Step 1: Open Airtable (base 'Campaign Ops', table 'Campaigns'). Create a new record with these exact field values: 'Campaign Name' = 'Summer SaaS Launch 2026'; 'Target Audience' = 'Mid-market SaaS operations leaders'; 'Channels' = 'Email, LinkedIn, Webinar'; 'Launch Date' = '2026-07-15'; 'Status' = 'Planned'. Step 2: Open Asana (project 'Campaign Execution'). Create a task titled 'Execute: Summer SaaS Launch 2026' assigned to you, with the description 'Run Email + LinkedIn + Webinar per Airtable plan; launch 2026-07-15', and set the due date to 2026-07-15. Do not modify any other Airtable records or Asana tasks.", + "instruction_zh": "你是一名营销活动经理。请创建一条新的营销活动记录及其执行任务。步骤1:打开 Airtable(base 'Campaign Ops',table 'Campaigns')。创建一条新记录,并填入以下确切的字段值:'Campaign Name' = 'Summer SaaS Launch 2026';'Target Audience' = 'Mid-market SaaS operations leaders';'Channels' = 'Email, LinkedIn, Webinar';'Launch Date' = '2026-07-15';'Status' = 'Planned'。步骤2:打开 Asana(project 'Campaign Execution')。创建一个任务,标题为 'Execute: Summer SaaS Launch 2026',指派给你自己,描述填写为 'Run Email + LinkedIn + Webinar per Airtable plan; launch 2026-07-15',并将截止日期设为 2026-07-15。请勿修改任何其他 Airtable 记录或 Asana 任务。", + "id": "mktg_campaign_create_004", + "app_type": "libreoffice_calc", + "generated_at": "2026-07-02T08:50:09.906307", + "adversarial_rounds": "3", + "domain": "mktg", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_field_reconcile_006.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_field_reconcile_006.json new file mode 100644 index 0000000000000000000000000000000000000000..390bfda35af1290d7e32ad54350baacb70013cb6 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_field_reconcile_006.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Marketing Operations / Growth Analyst at a 200-person B2B SaaS company. We keep our target account list in Google Sheets and our working lead records in HubSpot. Compare the two and fix the lifecycle-stage gaps. In Google Sheets (workbook 'Target Accounts Q3'), the 'Accounts' sheet lists 12 target accounts in rows 2-13 with columns A 'Company', B 'Domain', C 'Lifecycle Stage'. In HubSpot, the 'Leads' view has 12 lead records keyed by the same domains. Three leads are missing a Lifecycle Stage value in HubSpot that the Sheets list already has: northwindcloud.com (should be 'Lead'), lumendata.io ('MQL'), and vectorlabs.ai ('SQL'). For each of those three, open the HubSpot lead record by domain and set its Lifecycle Stage dropdown to the value shown in the Sheets 'Accounts' sheet (northwindcloud.com -> Lead, lumendata.io -> MQL, vectorlabs.ai -> SQL). Leave all other lead records unchanged. Do not edit the Sheets file.", + "instruction_zh": "你是一家200人规模的B2B SaaS公司的营销运营/增长分析师。我们的目标账户列表保存在 Google Sheets 中,工作线索记录保存在 HubSpot 中。请对比两者并修复生命周期阶段的缺口。在 Google Sheets(工作簿名为 'Target Accounts Q3')中,'Accounts' 工作表在第2-13行列出了12个目标账户,其中A列是 'Company',B列是 'Domain',C列是 'Lifecycle Stage'。在 HubSpot中,'Leads' 视图中有12条以相同域名为键的线索记录。有三条线索在 HubSpot 中缺少生命周期阶段值,而 Sheets 列表中已有:northwindcloud.com(应为 'Lead')、lumendata.io('MQL')和 vectorlabs.ai('SQL')。对这三条线索中的每一条,在 HubSpot 中按域名打开线索记录,并将其生命周期阶段下拉菜单设置为 Sheets 'Accounts' 工作表中显示的值(northwindcloud.com -> Lead,lumendata.io -> MQL,vectorlabs.ai -> SQL)。其余线索记录均保持不变。不要编辑 Sheets 文件。", + "id": "mktg_field_reconcile_006", + "app_type": "libreoffice_calc", + "generated_at": "2026-07-02T08:28:39.103157", + "adversarial_rounds": "1", + "domain": "mktg", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_funnel_report_007.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_funnel_report_007.json new file mode 100644 index 0000000000000000000000000000000000000000..6af45355dfe6e7007da85039685ebb53e301a5f5 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_funnel_report_007.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Marketing Operations / Growth Analyst. Produce this week's funnel report and send the pipeline-vs-target summary to Slack. Step 1: Open Google Sheets (workbook 'Growth Funnel Q3', sheet 'Weekly'). The sheet has a 'Target' table (rows 2-7: Stage in A, Weekly Target in B) and a 'Current' table (rows 10-15: Stage in A, Actual in B, Source System in C). Targets: Leads 500, MQLs 180, SQLs 70, Opportunities 28, Customers 9. Current actuals to enter: Leads 472 (source HubSpot), MQLs 165 (source HubSpot), SQLs 63 (source Salesforce), Opportunities 24 (source Salesforce), Customers 7 (source Salesforce). Fill the 'Current' B column with those actuals and the C column ('Source System') with the stated source for each row. In column D compute the variance (Actual - Target) for each stage. Step 2: In Salesforce ('Campaign Attribution' report) confirm the SQL=63 / Opportunity=24 / Customer=7 figures match the 'Pipeline Report' object (they do); note any stage where Actual < Target by more than 10% — that is MQLs (165 vs 180, -8.3%, NOT flagged) and Customers (7 vs 9, -22.2%, FLAGGED). Step 3: Open Google Docs and create a new document titled 'Weekly Funnel Report - 2026-W27'. Add an H1 title 'Weekly Funnel Report (2026-W27)', then a 'Summary' section with one sentence: 'Pipeline is tracking 4% below target on volume; Customers are the at-risk stage at -22.2% vs goal.' Then a 'Stage Detail' table with columns Stage | Target | Actual | Variance | Source, listing all 5 stages with the values above. Then an 'At-Risk' section naming 'Customers (7 vs 9, -22.2%)' as the flagged stage and 'Recommendation: launch win-back nurture to the 2 slipped customers and review close-rate with Sales.' Step 4: In Slack post to #growth-reviews: 'Weekly Funnel 2026-W27 — Pipeline vs Target: Leads 472/500, MQLs 165/180, SQLs 63/70, Opps 24/28, Customers 7/9. At-risk: Customers -22.2%. Full report: .' Use the actual doc URL as the link.", + "instruction_zh": "你是 Marketing Operations / Growth Analyst。请生成本周的漏斗报告,并将 pipeline-vs-target 摘要发送至 Slack。\n\n步骤 1:打开 Google Sheets(工作簿 'Growth Funnel Q3',工作表 'Weekly')。该工作表中包含一个 'Target' 表格(第 2–7 行:A 列为 Stage,B 列为 Weekly Target)和一个 'Current' 表格(第 10–15 行:A 列为 Stage,B 列为 Actual,C 列为 Source System)。目标值:Leads 500、MQLs 180、SQLs 70、Opportunities 28、Customers 9。需录入的当前实际值:Leads 472(来源 HubSpot)、MQLs 165(来源 HubSpot)、SQLs 63(来源 Salesforce)、Opportunities 24(来源 Salesforce)、Customers 7(来源 Salesforce)。请在 'Current' 表格的 B 列填入上述实际值,在 C 列('Source System')填入每行对应的来源。在 D 列计算每个阶段的 variance(Actual - Target)。\n\n步骤 2:在 Salesforce('Campaign Attribution' 报告)中确认 SQL=63 / Opportunity=24 / Customer=7 这些数据与 'Pipeline Report' 对象一致(确实一致);记录所有 Actual < Target 且差距超过 10% 的阶段——即 MQLs(165 vs 180,-8.3%,不标记)和 Customers(7 vs 9,-22.2%,标记)。\n\n步骤 3:打开 Google Docs,新建一个标题为 'Weekly Funnel Report - 2026-W27' 的文档。添加一个 H1 标题 'Weekly Funnel Report (2026-W27)',然后添加一个 'Summary' 部分,其中包含一句话:\"Pipeline is tracking 4% below target on volume; Customers are the at-risk stage at -22.2% vs goal.\" 接着添加一个 'Stage Detail' 表格,列名为 Stage | Target | Actual | Variance | Source,列出上述全部 5 个阶段及其对应数值。然后添加一个 'At-Risk' 部分,将 'Customers (7 vs 9, -22.2%)' 列为标记阶段,并写出建议:\"Recommendation: launch win-back nurture to the 2 slipped customers and review close-rate with Sales.\"\n\n步骤 4:在 Slack中向 #growth-reviews 频道发布消息:\"Weekly Funnel 2026-W27 — Pipeline vs Target: Leads 472/500, MQLs 165/180, SQLs 63/70, Opps 24/28, Customers 7/9. At-risk: Customers -22.2%. Full report: .\" 请使用你实际创建的 Google Doc 的 URL 作为链接。", + "id": "mktg_funnel_report_007", + "app_type": "libreoffice_calc", + "generated_at": "2026-07-02T08:31:45.333502", + "adversarial_rounds": "2", + "domain": "mktg", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_inbound_qualify_009__long.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_inbound_qualify_009__long.json new file mode 100644 index 0000000000000000000000000000000000000000..7a7b679f596793254339c6d13a247c997d269e25 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_inbound_qualify_009__long.json @@ -0,0 +1,77 @@ +{ + "id": "mktg_inbound_qualify_009__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou're Riley in marketing ops, qualifying this morning's inbound contacts in HubSpot Marketing. Each contact has an Original Source shown on its detail page. Use the 'Lead Tier Playbook' Google Doc as the single source of truth for tier assignment -- do not guess. The playbook says:\n\n- If the contact's Lifecycle Stage is already Customer, leave it completely untouched (not a fresh lead).\n- Otherwise, map Original Source to tier:\n * demo_request -> HOT\n * gated_content -> WARM\n * webinar -> WARM\n * newsletter -> COLD\n\nRoute every one of these contacts by tier by inline-editing its properties on the contact's detail page:\n\n- HOT: set Lifecycle Stage to Sales Qualified Lead, and set Contact Owner to the Account Executive who owns that contact's company territory (see the AE Territory table in the Lead Tier Playbook).\n- WARM: set Lifecycle Stage to Marketing Qualified Lead, and set Contact Owner to the nurture rep (Nadia Cole).\n- COLD: leave the Lifecycle Stage as it is, and set Contact Owner to the Unassigned Queue.\n\nFor each HOT contact only: in the Google Docs 'AE Briefing' document, add a briefing row that includes the contact's full name and company, and share that document with the routed AE (type the AE's email into the Share dialog, editor access). Then, in Google Drive, move the 'AE Briefing' document into the 'Sales Handoff' folder.\n\nFinally, post a short routing summary to the Slack #marketing channel (how many contacts you routed as SQL, MQL, and unassigned) and pin that message.", + "app_type": "hubspot_marketing_mock,google_docs_mock,google_drive_mock,slack_mock", + "domain": "mktg", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_leadhandoff_002.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_leadhandoff_002.json new file mode 100644 index 0000000000000000000000000000000000000000..a4963db4f44cf84b7477466135e1eb901af9faf5 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_leadhandoff_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "The 'Product Demo Request' campaign generated qualified leads ready for sales. In HubSpot, there are 8 contacts currently in the 'MQL' lifecycle stage that are Unassigned. Open each of these 8 contacts, and in its edit panel set the 'Assigned To' / 'Owner' field to the sales rep 'Jordan Blake' and save (there is no bulk-assign action, so update the contacts one by one). Then log the handoff in the Airtable 'Lead Handoff' table (Campaign = Product Demo Request, Lead Count = 8, Assigned To = Jordan Blake, Handoff Date = today's date), and post a message in Slack #sales-handoff that @mentions Jordan asking him to follow up on the 8 leads.", + "id": "mktg_leadhandoff_002", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T17:23:04.390644", + "adversarial_rounds": "1", + "domain": "mktg", + "_source": "minicua", + "instruction_zh": "“Product Demo Request”营销活动生成了已准备好对接销售的合格线索。在 HubSpot 中,当前有 8 个处于“MQL”生命周期阶段且为 Unassigned 的联系人。逐个打开这 8 个联系人,在其编辑面板中将“Assigned To”/“Owner”字段设置为销售代表“Jordan Blake”并保存(没有批量分配操作,因此需要逐个更新联系人)。然后在 Airtable 的“Lead Handoff”表中记录此次交接(Campaign = Product Demo Request,Lead Count = 8,Assigned To = Jordan Blake,Handoff Date = 今天的日期),并在 Slack 频道 #sales-handoff 中发布一条消息,@提及 Jordan,请他跟进这 8 条线索。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_perf_report_005.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_perf_report_005.json new file mode 100644 index 0000000000000000000000000000000000000000..0858191e348c39ac4fcd550807cac208c5283aea --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_perf_report_005.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Marketing Campaign Manager running the post-campaign performance pull. Step 1: Open HubSpot ('Campaign Performance' report for 'Spring Nurture 2026'). Read the three metrics: MQLs = 312, Open Rate = 38.4%, Conversion Rate = 4.9%. Step 2: Open Google Sheets (workbook 'Campaign Reports 2026', sheet 'Performance'). Row 2 is the header; row 3 is the 'Spring Nurture 2026' row with columns A 'Campaign', B 'MQLs', C 'Open Rate', D 'Conversion Rate', E 'Source'. Set B3 = 312, C3 = 38.4%, D3 = 4.9%, E3 = 'HubSpot'. Step 3: In Airtable (base 'Campaign Ops', table 'Campaigns') find the record 'Spring Nurture 2026' and set its 'Status' field to 'Reported'. Step 4: In Slack post to #campaign-reporting: 'Spring Nurture 2026 performance — MQLs: 312, Open Rate: 38.4%, Conversion: 4.9% (source: HubSpot). Logged to Campaign Reports 2026 sheet.'. Step 5: Send a Gmail to cmo@northwindcloud.com with subject 'Spring Nurture 2026 — Performance Summary' and body 'Hi — Spring Nurture 2026 closed with 312 MQLs, 38.4% open rate, and 4.9% conversion (per HubSpot). Full numbers are in the Campaign Reports 2026 sheet. Best, Marketing Campaign Mgmt.'. Do not alter any other rows in the sheet or other Airtable records.", + "instruction_zh": "标签包裹。 你是一名营销活动经理,正在执行营销活动结束后的绩效数据提取。步骤1:打开 HubSpot,查看 'Spring Nurture 2026' 的 'Campaign Performance' 报告。读取三个指标:MQLs = 312、Open Rate = 38.4%、Conversion Rate = 4.9%。步骤2:打开 Google Sheets(工作簿 'Campaign Reports 2026',工作表 'Performance')。第2行为表头;第3行为 'Spring Nurture 2026' 所在行,其中A列是 'Campaign'、B列是 'MQLs'、C列是 'Open Rate'、D列是 'Conversion Rate'、E列是 'Source'。设置 B3 = 312、C3 = 38.4%、D3 = 4.9%、E3 = 'HubSpot'。步骤3:在 Airtable(数据库 'Campaign Ops',表格 'Campaigns')中找到记录 'Spring Nurture 2026',并将其 'Status' 字段设置为 'Reported'。步骤4:在 Slack中向 #campaign-reporting 频道发送消息:'Spring Nurture 2026 performance — MQLs: 312, Open Rate: 38.4%, Conversion: 4.9% (source: HubSpot). Logged to Campaign Reports 2026 sheet.'。步骤5:通过 Gmail向 cmo@northwindcloud.com 发送邮件,主题为 'Spring Nurture 2026 — Performance Summary',正文为 'Hi — Spring Nurture 2026 closed with 312 MQLs, 38.4% open rate, and 4.9% conversion (per HubSpot). Full numbers are in the Campaign Reports 2026 sheet. Best, Marketing Campaign Mgmt.'。请勿修改表格中的其他行或其他 Airtable 记录。", + "id": "mktg_perf_report_005", + "app_type": "libreoffice_calc", + "generated_at": "2026-07-02T08:47:13.624356", + "adversarial_rounds": "2", + "domain": "mktg", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_report_003.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_report_003.json new file mode 100644 index 0000000000000000000000000000000000000000..97b21d1982756827dda2f7f110b0599851279d7e --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_report_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "The latest results for the 'Spring Nurture' email campaign are: 142 MQLs, a 38.5% email open rate, and a 4.2% conversion rate. Enter these three numbers into the 'Campaign Performance' Google Sheet in the row for Spring Nurture (the MQLs, Open Rate, and Conversion Rate columns), then post a one-line summary of these results in Slack #marketing.", + "id": "mktg_report_003", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T16:50:36.900523", + "adversarial_rounds": "1", + "domain": "mktg", + "_source": "minicua", + "instruction_zh": "“Spring Nurture”邮件营销活动的最新结果为:142个MQL、38.5%的邮件打开率和4.2%的转化率。请将这三个数字输入到'Campaign Performance' Google Sheet中Spring Nurture所在行的对应列(MQLs、Open Rate和Conversion Rate列),然后在Slack #marketing中发布这些结果的一句话摘要。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_social_approve_010.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_social_approve_010.json new file mode 100644 index 0000000000000000000000000000000000000000..b3d3eb59819b5f8ba7ff0d85d83c6837ef7a7d15 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_social_approve_010.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are the Social Media Manager at Northwind Co. A new LinkedIn post draft needs to move into the legal review stage before it can be published.\n\nIn Trello (trello_mock), open the 'Content Pipeline' board. Find the card titled 'Post: Q3 Product Launch Teaser (LinkedIn)' which is currently in the 'Draft' list. Move that card from the 'Draft' list to the 'Legal Review' list.\n\nDo NOT move or modify any other card on the board. Only the single card 'Post: Q3 Product Launch Teaser (LinkedIn)' should be changed.", + "instruction_zh": "你是 Northwind Co. 的社交媒体经理。一篇新的 LinkedIn 帖子草稿在发布前需要进入法务审核阶段。\n\n在 Trello(trello_mock)中,打开 'Content Pipeline' 看板。找到标题为 'Post: Q3 Product Launch Teaser (LinkedIn)' 的卡片,该卡片当前位于 'Draft' 列表中。将该卡片从 'Draft' 列表移动到 'Legal Review' 列表。\n\n请勿移动或修改看板上的任何其他卡片。只应更改单张卡片 'Post: Q3 Product Launch Teaser (LinkedIn)'。", + "id": "mktg_social_approve_010", + "app_type": "mock_websites", + "generated_at": "2026-07-02T03:20:07.177376", + "adversarial_rounds": "1", + "domain": "mktg", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_webinar_guide_011.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_webinar_guide_011.json new file mode 100644 index 0000000000000000000000000000000000000000..5be8059772e2f9452a49552d7fb9a457a470c238 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_webinar_guide_011.json @@ -0,0 +1,80 @@ +{ + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "id": "mktg_webinar_guide_011", + "difficulty": "hard", + "instruction": "Prepare next month's customer webinar on our reporting module. In Notion, create a page titled 'Reporting Webinar Guide' whose body lays out five run-of-show steps: Intro, Live demo, Q&A, Resources, and Follow-up. Schedule the webinar on Google Calendar titled 'Reporting Module Webinar' for July 9. Add a Trello card 'Send webinar follow-up' to the To Do list so we don't forget the recap. Finally, email the customer community contact (community@company.com) announcing the July 9 webinar.", + "instruction_zh": "筹备下个月关于我们报告模块的客户网络研讨会。在 Notion 中创建一个标题为 'Reporting Webinar Guide' 的页面,在正文中列出五个流程步骤:开场介绍、现场演示、问答环节、资料资源和后续跟进。在 Google Calendar 中安排一场标题为 'Reporting Module Webinar' 的网络研讨会,日期为 July 9。在 Trello 的 To Do 列表中添加一张名为 'Send webinar follow-up' 的卡片,以免忘记发送会后回顾。最后,给客户社区联系人(community@company.com)发送邮件,宣布 July 9 的网络研讨会。", + "app_type": "notion_mock", + "persona": "You are an office worker acting as a product manager. Your tools for this task are: the Notion workspace, the team calendar, the Trello board, the shared email inbox.", + "context": "Initial environment (seeded via a single shared session id across all mocks): Notion workspace with pages 'Knowledge Base'; an empty Google Calendar; Trello 'Project Alpha' board with lists To Do, Doing, Done; Gmail inbox with 1 email(s): \"Next webinar?\" from community@company.com. GROUND TRUTH — the agent earns partial credit for each checkpoint: webinar guide page created (+0.15); guide has the 5 run-of-show steps (+0.25); cal_new_event (+0.1); webinar on July 9 (+0.1); follow-up Trello card (+0.1); card in To Do (+0.1); gmail_new_sent (+0.05); emailed community contact (+0.1); names the July 9 webinar (+0.05). 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.", + "domain": "mktg", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/mktg/mktg_webinar_mql_008.json b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_webinar_mql_008.json new file mode 100644 index 0000000000000000000000000000000000000000..07e9691fc98003952de8c052b668aa5572d12cb5 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/mktg/mktg_webinar_mql_008.json @@ -0,0 +1,79 @@ +{ + "instruction": "You are a Marketing Operations / Growth Analyst. We just ran the 'Q3 Product Launch Webinar' and have an attendee export to turn into a tracked list and push qualified leads into HubSpot as MQLs. Step 1: Open Airtable (base 'Marketing Ops', table 'Webinar Attendees'). Create a new record for each of the 8 attendees listed below in the 'Attendee Name' / 'Email' / 'Company' / 'Attended Live?' / 'Qualified?' columns. Attendees: (1) Priya Nair, priya.nair@cobaltstack.io, Cobalt Stack, Yes, Yes; (2) Marcus Lee, marcus.lee@denovaworks.com, Denova Works, Yes, Yes; (3) Sofia Romano, sofia.romano@everlytics.io, Everlytics, No, Yes; (4) Tom Becker, tom.becker@finchpay.com, Finch Pay, Yes, No; (5) Aisha Khan, aisha.khan@heliosys.com, Heliosys, No, Yes; (6) Diego Alvarez, diego.alvarez@ironcladlabs.io, Ironclad Labs, Yes, Yes; (7) Lena Hofer, lena.hofer@greydesk.com, GreyDesk, No, No; (8) Ben Carter, ben.carter@bexter.com, Bexter, Yes, No. Step 2: The 5 attendees marked 'Qualified? = Yes' (Priya Nair, Marcus Lee, Sofia Romano, Aisha Khan, Diego Alvarez) are the qualified leads. For each of those 5, open HubSpot, find or create the lead record by email, and set its Lifecycle Stage to 'MQL'. Step 3: In Airtable, on each of those 5 qualified records set the 'Pushed to HubSpot?' field to 'Yes'. Do not change the 3 unqualified attendees' HubSpot records. Step 4: In Slack, post a message to the #marketing-ops channel that says: 'Q3 Product Launch Webinar: 8 attendees, 5 qualified (Priya Nair, Marcus Lee, Sofia Romano, Aisha Khan, Diego Alvarez) pushed to HubSpot as MQLs. 3 not qualified (Tom Becker, Lena Hofer, Ben Carter).'", + "instruction_zh": "你是一名营销运营/增长分析师。我们刚刚举办了\"Q3 Product Launch Webinar\",现有一份参会者导出名单,需要将其转化为可跟踪的列表,并将符合条件的潜在客户作为MQL推送到HubSpot。\n\n步骤1:打开Airtable(base \"Marketing Ops\",表格\"Webinar Attendees\")。为下方列出的8位参会者分别在\"Attendee Name\"/\"Email\"/\"Company\"/\"Attended Live?\"/\"Qualified?\"列中创建新记录。参会者:(1) Priya Nair, priya.nair@cobaltstack.io, Cobalt Stack, Yes, Yes;(2) Marcus Lee, marcus.lee@denovaworks.com, Denova Works, Yes, Yes;(3) Sofia Romano, sofia.romano@everlytics.io, Everlytics, No, Yes;(4) Tom Becker, tom.becker@finchpay.com, Finch Pay, Yes, No;(5) Aisha Khan, aisha.khan@heliosys.com, Heliosys, No, Yes;(6) Diego Alvarez, diego.alvarez@ironcladlabs.io, Ironclad Labs, Yes, Yes;(7) Lena Hofer, lena.hofer@greydesk.com, GreyDesk, No, No;(8) Ben Carter, ben.carter@bexter.com, Bexter, Yes, No。\n\n步骤2:标记为\"Qualified? = Yes\"的5位参会者(Priya Nair、Marcus Lee、Sofia Romano、Aisha Khan、Diego Alvarez)即为合格潜在客户。针对这5人,打开HubSpot,通过邮箱查找或创建潜在客户记录,将其Lifecycle Stage设置为\"MQL\"。\n\n步骤3:在Airtable中,将这5条合格记录的\"Pushed to HubSpot?\"字段设置为\"Yes\"。不要修改3位不合格参会者的HubSpot记录。\n\n步骤4:在Slack中,向#marketing-ops频道发送一条消息,内容为:\"Q3 Product Launch Webinar: 8 attendees, 5 qualified (Priya Nair, Marcus Lee, Sofia Romano, Aisha Khan, Diego Alvarez) pushed to HubSpot as MQLs. 3 not qualified (Tom Becker, Lena Hofer, Ben Carter).\"", + "id": "mktg_webinar_mql_008", + "app_type": "libreoffice_calc", + "generated_at": "2026-07-02T08:27:24.313866", + "adversarial_rounds": "1", + "domain": "mktg", + "_source": "cua_gym", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/pm/pm_board_sync_003.json b/raw/evaluation_examples/OSWorker/examples/pm/pm_board_sync_003.json new file mode 100644 index 0000000000000000000000000000000000000000..6299fb60455b55e75681e3e9e533aa9017ffeb9a --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/pm/pm_board_sync_003.json @@ -0,0 +1,80 @@ +{ + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "id": "pm_board_sync_003", + "difficulty": "hard", + "instruction": "Keep the PMO board in sync with engineering. In Jira, the 'Payments API hardening' story (KAN-7) is now In Progress. Reflect that on the Trello PMO board: move the 'Payments API hardening' card from the To Do list into the Doing list. Don't move the unrelated 'Marketing site refresh' card. Then mark KAN-7 itself as 'In Progress' if it isn't already, and post in #general that payments hardening is underway and tracked in both tools.", + "instruction_zh": "保持 PMO board 与工程团队同步。在 Jira 中,'Payments API hardening' 故事(KAN-7)当前已是 In Progress 状态。请在 Trello 的 PMO board 上同步这一状态:将 'Payments API hardening' 卡片从 To Do 列表移到 Doing 列表。不要移动无关的 'Marketing site refresh' 卡片。随后,如果 KAN-7 本身还未标记为 In Progress,请将其标记为 In Progress,并在 #general 频道发帖说明 payments hardening 正在进行,且已在两个工具中同步跟踪。", + "app_type": "trello_mock", + "persona": "You are an office worker acting as a project coordinator. Your tools for this task are: the Trello board, the Jira project board, team communications.", + "context": "Initial environment (seeded via a single shared session id across all mocks): Trello 'Project Alpha' board with lists To Do, Doing, Done; Jira Kanban project with issues KAN-1(Done), KAN-7(To Do); Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: Payments card moved to Doing (+0.45); KAN-7 set to In Progress (+0.3); slack_new_msg (+0.1); announces payments hardening (+0.15). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0.", + "domain": "pm", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/pm/pm_sprint_closeout_002__long.json b/raw/evaluation_examples/OSWorker/examples/pm/pm_sprint_closeout_002__long.json new file mode 100644 index 0000000000000000000000000000000000000000..8f0c57d9522c2933e316f9f84895185ed9b2b489 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/pm/pm_sprint_closeout_002__long.json @@ -0,0 +1,77 @@ +{ + "id": "pm_sprint_closeout_002__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou're Lena, the agile PM closing out the current sprint for the Apollo Platform project in Jira. Wrap up the sprint that is currently running: work that finished stays counted against this sprint. For the unfinished work, the team already talked through what to do with each item during the sprint standup discussion over in Discord -- follow those calls: whatever the team agreed to carry forward gets moved into the next sprint so they pick it up there, and whatever they decided to drop goes back to the backlog. Once the unfinished items are sorted the way the team decided, finish closing out the sprint.\n\nIn the 'Sprint Carryover' project in Asana, each unfinished item has a card waiting in the Triage column. File each card by the priority that Jira has on record for that item: High priority into 'Critical', Medium into 'Standard', and Low into 'Backlog'.\n\nRecord the outcome of every issue from the sprint in the 'Sprint Report' Google Sheet, marking each one 'Completed' or 'Carried Over' in the Disposition column. Finally, post a wrap-up in the Discord #standup channel stating how many issues were completed and how many were carried over.", + "app_type": "jira_mock,asana_mock,discord_mock,google_sheets_mock", + "domain": "pm", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/pm/pm_sprint_planning_001__long.json b/raw/evaluation_examples/OSWorker/examples/pm/pm_sprint_planning_001__long.json new file mode 100644 index 0000000000000000000000000000000000000000..22f6426ce5b173fc672df324433f807a9741dfb4 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/pm/pm_sprint_planning_001__long.json @@ -0,0 +1,77 @@ +{ + "id": "pm_sprint_planning_001__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou're Dana, the delivery manager running Sprint 24 planning. In Asana, the 'Sprint 24' project holds the candidate backlog. Decide which candidates the team is committing to this sprint, then set each committed task up across the tools.\n\nFor every task you commit to: assign it to the right owner and give it a due date in Asana; add a row for it to the 'Sprint Plan' database in Notion; and create a kickoff meeting in Google Calendar. Match each task to the engineer whose discipline fits the work: server-side or API work goes to the Backend Engineer, work in the mobile (iOS/Android) app goes to the Mobile Engineer, and web frontend or general work goes to the Senior Engineer. Each engineer's role is shown on their Slack profile.\n\nWhen you're done, post a summary of the sprint commitment to the Slack channel #delivery and pin it.", + "app_type": "asana_mock,notion_mock,slack_mock,google_calendar_mock", + "domain": "pm", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/qa/qa_bug_escalate_004.json b/raw/evaluation_examples/OSWorker/examples/qa/qa_bug_escalate_004.json new file mode 100644 index 0000000000000000000000000000000000000000..ac1d3b39314d1c6d7ecef502f507505324b1f240 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/qa/qa_bug_escalate_004.json @@ -0,0 +1,80 @@ +{ + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "id": "qa_bug_escalate_004", + "difficulty": "hard", + "instruction": "Customers are reporting checkout failures with a payment timeout. Find the matching bug on the Kanban board (it's the one about payment checkout timing out), move it to 'In Progress', and open a matching issue in the GitLab backend-api project titled 'Payment checkout timeout' so the code work is tracked there. Then add a concrete troubleshooting step to the 'Payments Runbook' page in Notion — specifically to raise the payment gateway timeout and retry idempotently — and paste a pointer to that runbook back onto the Jira bug as a comment. Finally, note in #engineering which issue you're working. Leave the other board items alone.", + "instruction_zh": "客户报告结账时因支付超时而失败。请在 Kanban 看板上找到对应的 bug(即关于支付结账超时的问题),将其移动到 'In Progress',并在 GitLab 的 backend-api 项目中创建一个标题为 'Payment checkout timeout' 的对应 issue,以便在那里跟踪代码工作。然后在 Notion 的 'Payments Runbook' 页面中添加一个具体的故障排查步骤——特别是提高支付网关的超时时间并进行幂等重试——并将该运行手册的链接作为评论粘贴回 Jira bug 上。最后,在 #engineering 频道中说明你正在处理哪个 issue。不要动看板上的其他事项。", + "app_type": "jira_mock", + "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.", + "context": "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.", + "domain": "qa", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/qa/qa_defect_triage_001__long.json b/raw/evaluation_examples/OSWorker/examples/qa/qa_defect_triage_001__long.json new file mode 100644 index 0000000000000000000000000000000000000000..60b99ee8ca3a2f83bb262bc845bfc93a9182a398 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/qa/qa_defect_triage_001__long.json @@ -0,0 +1,77 @@ +{ + "id": "qa_defect_triage_001__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou're Quinn, the QA engineer running defect triage for the 'Checkout & Payments' project in Jira. Each open defect carries a severity label, but they're scattered through a long backlog mixed in with already-resolved and non-defect items. Triage the open defects by severity: Critical defects should be set to priority Highest and assigned to Sarah Connor; Major defects should be set to priority High and assigned to John Smith.\n\nIn GitLab's 'web-checkout' project, for every high-risk security finding (Critical or High severity), raise a tracking issue from it and move that issue into the 'In Progress' column. Each of those findings corresponds to one of the open Jira defects -- once you've raised the tracking issue, record its issue number on the matching Jira defect so the two are linked.\n\nRecord each defect you triage in the 'Defect Triage' Google Sheet (its key, severity, new priority, and assignee); the first row, KAN-000, is a filled-in example showing the format. Finally, post a summary to the Discord #qa channel including the number of defects you triaged.", + "app_type": "jira_mock,gitlab_mock,discord_mock,google_sheets_mock", + "domain": "qa", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/qa/qa_pr_latency_002.json b/raw/evaluation_examples/OSWorker/examples/qa/qa_pr_latency_002.json new file mode 100644 index 0000000000000000000000000000000000000000..dde55bc6cae3cb88e5ec0aab841bc8f57a64e8d7 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/qa/qa_pr_latency_002.json @@ -0,0 +1,80 @@ +{ + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "id": "qa_pr_latency_002", + "difficulty": "hard", + "instruction": "Review latency is our sprint-health risk this week. Today is June 23, 2026. Look at the open PRs in hello-world: PR #12 'Add caching layer to API' was opened June 20 and is still unreviewed; PR #13 'Fix typo in README' was opened today. Our rule flags any PR open more than 2 days without review. Log the flagged PR into the 'Review Latency' sheet at row 2 (PR number in column A, title in column B, days open in column C). Then nudge the reviewer in #engineering naming the flagged PR number so it gets reviewed today, and in Lattice leave written feedback for James Kim about keeping review latency down ahead of our 1:1. Don't flag the PR opened today.", + "instruction_zh": "代码评审延迟是我们本周冲刺健康度的风险所在。今天是 June 23, 2026。查看 hello-world 中尚未关闭的 PR:PR #12 'Add caching layer to API' 于 June 20 开启,至今仍未被评审;PR #13 'Fix typo in README' 于今天开启。按照我们的规则,任何开启超过 2 天且未被评审的 PR 都会被标记。将被标记的 PR 录入 'Review Latency' 表格的第 2 行(A 列填 PR 编号,B 列填标题,C 列填开启天数)。然后在 #engineering 频道提醒评审人,报出被标记的 PR 编号,以便今天完成评审,并在 Lattice 中给 James Kim 留下书面反馈,提醒他在我们的 1:1 之前降低评审延迟。不要标记今天开启的 PR。", + "app_type": "github_mock", + "persona": "You are an office worker acting as a release engineer. Your tools for this task are: the GitHub repositories, shared spreadsheets, team communications, Lattice performance management.", + "context": "Initial environment (seeded via a single shared session id across all mocks): GitHub repo with 0 issue(s) and 2 PR(s); a Google Sheet with seeded tabular data; Slack workspace with channels #general, #engineering, #random; Lattice with 12 goals and feedback history. GROUND TRUTH — the agent earns partial credit for each checkpoint: latency log lists PR #12 (+0.25); log has the PR title (+0.15); slack_new_msg (+0.1); nudge names PR #12 (+0.2); does NOT flag the PR opened today (+0.1); Lattice 1:1 feedback to James Kim (user_4) on review latency (+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.", + "domain": "qa", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/qa/qa_pr_mergeable_003.json b/raw/evaluation_examples/OSWorker/examples/qa/qa_pr_mergeable_003.json new file mode 100644 index 0000000000000000000000000000000000000000..c4232abe99256e067643435663fb589a3895b269 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/qa/qa_pr_mergeable_003.json @@ -0,0 +1,80 @@ +{ + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "id": "qa_pr_mergeable_003", + "difficulty": "hard", + "instruction": "Two PRs are up for review in hello-world and the team wants to know which one can go in. The rule: a PR is mergeable only if ALL its CI checks are green AND it has at least one approving review. Inspect both open PRs (#7 'Add retry logic to webhook dispatcher' and #8 'Refactor auth middleware'). Exactly one qualifies. For the PR that qualifies, move its linked Jira issue to 'In Review' — PR #7 is linked to KAN-3, PR #8 is linked to KAN-4. Then reply in the #engineering thread naming which PR number is ready to merge and which is blocked and why.", + "instruction_zh": "hello-world 中有两个 PR 待审查,团队想知道哪个可以合入。规则是:PR 只有在所有 CI 检查均为绿色,且至少有一个批准审查时,才可合并。请检查两个打开的 PR(#7 'Add retry logic to webhook dispatcher' 和 #8 'Refactor auth middleware')。恰好有一个符合条件。对于符合条件的 PR,请将其关联的 Jira 工单移动到 'In Review' —— PR #7 关联 KAN-3,PR #8 关联 KAN-4。然后在 #engineering 线程中回复,说明哪个 PR 编号已准备好合并,哪个被阻塞以及原因。", + "app_type": "github_mock", + "persona": "You are an office worker acting as a release engineer. Your tools for this task are: the GitHub repositories, the Jira project board, team communications.", + "context": "Initial environment (seeded via a single shared session id across all mocks): GitHub repo with 0 issue(s) and 2 PR(s); Jira Kanban project with issues KAN-1(Done), KAN-3(In Progress), KAN-4(In Progress); Slack workspace with channels #general, #engineering, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: KAN-3 (PR #7) moved to In Review (+0.45); slack_new_msg (+0.1); verdict names PR #7 as ready (+0.2); explains #8 is blocked (+0.25). 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.", + "domain": "qa", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_candidate_flow_007__long.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_candidate_flow_007__long.json new file mode 100644 index 0000000000000000000000000000000000000000..acbaba584316828f62bb24380c237f33a2e6a4ab --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_candidate_flow_007__long.json @@ -0,0 +1,77 @@ +{ + "id": "recruit_candidate_flow_007__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nAssume today is March 11, 2024. For every candidate currently in Greenhouse (first 5 candidates), run the full onsite‑scheduling pipeline: (1) move them to 'Onsite' in Greenhouse; (2) create a 1‑hour Google Calendar event titled 'Onsite – {Name}' in the earliest weekday 2–5 pm slot that does not clash with any existing event (some slots are already occupied by panel blocks, and some candidates share the same name); (3) send the 'Onsite Invitation' email via Gmail to each candidate with the confirmed time; (4) post '{Name} scheduled for onsite on {date/time}' in the Slack channel #recruiting. Never double‑book the calendar.", + "app_type": "greenhouse_mock,google_calendar_mock,gmail_mock,slack_mock", + "domain": "recruit", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_coordinator_006__long.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_coordinator_006__long.json new file mode 100644 index 0000000000000000000000000000000000000000..5a68f3fb0580c07daa5620002ec7d290dc6ffefc --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_coordinator_006__long.json @@ -0,0 +1,77 @@ +{ + "id": "recruit_coordinator_006__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (Greenhouse, Gmail, Google Sheets, and Slack). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou are the recruiting coordinator processing the outstanding offer approvals for the 'Senior Backend Engineer' job in Greenhouse. The Google Sheet 'Offer Decisions' (tab 'Offers') lists each candidate with their Recommended Salary, the role's Band Max, and a Decision. For every candidate, route them by these rules:\n- HIRE if the Decision is 'Approved' AND the Recommended Salary is at or below the Band Max: move the candidate's application to the 'Hired' stage in Greenhouse, send them an email via Gmail with Subject 'Offer confirmed - ', and add a note on the candidate recording the decision (mention it was hired / the offer was approved) and pin that note.\n- REJECT if the Decision is 'Declined', OR the Recommended Salary is above the Band Max (over band): reject the candidate's application in Greenhouse with the rejection reason 'Compensation expectations', send an email with Subject 'Update on your offer - ', and add a note recording the rejection (mention 'Compensation expectations') and pin that note.\n- If the Decision is 'Pending', leave the candidate unchanged.\n\nSkip any candidate who is already in the 'Hired' stage, and do not touch candidates who are not applicants for the 'Senior Backend Engineer' job (a look-alike from another job may appear in an offer stage -- leave it alone).\n\nRecord the approved offers: in the 'Offer Decisions' workbook, create a new tab named 'Approved Offers' with the columns Name, Email, Salary, and add one row for each candidate you hired (their name, their email, and their Recommended Salary from the Offers tab).\n\nWhen you have processed all the offer approvals, post a one-line summary to the Slack #recruiting channel stating how many offers you confirmed and how many you rejected, and pin that message to the channel.\n\nDo not email, move, reject, or note candidates you leave or skip.", + "app_type": "greenhouse_mock,gmail_mock,google_sheets_mock,slack_mock", + "domain": "recruit", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_followup_001.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_followup_001.json new file mode 100644 index 0000000000000000000000000000000000000000..d5f571b4250cb3ae92d7eff66d1d53bc30d42f27 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_followup_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "Send a same-day follow-up email to candidate Diego Ramos (diego.ramos@gmail.com) from Gmail thanking him for today's technical interview — the email must clearly thank him and reference the interview. Then post a quick reminder in Slack #hiring that mentions both interviewers by name, Sara and Ben, asking them to submit their scorecards in Greenhouse by end of day (the reminder should include the word 'scorecard' and reference Greenhouse or end of day).", + "id": "recruit_followup_001", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T19:22:18.619589", + "adversarial_rounds": "2", + "domain": "recruit", + "_source": "minicua", + "instruction_zh": "通过 Gmail 向候选人 Diego Ramos(diego.ramos@gmail.com)发送一封当日跟进邮件,感谢他参加今天的技术面试——邮件必须明确致谢并提及此次面试。随后在 Slack #hiring 中发布一条简短提醒,点名提到两位面试官 Sara 和 Ben,请他们在今天结束前将 scorecards 提交至 Greenhouse(提醒内容需包含单词 \"scorecard\",并提及 Greenhouse 或今天结束前)。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_offer_003.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_offer_003.json new file mode 100644 index 0000000000000000000000000000000000000000..3bd5cb9dcb5b960950cfc96fcb2504131b3fe098 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_offer_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "We're extending an offer to candidate Sofia Rossi for the Marketing Manager role. Move her to the 'Offer' stage in Greenhouse, create an offer in Greenhouse with a base salary of $120,000 and start date 2026-08-03, send her a personalized offer email from Outlook, and announce in Slack #hiring that an offer has gone out (without disclosing the salary number).", + "id": "recruit_offer_003", + "app_type": "libreoffice_calc", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-30T19:18:14.659630", + "adversarial_rounds": "1", + "domain": "recruit", + "_source": "minicua", + "instruction_zh": "我们拟向候选人Sofia Rossi发出营销经理职位的录用通知。请在Greenhouse中将她移至'Offer'阶段,在Greenhouse中创建一份录用通知,基本年薪为$120,000,入职日期为2026-08-03,通过Outlook向她发送一封个性化的录用通知邮件,并在Slack #hiring频道中宣布录用通知已发出(不透露薪资数字)。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_onsite_decision_005__long.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_onsite_decision_005__long.json new file mode 100644 index 0000000000000000000000000000000000000000..c6a4ee53d82f04aff0deadd5318f61831d3be264 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_onsite_decision_005__long.json @@ -0,0 +1,77 @@ +{ + "id": "recruit_onsite_decision_005__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (Greenhouse, Gmail, Google Calendar, and Slack). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nYou are the recruiter making onsite decisions for the 'Senior Backend Engineer' job in Greenhouse. For every active application currently in the Onsite stage, read the submitted interview scorecards and decide whether to advance, reject, or leave the candidate. The exact decision rule is NOT repeated here: read it in the Slack #hiring channel (see the pinned message) and apply it. Note that if an interviewer submitted more than one scorecard, only their most recent one counts, and pending (unsubmitted) scorecards are ignored.\n\nWhen you ADVANCE a candidate: move their application to the Offer stage, and book a Google Calendar debrief event titled 'Debrief - ' scheduled on 2026-05-03 with the hiring manager (Omar Farouk, omar.farouk@company.com) as a guest -- a debrief is an internal review, so invite the hiring manager, not the candidate. When you REJECT a candidate: set the application status to rejected and send the candidate a rejection email -- addressed to the candidate's own email, with the subject exactly 'Update on your application - '. Leave everyone else as-is.\n\nFinally, post a one-line summary of your decisions to Slack #hiring.", + "app_type": "greenhouse_mock,gmail_mock,google_calendar_mock,slack_mock", + "domain": "recruit", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_onsite_stage_008__long.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_onsite_stage_008__long.json new file mode 100644 index 0000000000000000000000000000000000000000..5015e2cc85586e4fcd2fca5e0dbb0ddf48b3daf0 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_onsite_stage_008__long.json @@ -0,0 +1,77 @@ +{ + "id": "recruit_onsite_stage_008__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nAssume today is Monday, June 8, 2026. For every active application in an 'Onsite' stage that already has all of its onsite interviews marked 'completed', schedule a 30-minute debrief on the Google Calendar titled 'Debrief - '. The debrief must (a) be on a weekday within June 8-11, 2026, between 13:00 and 17:00 local, (b) not overlap any existing event on the calendar, and (c) invite as guests EXACTLY the interviewers who submitted scorecards for that application (resolve interviewer ids to their emails) -- do not invite yourself (the organizer), the candidate, or anyone else. Schedule at most ONE debrief per day: process candidates in candidate order (alphabetical by candidate name) and place each candidate on the earliest weekday in the window that does not yet hold a debrief; within that day, pick the EARLIEST conflict-free 30-min slot (aligned to :00 or :30). Skip applications that still have a 'scheduled' (not completed) onsite interview, and skip non-onsite applications.\n\nFinally, in Slack, post one message per scheduled candidate in the '#interviews' channel announcing the debrief: name the candidate and @mention EXACTLY that candidate's interviewers (the same people you invited as calendar guests) -- mention no one else.", + "app_type": "greenhouse_mock,google_calendar_mock,slack_mock", + "domain": "recruit", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_resume_screen_004__long.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_resume_screen_004__long.json new file mode 100644 index 0000000000000000000000000000000000000000..565c9648721c0d23b244620d34abb79acab475ec --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_resume_screen_004__long.json @@ -0,0 +1,77 @@ +{ + "id": "recruit_resume_screen_004__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (Greenhouse, Gmail, Google Calendar, and Slack). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nToday's date is Tuesday, June 23, 2026.\n\nYou are screening candidates in Greenhouse for the 'Senior Frontend Engineer' job. For each active application currently in the 'Onsite' stage, read its submitted scorecards and decide: ADVANCE the candidate to 'Offer' if the scorecards have NO 'no'/'strong_no' recommendations AND at least two 'strong_yes'/'yes'; REJECT (move application status to rejected with reason 'Not enough support') if there is any 'strong_no', or two or more 'no'; otherwise LEAVE in 'Onsite' (mixed/insufficient signal). The stage-move and reject controls are on the candidate's own detail page.\n\nAfter advancing a candidate, send them an email via Gmail with Subject 'Next steps - ' AND create a Google Calendar event titled 'Offer discussion - ' three days from today (i.e. on Friday, June 26, 2026), adding the candidate's email address as a guest (type it into the guest field; they are not in the autocomplete). After rejecting, send Subject 'Update on your application - '.\n\nFor every candidate you advance or reject, also add a note on that candidate recording the decision (for an advance, mention it was advanced to Offer; for a reject, mention 'Not enough support') and pin that note (use the pin control on the candidate's Notes tab).\n\nWhen you have processed all the onsite decisions, post a one-line summary to the Slack #recruiting channel stating how many onsite decisions you processed, and pin that message to the channel (the pin option is in the message's hover '...' more-actions menu).\n\nDo not email, move, schedule, or note candidates you leave in Onsite. Ignore applications not in the Onsite stage and pending (unsubmitted) scorecards.", + "app_type": "greenhouse_mock,gmail_mock,google_calendar_mock,slack_mock", + "domain": "recruit", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/recruit/recruit_screen_002.json b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_screen_002.json new file mode 100644 index 0000000000000000000000000000000000000000..efcfb49f7c1026796bca00849104ba496b336fcb --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/recruit/recruit_screen_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "Candidate Nina Patel (nina.patel@gmail.com) passed her recruiter screen for the Software Engineer role. In Greenhouse, move her application to the 'Hiring Manager Interview' stage and add a scorecard note stating she has 6 years of relevant experience and strong communication. Then send her an email from Gmail letting her know the next step is a hiring-manager interview, and post a message in Slack #hiring that @mentions the hiring manager Greg asking him to review Nina's profile.", + "id": "recruit_screen_002", + "app_type": "recruiter_cross_app", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T19:06:56.005566", + "adversarial_rounds": "2", + "domain": "recruit", + "_source": "minicua", + "instruction_zh": "候选人 Nina Patel(nina.patel@gmail.com)通过了 Software Engineer 职位的招聘官筛选。在 Greenhouse 中,将她的申请移至 'Hiring Manager Interview' 阶段,并添加一条评分卡备注,说明她具备 6 年相关经验且沟通能力强。然后通过 Gmail 给她发送一封邮件,告知她下一步是招聘经理面试,并在 Slack #hiring 频道发布一条消息,@提及招聘经理 Greg,请他查看 Nina 的档案。" +} diff --git a/raw/evaluation_examples/OSWorker/examples/sdr/sdr_cold_outreach_001.json b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_cold_outreach_001.json new file mode 100644 index 0000000000000000000000000000000000000000..cc3a77a737b2a5e577e46e754c70ab3fc08b1863 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_cold_outreach_001.json @@ -0,0 +1,79 @@ +{ + "instruction": "Marcus Bell over at Cedar Grove Health is a brand-new lead in our CRM and I want to get the first touch out today. Use the computer's current local date as the reference: \"this Friday\" means the upcoming Friday in local time, or today if today is Friday. Send him a short cold outreach email — keep it to about three sentences that speak to his role running operations — then update his contact record to reflect that we've now attempted to reach him, log a quick note recording the outreach, and set yourself a follow-up reminder for this Friday in case he doesn't reply.", + "instruction_zh": "Cedar Grove Health 的 Marcus Bell 是我们 CRM 中的全新线索,我想今天就完成首次触达。以电脑当前本地日期为基准:“本周五”表示本地时间即将到来的周五;如果今天就是周五,则表示今天。给他发一封简短的冷邮件——控制在三句话左右,内容要针对他负责运营的角色——然后更新他的联系人记录,表明我们已尝试联系过他;快速记一条备注,记录这次外联;并给自己设置一个本周五的跟进提醒,以防他没有回复。", + "id": "sdr_cold_outreach_001", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:31:20.961871", + "adversarial_rounds": "1", + "domain": "sdr", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/sdr/sdr_inbound_lead_006__long.json b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_inbound_lead_006__long.json new file mode 100644 index 0000000000000000000000000000000000000000..b6a772d32bd4bd925d1cd6f63f0597356d664e3b --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_inbound_lead_006__long.json @@ -0,0 +1,77 @@ +{ + "id": "sdr_inbound_lead_006__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in (Salesforce, Gmail, Google Calendar, and Slack). Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nAssume today is Monday, July 6, 2026. Work the overnight inbound emails in Gmail and qualify the sales pipeline. A GENUINE inbound is a prospect asking about the product. For each genuine inbound email, classify its tier by intent keyword in the body (precedence Hot > Warm > Cold): if the body mentions 'ready to buy', 'budget approved', or 'sign this quarter' -> Hot; else if it mentions 'evaluating', 'comparing', or 'demo' -> Warm; otherwise -> Cold.\n\nApply the matching tier label ('Hot', 'Warm', or 'Cold') to each genuine inbound email in Gmail.\n\nThen bring Salesforce into line. Find the Opportunity that matches the email's company and set its Stage by tier: Hot -> 'Value Proposition'; Warm -> 'Qualification'; Cold -> 'Prospecting'. If a genuine inbound has no matching Salesforce Opportunity, still label the email but make no Salesforce change.\n\nFor each Hot lead only, also (a) log a follow-up Task on that Opportunity with Subject 'Discovery follow-up: ', and (b) book a Google Calendar discovery call titled 'Discovery call - ' on Wednesday, July 8, 2026 (today + 2 days), and add the prospect (the email sender's address) as a guest on that event.\n\nDo NOT label or take Salesforce/Calendar action on newsletters, auto-replies, or email threads whose later reply says the matter is already closed -- archive all of those instead.\n\nFinally, post a one-line summary to the Slack #sales channel stating how many inbound leads you qualified, and pin that message to the channel.", + "app_type": "salesforce_mock,gmail_mock,google_calendar_mock,slack_mock", + "domain": "sdr", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/sdr/sdr_lead_import_004__long.json b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_lead_import_004__long.json new file mode 100644 index 0000000000000000000000000000000000000000..c1407a95d22ad118ca8813fb680c0e362e66f02c --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_lead_import_004__long.json @@ -0,0 +1,77 @@ +{ + "id": "sdr_lead_import_004__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nThe 'Inbound' Google Sheet contains 10 lead rows (rows 2-11). For every row, create a Salesforce Lead with this exact field mapping: First Name -> First Name, Last Name -> Last Name, Company -> Company, Phone -> Phone, Email -> Email, Notes -> Description; set Lead Status to 'New'. After creating each lead, write 'Entered' into the Status column (column G) of that same row. If a row's Status column already says 'Entered', SKIP that row -- do not create a duplicate Lead in Salesforce. When finished, post in the Slack channel #sales-ops: 'Entered {n} new leads', where {n} is the total number of rows you needed to process (i.e. rows 2-11 whose Status column was NOT already 'Entered' before you started); use this exact count even if you did not finish them all.", + "app_type": "salesforce_mock,google_sheets_mock,slack_mock", + "domain": "sdr", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/sdr/sdr_lead_routing_005__long.json b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_lead_routing_005__long.json new file mode 100644 index 0000000000000000000000000000000000000000..6e38ae5cbdec78c7cbce3c65db693ab60b56c2d5 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_lead_routing_005__long.json @@ -0,0 +1,77 @@ +{ + "id": "sdr_lead_routing_005__long", + "difficulty": "hard", + "instruction": "The apps for this task are already open in separate browser tabs and logged in. Just switch between these tabs to do the task -- no sign-in or URL needed.\n\nRoute every Salesforce lead with status 'New'. Use Annual Revenue to assign a tier and act: >=$5,000,000 -> Enterprise, set Status 'Working' and Owner 'Sarah Chen'; $1,000,000-4,999,999 -> Mid-Market, Owner 'Tom Ray'; <$1,000,000 -> SMB, Owner 'Tom Ray'; if Annual Revenue is blank -> set Status 'Unqualified'. For each lead, add a row to the 'Routing Log' Google Sheet and post one line in the Slack channel #sales-routing in the format '{Company} -> {Tier} -> {Owner or Unqualified}', where {Company} is the lead's Company name, {Tier} is one of 'Enterprise' / 'Mid-Market' / 'SMB' / 'Unqualified' chosen by the rules above, and the third field is the assigned owner name -- or the literal word 'Unqualified' when Annual Revenue is blank. Examples: 'NoRev -> Enterprise -> John Smith', 'Acme Corp -> Unqualified -> Unqualified'.", + "app_type": "salesforce_mock,google_sheets_mock,slack_mock", + "domain": "sdr", + "_source": "lc_task_py", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + } +} diff --git a/raw/evaluation_examples/OSWorker/examples/sdr/sdr_outreach_tracker_002.json b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_outreach_tracker_002.json new file mode 100644 index 0000000000000000000000000000000000000000..31dd8b167a3ab1c44b00f5bd7887eab1b4b091d2 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_outreach_tracker_002.json @@ -0,0 +1,79 @@ +{ + "instruction": "It's outreach day. Open my SDR Outreach Tracker and work through the prospects that are still Not Contacted, assigned to Alex Morgan, and have an email address. For each target, send a brief intro email from Outlook with the exact subject \"Intro from Northwind Cloud\". The emails must be sent, not left as drafts. Then mark those same tracker rows as Contacted, set Last Contacted to 2026-06-24, and make each Status cell green. Keep HubSpot in sync by changing those same prospects to leadStatus attempted.", + "instruction_zh": "今天是外联日。打开我的 SDR Outreach Tracker,处理仍为 Not Contacted、分配给 Alex Morgan 且有邮箱地址的潜在客户。请分别从 Outlook 给每位目标发送一封简短的自我介绍邮件,邮件主题必须精确为 \"Intro from Northwind Cloud\",并且邮件必须已发送,不能停留为草稿。然后在 tracker 中把对应行标记为 Contacted,将 Last Contacted 填为 2026-06-24,并把各自的 Status 单元格设为绿色。最后在 HubSpot 中同步把这些潜在客户的 leadStatus 改为 attempted。", + "id": "sdr_outreach_tracker_002", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:52:20.504700", + "adversarial_rounds": "1", + "domain": "sdr", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/examples/sdr/sdr_source_lead_003.json b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_source_lead_003.json new file mode 100644 index 0000000000000000000000000000000000000000..0872a2f8770f20fe681e1f701268ae4c8608caa8 --- /dev/null +++ b/raw/evaluation_examples/OSWorker/examples/sdr/sdr_source_lead_003.json @@ -0,0 +1,79 @@ +{ + "instruction": "I'm prospecting on LinkedIn. Find Priya Nair, the VP of Engineering at NorthBeam Logistics, and send her a connection request with a brief personalized note that mentions Priya and either NorthBeam or her engineering/logistics context. Then add her to Salesforce as a new lead — capture her name, company, and title, mark the lead source as LinkedIn, give it a Warm rating, keep the status New, and assign it to yourself. Finally, using the computer's current local date as the anchor, add an open Salesforce task assigned to yourself and related to that new lead to send Priya an intro email two days from now.", + "instruction_zh": "我正在 LinkedIn 上寻找潜在客户。找到 NorthBeam Logistics 的工程副总裁 Priya Nair,向她发送连接请求并附上简短的个性化备注,备注需提到 Priya,并结合 NorthBeam 或她的工程/物流相关背景。然后将她作为新线索添加到 Salesforce——录入她的姓名、公司和职位,将线索来源标记为 LinkedIn,评级设为 Warm,状态保持为 New,并分配给你自己。最后以电脑当前本地日期为基准,在 Salesforce 中添加一个未完成任务,任务分配给你自己、关联到这条新线索,并提醒你两天后给 Priya 发送介绍邮件。", + "id": "sdr_source_lead_003", + "app_type": "mock_websites", + "config": [ + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "_cua_gym_vm_bridge.sh", + "path": "/tmp/_cua_gym_vm_bridge.sh" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "bash /tmp/_cua_gym_vm_bridge.sh '{CLIENT_PASSWORD}' 9000 9097 28.7.184.198", + "shell": true + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "initial_setup.py", + "path": "/home/user/initial_setup.py" + } + ] + } + }, + { + "type": "execute", + "parameters": { + "command": "python3 /home/user/initial_setup.py" + } + }, + { + "type": "upload_cache_file", + "parameters": { + "files": [ + { + "local_path": "reward.py", + "path": "/home/user/_cua_reward.py" + } + ] + } + } + ], + "evaluator": { + "func": "cua_gym_reward", + "result": { + "type": "cache_file", + "path": "_cua_reward_stdout.txt" + }, + "postconfig": [ + { + "type": "execute", + "parameters": { + "command": [ + "python3", + "/home/user/_cua_reward.py" + ], + "stdout": "_cua_reward_stdout.txt", + "stderr": "_cua_reward_stderr.txt", + "shell": false + } + } + ] + }, + "generated_at": "2026-06-24T21:24:04.405369", + "adversarial_rounds": "1", + "domain": "sdr", + "_source": "cua_gym" +} diff --git a/raw/evaluation_examples/OSWorker/osworker_benchmark_full.json b/raw/evaluation_examples/OSWorker/osworker_benchmark_full.json new file mode 100644 index 0000000000000000000000000000000000000000..2457f4e903ec8614a1924b90563e41e3f1a2360d --- /dev/null +++ b/raw/evaluation_examples/OSWorker/osworker_benchmark_full.json @@ -0,0 +1,136 @@ +{ + "ae": [ + "ae_contract_signature_001", + "ae_deal_handoff_002__long", + "ae_pipeline_hygiene_003", + "ae_pipeline_review_004__long" + ], + "am": [ + "am_renewal_contract_001", + "am_renewal_hubspot_004__long", + "am_renewal_outreach_002", + "am_renewal_tracker_003" + ], + "ar": [ + "ar_aging_001", + "ar_approval_002", + "ar_billing_exception_012__long", + "ar_churn_refund_009__long", + "ar_closeout_006", + "ar_deal_to_invoice_007__long", + "ar_invoice_003", + "ar_payment_004", + "ar_payment_alert_010__long", + "ar_remittance_008__long", + "ar_signature_005", + "ar_stripe_reconcile_011__long" + ], + "calc": [ + "calc_boomerang_sales_004__long", + "calc_employee_roles_003__long", + "calc_income_statement_001__long", + "calc_sales_rep_002__long", + "calc_student_grades_005__long" + ], + "csm": [ + "csm_escalation_001", + "csm_health_risk_002", + "csm_onboarding_checklist_004", + "csm_qbr_renewal_003", + "csm_training_rate_005" + ], + "csops": [ + "csops_email_to_crm_case_001", + "csops_inbox_triage_006__long", + "csops_incident_command_004__long", + "csops_p1_incident_002", + "csops_sla_queue_triage_003", + "csops_ticket_queue_005__long" + ], + "fin": [ + "fin_expense_claim_001__long__cond", + "fin_expense_claim_002__long__cond" + ], + "hr": [ + "hr_it_provisioning_008__long", + "hr_midyear_review_007__long", + "hr_onboarding_003", + "hr_onboarding_checklist_004", + "hr_one_on_one_009", + "hr_payroll_approval_006__long", + "hr_policy_ack_001", + "hr_policy_ack_002", + "hr_policy_package_005" + ], + "img": [ + "img_brightness_001__long", + "img_contrast_002__long" + ], + "itops": [ + "itops_access_approval_001", + "itops_access_log_003", + "itops_access_ticket_004", + "itops_field_change_002" + ], + "mktg": [ + "mktg_campaign_001", + "mktg_campaign_create_004", + "mktg_field_reconcile_006", + "mktg_funnel_report_007", + "mktg_inbound_qualify_009__long", + "mktg_leadhandoff_002", + "mktg_perf_report_005", + "mktg_report_003", + "mktg_social_approve_010", + "mktg_webinar_guide_011", + "mktg_webinar_mql_008" + ], + "ops": [ + "ops_board_agenda_008", + "ops_catalog_update_003__long", + "ops_grade_report_011__long", + "ops_inbox_meeting_007", + "ops_inventory_reorder_001__long", + "ops_license_audit_010__long", + "ops_meeting_schedule_004__long", + "ops_meeting_setup_009", + "ops_pdf_mail_012__long__cond", + "ops_region_consolidate_002__long", + "ops_risk_log_006", + "ops_shift_cover_005" + ], + "pm": [ + "pm_board_sync_003", + "pm_sprint_closeout_002__long", + "pm_sprint_planning_001__long" + ], + "qa": [ + "qa_bug_escalate_004", + "qa_defect_triage_001__long", + "qa_pr_latency_002", + "qa_pr_mergeable_003" + ], + "recruit": [ + "recruit_candidate_flow_007__long", + "recruit_coordinator_006__long", + "recruit_followup_001", + "recruit_offer_003", + "recruit_onsite_decision_005__long", + "recruit_onsite_stage_008__long", + "recruit_resume_screen_004__long", + "recruit_screen_002" + ], + "sdr": [ + "sdr_cold_outreach_001", + "sdr_inbound_lead_006__long", + "sdr_lead_import_004__long", + "sdr_lead_routing_005__long", + "sdr_outreach_tracker_002", + "sdr_source_lead_003" + ], + "sre": [ + "sre_change_review_002__long", + "sre_error_triage_001__long", + "sre_runbook_003" + ] +} diff --git a/recruit_candidate_flow_007__long/_cua_gym_vm_bridge.sh b/recruit_candidate_flow_007__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_candidate_flow_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/recruit_candidate_flow_007__long/initial_setup.py b/recruit_candidate_flow_007__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e7458509f7d2c58afd3d67b727d105c78164302d --- /dev/null +++ b/recruit_candidate_flow_007__long/initial_setup.py @@ -0,0 +1,643 @@ +""" +Initial Setup: P1 — Recruiting onsite scheduling loop (refine v2) +Source: cache_mock_apps_debug/README_ccf892d6.md (refine doc) +Variant: eval +Mocks: greenhouse_mock,google_calendar_mock,gmail_mock,slack_mock + +Key change vs v1: +- greenhouse state now follows the official SCHEMA (candidateId/currentStageId, + jobStages with stageType, real job/candidate records). The pipeline view + will actually render the 5 onsite-bound candidates. +- gmail no longer injects unsupported `templates` field; the onsite-invitation + template is delivered to the agent as a draft email instead. +- google_calendar uses `currentDate` (real schema) instead of `today`. The + instruction itself anchors "today = 2024-03-11" via natural language. +""" +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}') + + +# ------------------------------------------------------------------ +# Greenhouse: 5 candidates parked at "Recruiter Phone Screen" of job-3 (Backend +# Engineer). All other arrays are explicitly cleared so the pipeline shows only +# our 5 candidates (deepMerge would otherwise keep 25 default applications and +# pollute the view). +# ------------------------------------------------------------------ +GH_USER_1 = { + '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', +} +_GH_USERS = [ + GH_USER_1, + {'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-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_JOB_3 = { + 'id': 'job-3', 'title': 'Backend Engineer', 'status': 'open', + 'departmentId': 'dept-1', 'officeId': 'office-3', + 'hiringManagerId': 'user-3', 'recruiterId': 'user-1', 'coordinatorId': 'user-7', + 'openings': 3, 'openDate': '2024-01-15', 'closeDate': None, + 'description': 'Backend engineer working on Python services and infra.', + 'requirements': ['5+ years backend', 'Python or Go', 'Distributed systems'], + 'stages': [f'stage-job-3-{i}' for i in range(1, 9)], + 'candidateCount': 5, + 'createdAt': '2024-01-15T09:00:00Z', 'updatedAt': '2024-03-01T09:00:00Z', +} + +_GH_JOB_STAGES = [ + {'id': 'stage-job-3-1', 'jobId': 'job-3', 'name': 'Application Review', + 'orderIndex': 0, 'stageType': 'application_review'}, + {'id': 'stage-job-3-2', 'jobId': 'job-3', 'name': 'Recruiter Phone Screen', + 'orderIndex': 1, 'stageType': 'phone_screen'}, + {'id': 'stage-job-3-3', 'jobId': 'job-3', 'name': 'Hiring Manager Screen', + 'orderIndex': 2, 'stageType': 'phone_screen'}, + {'id': 'stage-job-3-4', 'jobId': 'job-3', 'name': 'Technical Interview', + 'orderIndex': 3, 'stageType': 'interview'}, + {'id': 'stage-job-3-5', 'jobId': 'job-3', 'name': 'Take Home', + 'orderIndex': 4, 'stageType': 'take_home'}, + {'id': 'stage-job-3-6', 'jobId': 'job-3', 'name': 'Onsite Interview', + 'orderIndex': 5, 'stageType': 'onsite'}, + {'id': 'stage-job-3-7', 'jobId': 'job-3', 'name': 'Offer', + 'orderIndex': 6, 'stageType': 'offer'}, + {'id': 'stage-job-3-8', 'jobId': 'job-3', 'name': 'Hired', + 'orderIndex': 7, 'stageType': 'hired'}, +] + +_TASK_CANDIDATES = [ + ('cand-t1', 'Jordan', 'Lee', 'jordan.lee@example.com'), + ('cand-t2', 'Riley', 'Park', 'riley.park@example.com'), + ('cand-t3', 'Sam', 'Diaz', 'sam.diaz@example.com'), + ('cand-t4', 'Tess', 'Wong', 'tess.wong@example.com'), + ('cand-t5', 'Uma', 'Patel','uma.patel@example.com'), +] + +_GH_CANDIDATES = [ + {'id': cid, 'firstName': fn, 'lastName': ln, 'name': f'{fn} {ln}', + 'email': em, 'phone': '', 'location': '', + 'currentCompany': 'Acme', 'currentTitle': 'Engineer', + 'resumeUrl': None, 'linkedinUrl': None, + 'source': 'applied', 'referrerId': None, 'tags': [], + 'createdAt': '2024-02-15T10:00:00Z', 'updatedAt': '2024-03-05T10:00:00Z'} + for (cid, fn, ln, em) in _TASK_CANDIDATES +] + +_GH_APPLICATIONS = [ + {'id': f'app-t{idx}', 'candidateId': cid, 'jobId': 'job-3', + 'currentStageId': 'stage-job-3-2', 'status': 'active', + 'appliedAt': '2024-02-15T10:00:00Z', 'rejectedAt': None, + 'rejectionReason': None, 'hiredAt': None, + 'lastActivityAt': '2024-03-05T10:00:00Z', 'source': 'applied', + 'creditedTo': None, 'recruiterId': 'user-1', 'coordinatorId': 'user-7', + 'actionRequired': 'needs_scheduling', 'daysInCurrentStage': 6} + for idx, (cid, *_rest) in enumerate(_TASK_CANDIDATES, start=1) +] + +GREENHOUSE_STATE = { + 'currentUser': GH_USER_1, + 'users': _GH_USERS, + 'departments': [ + {'id': 'dept-1', 'name': 'Engineering', 'parentId': None}, + {'id': 'dept-6', 'name': 'People Operations', 'parentId': None}, + ], + 'offices': [ + {'id': 'office-1', 'name': 'San Francisco HQ', 'location': 'San Francisco, CA'}, + {'id': 'office-3', 'name': 'Remote', 'location': 'Remote'}, + ], + 'sources': [{'id': 'src-1', 'name': 'Applied'}], + 'rejectionReasons': [{'id': 'rr-1', 'name': 'Lacking technical skills'}], + 'jobs': [_GH_JOB_3], + 'jobStages': _GH_JOB_STAGES, + 'candidates': _GH_CANDIDATES, + 'applications': _GH_APPLICATIONS, + # Empty arrays — explicitly clear default seed data so the pipeline view + # only shows the 5 task candidates. + 'scorecards': [], + 'interviews': [], + 'offers': [], + 'notes': [], + 'activityFeed': [], + 'notifications': [], + 'ui': {'searchQuery': '', 'activeJobId': 'job-3', 'activeCandidateId': None, + 'modals': {}}, +} + + +# ------------------------------------------------------------------ +# Google Calendar: panel busy slots that block 2 of the 14:00–17:00 weekday +# slots starting Tue 2024-03-12. The agent has 5 candidates × 1h slots and +# at most 3 slots per day in the 14:00-17:00 window, so a non-clashing +# schedule must span at least 2 weekdays. +# +# Note: the schema does not expose a "today" field (currentDate only re-centers +# the calendar view). The instruction natural-language anchors today=2024-03-11. +# ------------------------------------------------------------------ +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': '#039BE5', + 'visible': True, 'userId': 'u1', 'isDefault': True}, + {'id': 'c2', 'name': 'Work', 'color': '#33B679', + 'visible': True, 'userId': 'u1', 'isDefault': False}, + ], + 'otherCalendars': [], + 'events': [ + {'id': 'evt_panel_1', 'calendarId': 'c2', 'title': 'Panel busy', + 'start': '2024-03-12T14:00:00.000Z', 'end': '2024-03-12T15:00:00.000Z', + 'allDay': False, 'location': '', 'description': '', + 'guests': [], 'color': '#33B679', 'recurring': 'none', + 'reminders': [], 'meetLink': '', 'status': 'confirmed'}, + {'id': 'evt_panel_2', 'calendarId': 'c2', 'title': 'Panel busy', + 'start': '2024-03-13T15:00:00.000Z', 'end': '2024-03-13T16:00:00.000Z', + 'allDay': False, 'location': '', 'description': '', + 'guests': [], 'color': '#33B679', 'recurring': 'none', + 'reminders': [], 'meetLink': '', 'status': 'confirmed'}, + ], + 'view': 'week', + 'currentDate': '2024-03-11T00:00:00.000Z', + 'sidebarOpen': True, + 'settings': { + 'weekStart': 0, 'defaultDuration': 60, 'defaultView': 'week', + 'defaultReminder': {'type': 'popup', 'minutes': 10}, + 'timeFormat': '12h', 'showWeekNumbers': False, + 'showDeclinedEvents': False, + }, +} + + +# ------------------------------------------------------------------ +# Gmail: a single draft email serves as the "Onsite Invitation" template. +# (The schema has no `templates` field; drafts live in `emails` with +# folder='drafts'.) +# ------------------------------------------------------------------ +GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Jules Park', + 'email': 'jules.park@company.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + 'emails': [ + { + 'id': 'email_template_onsite', + 'threadId': 'thread_template_onsite', + 'from': {'name': 'Jules Park', 'email': 'jules.park@company.com'}, + 'to': [], + 'cc': [], 'bcc': [], + 'subject': 'Onsite Invitation', + 'body': ( + 'Hi {Name},\n\n' + 'We would like to invite you to an onsite interview. ' + 'Your slot is {Day} {Time}–{Time+1h}. Please confirm.\n\n' + 'Best,\nJules' + ), + 'snippet': 'Onsite invitation template', + 'timestamp': '2024-03-10T09:00:00Z', + 'read': True, 'starred': False, 'important': False, + 'labels': [], 'category': 'primary', 'folder': 'drafts', + 'attachments': [], + }, + ], + 'labels': [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + ], + 'drafts': [], + 'settings': { + 'density': 'default', 'undoSend': 10, + 'signature': '--\nJules Park\njules.park@company.com', + 'replyBehavior': 'Reply', 'language': 'English (US)', + }, +} + + +# ------------------------------------------------------------------ +# Slack: agent posts onsite confirmations to #recruiting. Other channels +# (#general / #random / #eng-hiring) plus prior chatter are watermark +# decoration so the workspace doesn't look freshly-empty. reward.py only +# reads #recruiting so these extras don't affect scoring. +# ------------------------------------------------------------------ +SLACK_STATE = { + 'currentUser': { + 'userId': 'user_1', 'fullName': 'Jules Park', 'displayName': 'Jules', + 'email': 'jules.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Senior Recruiter', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York', + }, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'users': [ + {'userId': 'user_1', 'fullName': 'Jules Park', 'displayName': 'Jules', + 'email': 'jules.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Senior Recruiter', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Sarah Chen', 'displayName': 'Sarah', + 'email': 'sarah.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Recruiter', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + {'userId': 'user_3', 'fullName': 'David Kim', 'displayName': 'David', + 'email': 'david.kim@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'VP of Engineering', 'status': 'away', + 'statusMessage': 'In interviews', 'statusEmoji': ':calendar:', + 'timeZone': 'America/New_York'}, + {'userId': 'user_4', 'fullName': 'James Wright', 'displayName': 'James', + 'email': 'james.wright@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': 'Recruiting Coordinator', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + ], + 'channels': [ + {'channelId': 'general', 'name': 'general', + 'description': 'Company-wide announcements and work-based matters', + 'topic': 'Welcome to Acme Corp!', 'isPrivate': False, + 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_3', 'createdAt': '2024-01-01T08:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'random', 'name': 'random', + 'description': 'Non-work banter and watercooler chat', + 'topic': 'Coffee, memes, weekend plans', 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_2', 'createdAt': '2024-01-01T08:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'eng-hiring', 'name': 'eng-hiring', + 'description': 'Engineering hiring coordination', + 'topic': 'Pipeline syncs, debriefs, calibration', + 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_3', 'user_4'], + 'createdBy': 'user_3', 'createdAt': '2024-01-15T08:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'recruiting', 'name': 'recruiting', + 'description': 'Recruiting team channel — onsite confirmations, candidate updates', + 'topic': 'Post one line per onsite scheduled', + 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_4'], + 'createdBy': 'user_1', 'createdAt': '2024-01-01T08:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_3', + 'content': 'Heads up — interview panel for the Backend Engineer role is finalized. Marcus and Priya are primary; ping me for swaps.', + 'timestamp': '2024-03-08T15:30:00Z', 'reactions': [], + 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_2', 'senderId': 'user_4', + 'content': 'Reminder: office is closed next Friday (3/15) for the company offsite. Please reflect on your calendars.', + 'timestamp': '2024-03-08T17:02:00Z', + 'reactions': [{'emoji': '\u2705', 'users': ['user_1', 'user_2']}], + 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_3', 'senderId': 'user_2', + 'content': 'Q1 hiring plan attached on the wiki — TL;DR: 5 backend, 2 frontend, 1 SRE. Onsites should ramp this week.', + 'timestamp': '2024-03-11T13:10:00Z', + 'reactions': [{'emoji': '\ud83d\udcc8', 'users': ['user_1', 'user_3', 'user_4']}], + 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'random': [ + {'messageId': 'm_r_1', 'senderId': 'user_2', + 'content': 'Has anyone else noticed the espresso machine making sad noises this morning? :coffee:', + 'timestamp': '2024-03-11T13:45:00Z', + 'reactions': [{'emoji': '\ud83d\ude22', 'users': ['user_1', 'user_4']}], + 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_2', 'senderId': 'user_4', + 'content': 'Filed a ticket. ETA: whenever facilities feels like it.', + 'timestamp': '2024-03-11T13:48:00Z', 'reactions': [], + 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_3', 'senderId': 'user_1', + 'content': 'My cat has decided my keyboard is her new bed. Send help.', + 'timestamp': '2024-03-11T14:05:00Z', + 'reactions': [{'emoji': '\ud83d\ude3a', 'users': ['user_2', 'user_3', 'user_4']}], + 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'eng-hiring': [ + {'messageId': 'm_e_1', 'senderId': 'user_3', + 'content': 'Backend Engineer pipeline looks healthy — 5 candidates cleared phone screens, ready for onsite scheduling.', + 'timestamp': '2024-03-11T13:00:00Z', + 'reactions': [{'emoji': '\ud83d\udc4d', 'users': ['user_1']}], + 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_e_2', 'senderId': 'user_1', + 'content': 'On it — will set up onsites this week. Targeting 1h slots between 14:00–17:00 to keep panel availability sane.', + 'timestamp': '2024-03-11T13:04:00Z', 'reactions': [], + 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_e_3', 'senderId': 'user_4', + 'content': 'Note: panel has two pre-booked busy blocks (Tue 14:00 and Wed 15:00). Plan around those.', + 'timestamp': '2024-03-11T13:07:00Z', 'reactions': [], + 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'recruiting': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', + 'displayDensity': 'comfortable', 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + '_task_adapter': {'task_id': 'lc_p1', 'variant': 'eval'}, +} + + +APP_STATES = [ + ('http://28.7.184.198:8146', GREENHOUSE_STATE), # greenhouse_mock + ('http://28.7.184.198:8141', CALENDAR_STATE), # google_calendar_mock + ('http://28.7.184.198:8138', GMAIL_STATE), # gmail_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/recruit_candidate_flow_007__long/reward.py b/recruit_candidate_flow_007__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..df7170feb88221334343677da592e1ce6459bc5d --- /dev/null +++ b/recruit_candidate_flow_007__long/reward.py @@ -0,0 +1,585 @@ +""" +Reward Script: P1 — Recruiting onsite scheduling loop +Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_p1.py +Variant: eval +Mocks: greenhouse_mock,google_calendar_mock,gmail_mock,slack_mock +""" +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', 'google_calendar': 'http://28.7.184.198:8141', '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 _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 (refine v2: schema-aligned) === +def _gh_stage_index(state): + """Build {stage_id: stageType} index from greenhouse state.""" + out = {} + for s in (state or {}).get("jobStages", []) or []: + if isinstance(s, dict) and s.get("id"): + out[s["id"]] = norm(s.get("stageType")) + return out + + +def _gh_candidate_name(state, candidate_id): + for c in (state or {}).get("candidates", []) or []: + if isinstance(c, dict) and c.get("id") == candidate_id: + return c.get("name") or f"{c.get('firstName', '')} {c.get('lastName', '')}".strip() + return "" + + +def reward(go): + gh_initial = go("greenhouse")["initial_state"] or {} + gh_current = go("greenhouse")["current_state"] or {} + + stage_idx_initial = _gh_stage_index(gh_initial) + stage_idx_current = _gh_stage_index(gh_current) + + apps_i = gh_initial.get("applications", []) or [] + apps_c = {a.get("id"): a for a in (gh_current.get("applications", []) or []) + if isinstance(a, dict)} + + events = go("google_calendar")["current_state"].get("events", []) or [] + gmail_state = go("gmail")["current_state"] + sent = _gmail_sent_emails(gmail_state) + slack = go("slack")["current_state"] + + # Candidates initially in any "phone_screen" stage. + cands = [] + for a in apps_i: + if not isinstance(a, dict): + continue + if stage_idx_initial.get(a.get("currentStageId")) != "phone_screen": + continue + cands.append({ + "appId": a.get("id"), + "candidateId": a.get("candidateId"), + "name": _gh_candidate_name(gh_initial, a.get("candidateId")), + }) + n = len(cands) + chan = _slack_channel_messages(slack, "recruiting") + + # Reward-check prepared states may normalize away candidate names in text fields. + has_sent_fallback = len(sent) >= n and n > 0 + has_ops_post_fallback = len(chan) >= n and n > 0 + + stage_done = 0 + event_done = 0 + email_done = 0 + slack_done = 0 + + for c in cands: + name = c["name"] + + cur_app = apps_c.get(c["appId"], {}) if c["appId"] else {} + cur_stage_id = cur_app.get("currentStageId") + stage_ok = stage_idx_current.get(cur_stage_id) == "onsite" + + ev = next((v for v in events if name and has_text(v.get("title", ""), name)), None) + event_ok = False + if ev: + st, en = _parse(ev.get("start")), _parse(ev.get("end")) + if st and en: + # Convert both 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 + + # Convert to local time for hour checking + if st.tzinfo is not None: + st_local = st.astimezone() + else: + st_local = st + event_ok = bool((en_naive - st_naive).seconds == 3600 and 14 <= st_local.hour < 17) + # print(name, sent) + email_ok = bool(name) and any(has_text(_email_text(e), name) for e in sent) + slack_ok = bool(name) and any(has_text(_slack_msg_text(m), name) for m in chan) + + if not email_ok and has_sent_fallback: + email_ok = True + # (removed loose fallback: a #recruiting post must actually name the + # candidate rather than being credited on message count alone) + + stage_done += int(stage_ok) + event_done += int(event_ok) + email_done += int(email_ok) + slack_done += int(slack_ok) + + print('stage_done', stage_done, 'event_done', event_done, 'email_done', email_done, 'slack_done', slack_done, 'n', n) + stage_rate = frac(stage_done, n) if n else 0.0 + event_rate = frac(event_done, n) if n else 0.0 + email_rate = frac(email_done, n) if n else 0.0 + slack_rate = frac(slack_done, n) if n else 0.0 + + base = 0.30 * stage_rate + 0.35 * event_rate + 0.25 * email_rate + 0.10 * slack_rate + overlaps = _overlaps(events) + penalty = 0.1 * overlaps + score = base - penalty + + print( + "DEBUG_ccf892d6 " + f"ver=20260615_refinev2 n={n} sent={len(sent)} chan={len(chan)} events={len(events)} overlaps={overlaps} " + f"stage_rate={round(stage_rate, 4)} event_rate={round(event_rate, 4)} " + f"email_rate={round(email_rate, 4)} slack_rate={round(slack_rate, 4)} " + f"has_sent_fallback={has_sent_fallback} has_ops_post_fallback={has_ops_post_fallback} " + f"base={round(base, 4)} 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/recruit_offer_003/_cua_gym_vm_bridge.sh b/recruit_offer_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_offer_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/recruit_offer_003/initial_setup.py b/recruit_offer_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d61411dc49fa992af11c51f6b12592653d6ea791 --- /dev/null +++ b/recruit_offer_003/initial_setup.py @@ -0,0 +1,280 @@ +""" +Initial Setup: Extend offer to Sofia Rossi for Marketing Manager (PRE-task state) +Task ID: recruit_offer_001 +Domain: mock_websites (greenhouse + outlook_web + slack) + +Real mocks used (all live in the registry): + Greenhouse (8146) — ATS pipeline: Sofia's application sits in the 'Recruiter Screen' + stage (NOT yet in the 'Offer' stage); NO offer record. + Outlook (8168) — recruiter mailbox; NO sent offer email to Sofia yet. + Slack (8178) — #hiring channel with prior chatter; NO offer announcement yet. + +Pre-task invariants (so reward scores ONLY task-introduced deltas): + - Greenhouse: job 'Marketing Manager' with an explicit 'Offer' stage. Sofia Rossi + candidate + application in the 'Recruiter Screen' stage. offers list is empty. + - Outlook: recruiter (jordan.avery@company.com) inbox + prior sent mail; no offer email. + - Slack: #hiring with 2 pre-seeded messages; no offer-extended announcement. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +GREENHOUSE_URL = 'http://28.7.184.198:8146' +OUTLOOK_URL = 'http://28.7.184.198:8168' +SLACK_URL = 'http://28.7.184.198:8178' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated session ID: {sid}') + + +# ===================================================================== +# Greenhouse — Marketing Manager pipeline; Sofia in Recruiter Screen, no offer. +# ===================================================================== +def build_greenhouse_state(): + users = [ + {"id": "user-1", "firstName": "Jordan", "lastName": "Avery", "name": "Jordan Avery", + "email": "jordan.avery@company.com", "role": "recruiter", + "department": "People Operations", "title": "Senior Recruiter", "avatarUrl": None}, + {"id": "user-2", "firstName": "Lisa", "lastName": "Thompson", "name": "Lisa Thompson", + "email": "lisa.thompson@company.com", "role": "hiring_manager", + "department": "Marketing", "title": "VP of Marketing", "avatarUrl": None}, + ] + departments = [{"id": "dept-mkt", "name": "Marketing", "parentId": None}] + offices = [{"id": "office-1", "name": "San Francisco HQ", "location": "San Francisco, CA"}] + + jobs = [{ + "id": "job-mm", "title": "Marketing Manager", "status": "open", + "departmentId": "dept-mkt", "officeId": "office-1", + "hiringManagerId": "user-2", "recruiterId": "user-1", "coordinatorId": None, + "openings": 1, "openDate": "2026-05-01", + }] + + # Ordered pipeline stages for the Marketing Manager job. + stage_names = ["Application Review", "Recruiter Screen", "Hiring Manager Interview", + "Final Interview", "Offer"] + job_stages = [] + for i, nm in enumerate(stage_names): + job_stages.append({ + "id": f"stage-mm-{i}", "jobId": "job-mm", "name": nm, "orderIndex": i, + "stageType": nm.lower().replace(' ', '_'), + }) + screen_stage_id = "stage-mm-1" # Recruiter Screen (Sofia starts here) + + candidates = [ + {"id": "cand-sofia", "firstName": "Sofia", "lastName": "Rossi", "name": "Sofia Rossi", + "email": "sofia.rossi@gmail.com", "phone": "(415) 555-0170", + "location": "San Francisco, CA", "currentCompany": "Digital Solutions Inc.", + "currentTitle": "Senior Marketing Strategist", "resumeUrl": "#", "linkedinUrl": "#", + "source": "applied", "referrerId": None, "tags": ["marketing", "senior"], + "createdAt": "2026-06-01T10:00:00Z", "updatedAt": "2026-06-23T10:00:00Z"}, + {"id": "cand-elena", "firstName": "Elena", "lastName": "Vasquez", "name": "Elena Vasquez", + "email": "elena.vasquez@gmail.com", "phone": "(415) 555-0171", + "location": "Remote", "currentCompany": "BrandWorks", "currentTitle": "Marketing Lead", + "resumeUrl": "#", "linkedinUrl": "#", "source": "applied", "referrerId": None, + "tags": ["marketing"], "createdAt": "2026-06-02T10:00:00Z", "updatedAt": "2026-06-20T10:00:00Z"}, + ] + + applications = [ + {"id": "app-sofia", "candidateId": "cand-sofia", "jobId": "job-mm", + "currentStageId": screen_stage_id, "status": "active", + "appliedAt": "2026-06-01T10:00:00Z", "rejectedAt": None, "rejectionReason": None, + "hiredAt": None, "lastActivityAt": "2026-06-23T10:00:00Z", "source": "applied", + "creditedTo": None, "recruiterId": "user-1", "coordinatorId": None, + "actionRequired": None, "daysInCurrentStage": 3}, + {"id": "app-elena", "candidateId": "cand-elena", "jobId": "job-mm", + "currentStageId": "stage-mm-0", "status": "active", + "appliedAt": "2026-06-02T10:00:00Z", "rejectedAt": None, "rejectionReason": None, + "hiredAt": None, "lastActivityAt": "2026-06-20T10:00:00Z", "source": "applied", + "creditedTo": None, "recruiterId": "user-1", "coordinatorId": None, + "actionRequired": None, "daysInCurrentStage": 6}, + ] + + return { + "currentUser": users[0], + "users": users, + "departments": departments, + "offices": offices, + "jobs": jobs, + "jobStages": job_stages, + "candidates": candidates, + "applications": applications, + "scorecards": [], + "interviews": [], + "offers": [], + "notes": [], + "activityFeed": [], + "notifications": [], + "sources": [{"id": "src-applied", "name": "Applied"}], + "rejectionReasons": [], + "settings": {}, + "ui": {"selectedJobId": "job-mm", "selectedApplicationId": "app-sofia"}, + } + + +# ===================================================================== +# Outlook — recruiter mailbox; no offer email to Sofia yet. +# ===================================================================== +def build_outlook_state(): + return { + "user": {"id": "u1", "name": "Jordan Avery", "email": "jordan.avery@company.com", + "avatar": "https://picsum.photos/100/100?random=user1"}, + "folders": [ + {"id": "inbox", "name": "Inbox", "icon": "Inbox", "type": "system"}, + {"id": "sent", "name": "Sent Items", "icon": "Send", "type": "system"}, + {"id": "drafts", "name": "Drafts", "icon": "File", "type": "system"}, + {"id": "archive", "name": "Archive", "icon": "Archive", "type": "system"}, + {"id": "deleted", "name": "Deleted Items", "icon": "Trash2", "type": "system"}, + {"id": "junk", "name": "Junk Email", "icon": "Ban", "type": "system"}, + ], + "emails": [ + {"id": "email-1", "folderId": "inbox", + "from": {"name": "Sofia Rossi", "email": "sofia.rossi@gmail.com"}, + "to": [{"name": "Jordan Avery", "email": "jordan.avery@company.com"}], + "subject": "Thank you — Marketing Manager final interview", + "body": "Hi Jordan,\n\nThank you for the final interview. I'm very excited about " + "the Marketing Manager role and the team.\n\nBest,\nSofia", + "preview": "Thank you for the final interview...", + "timestamp": "2026-06-23T17:00:00Z", "read": True, "flagged": False, "categories": []}, + {"id": "email-2", "folderId": "inbox", + "from": {"name": "Lisa Thompson", "email": "lisa.thompson@company.com"}, + "to": [{"name": "Jordan Avery", "email": "jordan.avery@company.com"}], + "subject": "Marketing Manager — hiring decision", + "body": "Jordan, the panel is aligned. Let's move Sofia forward to an offer.", + "preview": "The panel is aligned...", + "timestamp": "2026-06-23T18:30:00Z", "read": False, "flagged": True, "categories": []}, + {"id": "email-3", "folderId": "sent", + "from": {"name": "Jordan Avery", "email": "jordan.avery@company.com"}, + "to": [{"name": "Sofia Rossi", "email": "sofia.rossi@gmail.com"}], + "subject": "Final interview scheduling — Marketing Manager", + "body": "Hi Sofia,\n\nConfirming your final interview for the Marketing Manager role.", + "preview": "Confirming your final interview...", + "timestamp": "2026-06-19T11:00:00Z", "read": True, "flagged": False, "categories": []}, + ], + "contacts": [ + {"id": "c-sofia", "name": "Sofia Rossi", "email": "sofia.rossi@gmail.com"}, + {"id": "c-lisa", "name": "Lisa Thompson", "email": "lisa.thompson@company.com"}, + ], + "tasks": [], + "events": [], + "categories": [], + "rules": [], + "quickSteps": [], + # NOTE: the Outlook frontend reads settings.autoReply.* and settings.signature.* + # WITHOUT null-guards, so a full settings object is required or the page renders blank. + "settings": { + "theme": "light", "density": "default", "fontSize": "medium", + "conversationView": True, "focusedInbox": True, "previewText": True, + "readingPanePosition": "right", "highContrast": False, "screenReader": False, + "language": "en-US", "dateFormat": "M/D/YYYY", "timeFormat": "h:mm A", + "weekStart": 0, "defaultEventDuration": 30, + "defaultReminder": 15, "defaultReminderMinutes": 15, + "composeFont": "Calibri", "composeFontSize": 12, "composeFormat": "html", + "includeOriginalInReply": True, "alwaysShowBcc": False, + "autoAddContacts": False, "autoDeclineConflicts": False, + "contactSortOrder": "firstName", "calendarSharingPermission": "none", + "publishCalendar": False, "blockedSenders": [], "safeSenders": [], "rules": [], + "signature": {"name": "Jordan Avery", + "html": "

Jordan Avery
Talent Acquisition
Company Inc.

"}, + "autoReply": {"enabled": False, "internalMessage": "", "externalMessage": "", + "startTime": None, "endTime": None}, + }, + } + + +# ===================================================================== +# Slack — #hiring with prior chatter; no offer announcement yet. +# ===================================================================== +def build_slack_state(): + recruiter = {"userId": "user_recruiter", "fullName": "Jordan Avery", "displayName": "Jordan", + "email": "jordan.avery@company.com", "avatar": "https://picsum.photos/200/200?random=11", + "status": "online", "statusMessage": "Recruiting", "statusEmoji": "", + "timeZone": "America/New_York"} + lisa = {"userId": "user_lisa", "fullName": "Lisa Thompson", "displayName": "Lisa", + "email": "lisa.thompson@company.com", "avatar": "https://picsum.photos/200/200?random=12", + "status": "online", "statusMessage": "Hiring Manager", "statusEmoji": "", + "timeZone": "America/New_York"} + return { + "currentUser": recruiter, + "workspace": {"workspaceId": "ws_company", "workspaceName": "Company Workspace", "icon": ""}, + "users": [recruiter, lisa], + "channels": [ + {"channelId": "general", "name": "general", "description": "Company-wide chat", + "topic": "General", "isPrivate": False, "isStarred": False, + "members": ["user_recruiter", "user_lisa"], "createdBy": "user_recruiter", + "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "hiring", "name": "hiring", "description": "Recruitment and hiring updates", + "topic": "Hiring", "isPrivate": False, "isStarred": True, + "members": ["user_recruiter", "user_lisa"], "createdBy": "user_recruiter", + "createdAt": "2024-01-15T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "general": [ + {"messageId": "msg_gen_1", "senderId": "user_lisa", + "content": "Morning team! Busy week of interviews ahead.", + "timestamp": "2026-06-20T09:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + "hiring": [ + {"messageId": "msg_hire_1", "senderId": "user_recruiter", + "content": "Strong final-round candidates for the Marketing Manager role this week.", + "timestamp": "2026-06-22T14:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_hire_2", "senderId": "user_lisa", + "content": "Agreed — the final interviews went really well. Let's align on next steps.", + "timestamp": "2026-06-23T16:30:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + }, + "threads": {}, "dms": [], "bookmarkedMessages": [], "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], "notifications": [], + } + + +# ===================================================================== +# Inject baseline state (action: "set" -> initial_state == current_state) +# ===================================================================== +mocks = [ + ("Greenhouse", GREENHOUSE_URL, build_greenhouse_state()), + ("Outlook", OUTLOOK_URL, build_outlook_state()), + ("Slack", SLACK_URL, build_slack_state()), +] + +for name, url, state in mocks: + print(f'Injecting initial state into {name} mock...') + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name} state injection failed: {resp.status_code} {resp.text}' + +for name, url, _ in mocks: + go = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state'), f'{name} initial_state is None after injection' + assert go.get('current_state'), f'{name} current_state is None after injection' +print(f'States injected + verified for all three mocks: sid={sid}') + + +# ===================================================================== +# Launch GUI (Chrome) for all three surfaces with DISPLAY=:0 +# ===================================================================== +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + + +launch_gui(f'google-chrome "{GREENHOUSE_URL}/?sid={sid}"', delay_sec=3.0) +print(f'GUI_READY: launched Greenhouse at {GREENHOUSE_URL}/?sid={sid}') +launch_gui(f'google-chrome "{OUTLOOK_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched Outlook at {OUTLOOK_URL}/?sid={sid}') +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched Slack at {SLACK_URL}/?sid={sid}') + +print('Initial setup complete - Greenhouse, Outlook, and Slack are ready for the agent') diff --git a/recruit_offer_003/reward.py b/recruit_offer_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..dbfa9e5a86d80da0b1da077e979c90d92101e2af --- /dev/null +++ b/recruit_offer_003/reward.py @@ -0,0 +1,233 @@ +""" +Reward Script: Extend offer to Sofia Rossi (Marketing Manager) across 3 real mocks. +Task ID: recruit_offer_001 +Domain: mock_websites (greenhouse + outlook_web + slack) + +Scoring (all scored on the DELTA vs initial_state, so initial_env == 0.0): + Component 1 — GREENHOUSE, 0.40: + 1a (0.15) Sofia's application moved INTO the 'Offer' stage (out of its initial stage). + 1b (0.25) A NEW offer record exists for Sofia with base salary 120000 AND + start date 2026-08-03. + Component 2 — OUTLOOK, 0.30: + A NEW sent email (absent in initial) to sofia.rossi@gmail.com that is a + Marketing Manager offer (role keyword + 'offer' present). + Component 3 — SLACK, 0.30: + A NEW #hiring message announcing the offer to Sofia Rossi for Marketing Manager, + WITHOUT disclosing the salary figure (120,000 / 120000 / 120k / $120 must be ABSENT). +""" +import re +import sys + +import requests + +GREENHOUSE_URL = 'http://28.7.184.198:8146' +OUTLOOK_URL = 'http://28.7.184.198:8168' +SLACK_URL = 'http://28.7.184.198:8178' + +SOFIA_EMAIL = 'sofia.rossi@gmail.com' +ROLE = 'marketing manager' +EXPECTED_SALARY = 120000.0 +START_DATE_ISO = '2026-08-03' + + +def read_sid(): + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid empty') + return sid + except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + return None + + +def fetch(url, sid): + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=20).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + except Exception as e: + print(f'ERROR: cannot fetch {url}: {e}') + return None, None + + +def strip_html(s): + return re.sub(r'<[^>]+>', ' ', s or '') + + +def has_salary_figure(text): + """True if text discloses the $120,000 salary in any common form.""" + t = (text or '').lower().replace(',', '').replace('$', '') + if '120000' in t: + return True + if '120k' in t: + return True + if re.search(r'\b120\b', t): + return True + return False + + +def salary_matches(value): + """Tolerant match for a 120000 salary from a number or a text field.""" + if isinstance(value, (int, float)): + return abs(float(value) - EXPECTED_SALARY) <= 1.0 + if isinstance(value, str): + norm = value.lower().replace(',', '').replace('$', '').replace(' ', '') + return '120000' in norm or '120k' in norm + return False + + +def verify_greenhouse(sid): + """Component 1 (0.40): Sofia moved to 'Offer' stage + offer record with salary+start.""" + init, cur = fetch(GREENHOUSE_URL, sid) + if cur is None: + print('FAIL: Greenhouse unreachable') + return 0.0 + score = 0.0 + try: + # Resolve stage-id -> stage-name (current), and find the 'Offer' stage id. + stages = {s.get('id'): (s.get('name') or '').strip().lower() + for s in (cur.get('jobStages') or [])} + offer_stage_ids = {sid_ for sid_, nm in stages.items() if nm == 'offer'} + + def find_app(state): + # Sofia's candidate id, then her application. + cand_id = None + for c in (state.get('candidates') or []): + if (c.get('email') or '').lower() == SOFIA_EMAIL: + cand_id = c.get('id') + break + for a in (state.get('applications') or []): + if a.get('candidateId') == cand_id: + return a + return None + + init_app = find_app(init) or {} + cur_app = find_app(cur) or {} + init_stage = init_app.get('currentStageId') + cur_stage = cur_app.get('currentStageId') + + # 1a: moved INTO Offer stage (delta) (0.15) + moved = (cur_stage in offer_stage_ids) and (init_stage not in offer_stage_ids) + if moved: + print(f'PASS: 1a — Sofia moved into Offer stage (init={init_stage} cur={cur_stage}) (0.15)') + score += 0.15 + else: + print(f'FAIL: 1a — stage move. offer_stage_ids={offer_stage_ids} ' + f'init={init_stage} cur={cur_stage}') + + # 1b: NEW offer record for Sofia with salary 120000 AND start 2026-08-03 (0.25) + init_offer_ids = {o.get('id') for o in (init.get('offers') or [])} + cand_id = cur_app.get('candidateId') + new_offer = None + for o in (cur.get('offers') or []): + if o.get('id') in init_offer_ids: + continue + if o.get('candidateId') == cand_id or o.get('applicationId') == cur_app.get('id'): + new_offer = o + break + if new_offer is not None: + salary_ok = salary_matches(new_offer.get('salary')) + sd = str(new_offer.get('startDate') or '') + start_ok = START_DATE_ISO in sd + print(f'GREENHOUSE offer: salary={new_offer.get("salary")!r} salary_ok={salary_ok} ' + f'startDate={new_offer.get("startDate")!r} start_ok={start_ok}') + if salary_ok and start_ok: + print('PASS: 1b — new offer with $120,000 & start 2026-08-03 (0.25)') + score += 0.25 + else: + print('FAIL: 1b — offer found but salary/start mismatch') + else: + print('FAIL: 1b — no new offer record for Sofia') + return score + except Exception as e: + print(f'ERROR: Greenhouse component — {e}') + return score + + +def verify_outlook(sid): + """Component 2 (0.30): NEW sent offer email to Sofia for Marketing Manager.""" + init, cur = fetch(OUTLOOK_URL, sid) + if cur is None: + print('FAIL: Outlook unreachable') + return 0.0 + try: + init_ids = {e.get('id') for e in (init.get('emails') or [])} + for e in (cur.get('emails') or []): + if e.get('folderId') != 'sent': + continue + if e.get('id') in init_ids: + continue + tos = ' '.join(f"{r.get('name','')} {r.get('email','')}" + for r in (e.get('to') or [])).lower() + recipient_ok = SOFIA_EMAIL in tos + text = (strip_html(e.get('body')) + ' ' + (e.get('subject') or '')).lower() + role_ok = ROLE in text + offer_ok = 'offer' in text + print(f"OUTLOOK: new sent recipient_ok={recipient_ok} role_ok={role_ok} " + f"offer_ok={offer_ok} subj={e.get('subject')!r}") + if recipient_ok and role_ok and offer_ok: + print('PASS: Outlook — new offer email to Sofia for Marketing Manager (0.30)') + return 0.30 + print('FAIL: Outlook — no new sent offer email to Sofia matching criteria') + return 0.0 + except Exception as e: + print(f'ERROR: Outlook component — {e}') + return 0.0 + + +def verify_slack(sid): + """Component 3 (0.30): NEW #hiring message announcing offer, WITHOUT salary figure.""" + init, cur = fetch(SLACK_URL, sid) + if cur is None: + print('FAIL: Slack unreachable') + return 0.0 + try: + def hiring_key(st): + for ch in (st.get('channels') or []): + if (ch.get('name') == 'hiring') or (ch.get('channelId') == 'hiring'): + return ch.get('channelId') + return 'hiring' + + key = hiring_key(cur) + init_ids = {m.get('messageId') for m in (init.get('messages') or {}).get(key, [])} + new_msgs = [m for m in (cur.get('messages') or {}).get(key, []) + if m.get('messageId') not in init_ids] + + for m in new_msgs: + content = m.get('content') or '' + low = content.lower() + announce_ok = ('sofia rossi' in low) and (ROLE in low) and ('offer' in low) + salary_absent = not has_salary_figure(content) + print(f"SLACK: new msg announce_ok={announce_ok} salary_absent={salary_absent} " + f"content={content!r}") + if announce_ok and salary_absent: + print('PASS: Slack — offer announcement without salary (0.30)') + return 0.30 + if announce_ok and not salary_absent: + print('FAIL: Slack — announcement DISCLOSES salary -> 0 for this component') + return 0.0 + print('FAIL: Slack — no new #hiring announcement matching criteria') + return 0.0 + except Exception as e: + print(f'ERROR: Slack component — {e}') + return 0.0 + + +def main(): + sid = read_sid() + if not sid: + print('REWARD: 0.0') + return + + total = 0.0 + total += verify_greenhouse(sid) + total += verify_outlook(sid) + total += verify_slack(sid) + + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + + +main() diff --git a/recruit_offer_003/reward_label.json b/recruit_offer_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..bd84c955d4e643fb4f0de0accde3c8770b565b37 --- /dev/null +++ b/recruit_offer_003/reward_label.json @@ -0,0 +1,64 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/recruit_offer_001_v2/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:32:38", + "label": { + "task_id": "recruit_offer_001", + "domain": "mock_websites", + "summary": "验证是否成功在 Greenhouse、Outlook 和 Slack 三个 mock 服务中向 Sofia Rossi(Marketing Manager)完成发 offer 的完整流程", + "is_placeholder": false, + "data_sources": [ + "greenhouse_mock", + "outlook_mock", + "slack_mock", + "/tmp/task_web_sid" + ], + "scoring_components": [ + { + "name": "Component 1a", + "weight": 0.15, + "description": "Greenhouse 中 Sofia 的申请从初始阶段移动到 Offer 阶段", + "check_logic": "比较 initial_state 与 current_state 中 Sofia 申请的 currentStageId,确认 cur_stage 属于 name 为 'offer' 的 stage 且 init_stage 不属于该 stage", + "pass_condition": "cur_stage 在 offer_stage_ids 中且 init_stage 不在 offer_stage_ids 中" + }, + { + "name": "Component 1b", + "weight": 0.25, + "description": "Greenhouse 中存在新的 offer 记录,且薪资和入职日期正确", + "check_logic": "在 current_state 的 offers 中查找 id 不在 initial_state 中、且 candidateId 或 applicationId 匹配的新 offer;检查 salary_matches(new_offer.get('salary')) 为真且 startDate 包含 '2026-08-03'", + "pass_condition": "存在新 offer,salary 匹配 120000(数值容差 <=1 或文本包含 120000/120k),且 startDate 包含 2026-08-03" + }, + { + "name": "Component 2", + "weight": 0.3, + "description": "Outlook 中发送了新的 offer 邮件给 Sofia", + "check_logic": "遍历 current_state sent 文件夹中 id 不在 initial_state 的新邮件;检查收件人包含 SOFIA_EMAIL,且 subject 与 body(去除 HTML)合并后的文本同时包含 ROLE('marketing manager') 和 'offer'", + "pass_condition": "存在新发送的邮件,收件人包含 sofia.rossi@gmail.com,且主题/正文同时包含 'marketing manager' 和 'offer'" + }, + { + "name": "Component 3", + "weight": 0.3, + "description": "Slack #hiring 频道发布了新的 offer 公告,且未泄露薪资", + "check_logic": "在 #hiring 频道查找 messageId 不在 initial_state 中的新消息;检查内容同时包含 'sofia rossi'、ROLE('marketing manager') 和 'offer',且 has_salary_figure(content) 返回 False", + "pass_condition": "存在新消息,内容包含 'sofia rossi'、'marketing manager'、'offer',且不包含 120000/120k/$120 等薪资数字;若公告存在但泄露薪资则该组件直接得 0" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败导致 sid 为 None,脚本直接退出并输出 REWARD: 0.0", + "任一 mock 服务(Greenhouse/Outlook/Slack)无法访问时,对应组件返回 0.0", + "Greenhouse 中 Sofia 未移动到 Offer 阶段,Component 1a 不得分", + "Greenhouse 中无新 offer 记录,或 salary/startDate 不匹配,Component 1b 不得分", + "Outlook sent 文件夹中无新邮件匹配收件人及关键词,Component 2 不得分", + "Slack #hiring 中无新消息匹配公告关键词,Component 3 不得分", + "Slack 公告匹配关键词但泄露薪资数字(has_salary_figure 返回 True),Component 3 显式返回 0.0", + "组件内部发生异常时,该组件返回当前已得分数或 0.0" + ], + "scoring_logic_explanation": "脚本首先从 /tmp/task_web_sid 读取 session id,然后依次向 Greenhouse、Outlook、Slack 三个 mock 服务拉取 initial_state 与 current_state。Greenhouse 组件分为两部分:1a 检查 Sofia 的申请 currentStageId 是否从非 Offer 阶段变为 Offer 阶段(0.15);1b 检查是否存在新的 offer 记录,其 salary 匹配 120000 且 startDate 包含 2026-08-03(0.25)。Outlook 组件检查 sent 文件夹中是否有新邮件发送给 sofia.rossi@gmail.com,且主题/正文同时包含 'marketing manager' 与 'offer'(0.30)。Slack 组件检查 #hiring 频道是否有新消息宣布 Sofia Rossi 的 Marketing Manager offer,且消息中不能出现 120000/120k/$120 等薪资数字;若公告存在但泄露薪资则该组件直接判 0(0.30)。三个组件得分累加后,通过 min(total, 1.0) 限制上限为 1.0,并四舍五入到 4 位小数作为最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 中提取:`recruit_offer_001`\n2. **Domain**: 从 docstring 中提取:`mock_websites (greenhouse + outlook_web + slack)`,按照要求应该是 `mock_websites`\n3. **Summary**: 一句话概括:验证是否成功向 Sofia Rossi(Marketing Manager)在 Greenhouse、Outlook 和 Slack 三个 mock 服务中完成发 offer 流程。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `GREENHOUSE_URL` (http://28.7.186.212:8166)\n - `OUTLOOK_URL` (http://28.7.186.212:8188)\n - `SLACK_URL` (http://28.7.186.212:8198)\n 可以写成 greenhouse_mock、outlook_mock、slack_mock,或者保留 URL。根据示例,应该是 greenhouse_mock、outlook_mock、slack_mock、/tmp/task_web_sid。\n\n6. **Scoring Components**:\n - Component 1: Greenhouse, weight 0.40\n - 1a: 0.15 - Sofia 的申请从初始阶段移动到 'Offer' 阶段\n - 1b: 0.25 - 存在新的 offer 记录,base salary 120000 且 start date 2026-08-03\n - Component 2: Outlook, weight 0.30\n - 新的已发送邮件给 sofia.rossi@gmail.com,包含 Marketing Manager 和 offer 关键词\n - Component 3: Slack, weight 0.30\n - 新的 #hiring 消息宣布 offer 给 Sofia Rossi for Marketing Manager,且不包含薪资数字\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数。\n9. **failure_modes**:\n - 读取 sid 失败(read_sid 返回 None)-> 直接退出,REWARD: 0.0\n - Greenhouse 无法访问 -> 该组件 0.0\n - Outlook 无法访问 -> 该组件 0.0\n - Slack 无法访问 -> 该组件 0.0\n - Slack 中如果 announce_ok 为真但 salary_absent 为假(泄露薪资)-> 该组件 0.0(注意这里是显式返回 0.0)\n - 各组件内部异常 -> 返回当前 score 或 0.0\n\n10. **scoring_logic_explanation**: 详细中文解释,按执行顺序:\n - 从 /tmp/task_web_sid 读取 session id。\n - 分别向三个 mock 服务(Greenhouse、Outlook、Slack)发送请求,获取 initial_state 和 current_state。\n - Greenhouse 组件(0.40):检查 Sofia 的申请是否从非 Offer 阶段移动到 Offer 阶段(0.15);检查是否存在新的 offer 记录,且 salary 为 120000、startDate 包含 2026-08-03(0.25)。\n - Outlook 组件(0.30):在 current_state 的 sent 文件夹中查找新邮件(id 不在 initial_state 中),收件人包含 sofia.rossi@gmail.com,且主题/正文同时包含 \"marketing manager\" 和 \"offer\"。\n - Slack 组件(0.30):在 #hiring 频道查找新消息(messageId 不在 initial_state 中),内容需同时包含 \"sofia rossi\"、\"marketing manager\"、\"offer\",且不能包含任何 120000/120k/$120 等薪资数字(若泄露薪资则该组件直接得 0)。\n - 三个组件得分相加,最终用 min(total, 1.0) 限制在 1.0 并四舍五入。\n\n11. **confidence**: 1.0(代码逻辑清晰完整)\n\n现在构建 JSON。注意:\n- 不要输出 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- weight 字段:Component 1 总分 0.40,但包含 1a (0.15) 和 1b (0.25)。我可以把 Component 1 拆成两个子组件,或者作为一个组件描述。根据要求 \"name: 组件名称或编号,如 Component 1\",我可以列出 Component 1、Component 2、Component 3,其中 Component 1 的 weight 是 0.40,然后在 description 和 check_logic 中说明 1a 和 1b。或者拆成 1a 和 1b。我觉得拆成 1a 和 1b 更准确,因为 weight 是显式给出的。但也可以保持 Component 1 整体。让我看看要求:\"weight 字段填写代码中显式给出的分值(如 0.3)\"。代码中显式给出了 0.40、0.30、0.30,也显式给出了 0.15 和 0.25。我可以这样组织:\n - Component 1a, weight 0.15\n - Component 1b, weight 0.25\n - Component 2, weight 0.30\n - Component 3, weight 0.30\n 这样更精确。\n\n让我再检查一下 Slack 的特殊逻辑:如果 announce_ok 为真但 salary_absent 为假,它会打印 FAIL 并返回 0.0。这是一个重要的失败模式。\n\n检查 Greenhouse 的 offer 记录查找逻辑:\n- `init_offer_ids` 是初始所有 offer id\n- 遍历 current offers,跳过在 init_offer_ids 中的\n- 检查 candidateId 或 applicationId 匹配\n- 然后检查 salary 和 startDate\n\n检查 Outlook:\n- 只检查 folderId == 'sent'\n- 跳过 initial 中已有的邮件\n- 检查收件人、body+subject 包含 ROLE 和 'offer'\n\n检查 Slack:\n- 找 #hiring 频道(name 或 channelId 为 'hiring')\n- 找新消息(messageId 不在 initial)\n- 检查内容包含 'sofia rossi'、ROLE、'offer'\n- 检查不包含薪资数字\n\n所有字符串 value 必须是中文。task_id、domain、字段名、代码标识符保留原样。\n\n让我确认 domain 的提取。docstring 中写的是 `Domain: mock_websites (greenhouse + outlook_web + slack)`,所以 domain 应该是 `mock_websites`。\n\ndata_sources 列表:根据示例,应该是 `[\"greenhouse_mock\", \"outlook_mock\", \"slack_mock\", \"/tmp/task_web_sid\"]`。或者保留 URL?示例中写的是 `slack_mock`、`github_mock` 等,所以我用服务名加 _mock。\n\nfailure_modes:\n- 读取 sid 失败导致提前退出并返回 0.0\n- 任一 mock 服务无法访问导致对应组件 0.0\n- Greenhouse 中 Sofia 未移动到 Offer 阶段\n- Greenhouse 中无新 offer 记录或 salary/startDate 不匹配\n- Outlook 中无新发送的 offer 邮件给 Sofia 或内容不匹配\n- Slack 中 #hiring 无新公告或内容不匹配\n- Slack 公告中泄露薪资数字(显式返回 0.0)\n- 组件内部异常导致该组件得 0.0 或部分得分\n\nscore_aggregation: 各组件分数相加,最终用 min(total, 1.0) 钳制到 1.0,并四舍五入到 4 位小数。\n\n现在写 JSON。确保没有思考过程、没有 markdown 代码块、没有额外解释。\n\n注意 JSON 格式要合法,字符串中的引号要转义。\n\n让我草拟内容:\n\n```json\n{\n \"task_id\": \"recruit_offer_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否成功在 Greenhouse、Outlook 和 Slack 三个 mock 服务中向 Sofia Rossi(Marketing Manager)完成发 offer 的完整流程\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"greenhouse_mock\",\n \"outlook_mock\",\n \"slack_mock\",\n \"/tmp/task_web_sid\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1a\",\n \"weight\": 0.15,\n \"description\": \"Greenhouse 中 Sofia 的申请从初始阶段移动到 Offer 阶段\",\n \"check_logic\": \"比较 initial_state 与 current_state 中 Sofia 申请的 currentStageId,确认 cur_stage 属于 name 为 'offer' 的 stage 且 init_stage 不属于该 stage\",\n \"pass_condition\": \"cur_stage 在 offer_stage_ids 中且 init_stage 不在 offer_stage_ids 中\"\n },\n {\n \"name\": \"Component 1b\",\n \"weight\": 0.25,\n \"description\": \"Greenhouse 中存在新的 offer 记录,且薪资和入职日期正确\",\n \"check_logic\": \"在 current_state 的 offers 中查找 id 不在 initial_state 中、且 candidateId/applicationId 匹配的新 offer;检查 salary_matches(new_offer.get('salary')) 为真且 startDate 包含 '2026-08-03'\",\n \"pass_condition\": \"存在新 offer,salary 匹配 120000(容差 <=1 或文本包含 120000/120k),且 startDate 包含 2026-08-03\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.3,\n \"description\": \"Outlook 中发送了新的 offer 邮件给 Sofia\",\n \"check_logic\": \"遍历 current_state sent 文件夹中 id 不在 initial_state 的新邮件;检查收件人包含 SOFIA_EMAIL,且 subject 与 body(去 HTML)合并后的文本同时包含 ROLE('marketing manager') 和 'offer'\",\n \"pass_condition\": \"存在新发送的邮件,收件人包含 sofia.rossi@gmail.com,且主题/正文同时包含 'marketing manager' 和 'offer'\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.3,\n \"description\": \"Slack #hiring 频道发布了新的 offer 公告,且未泄露薪资\",\n \"check_logic\": \"在 #hiring 频道查找 messageId 不在 initial_state 中的新消息;检查内容同时包含 'sofia rossi'、ROLE('marketing manager') 和 'offer',且 has_salary_figure(content) 返回 False\",\n \"pass_condition\": \"存在新消息,内容包含 'sofia rossi'、'marketing manager'、'offer',且不包含 120000/120k/$120 等薪资数字;若公告存在但泄露薪资则该组件直接得 0\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败导致 sid 为 None,脚本直接退出并输出 REWARD: 0.0\",\n \"任一 mock 服务(Greenhouse/Outlook/Slack)无法访问时,对应组件返回 0.0\",\n \"Greenhouse 中 Sofia 未移动到 Offer 阶段,Component 1a 不得分\",\n \"Greenhouse 中无新 offer 记录,或 salary/startDate 不匹配,Component 1b 不得分\",\n \"Outlook sent 文件夹中无新邮件匹配收件人及关键词,Component 2 不得分\",\n \"Slack #hiring 中无新消息匹配公告关键词,Component 3 不得分\",\n \"Slack 公告匹配关键词但泄露薪资数字(has_salary_figure 返回 True),Component 3 显式返回 0.0\",\n \"组件内部发生异常时,该组件返回当前已得分数或 0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先从 /tmp/task_web_sid 读取 session id,然后依次向 Greenhouse、Outlook、Slack 三个 mock 服务拉取 initial_state 与 current_state。Greenhouse 组件分为两部分:1a 检查 Sofia 的申请 currentStageId 是否从非 Offer 阶段变为 Offer 阶段(0.15);1b 检查是否存在新的 offer 记录,其 salary 匹配 120000 且 startDate 包含 2026-08-03(0.25)。Outlook 组件检查 sent 文件夹中是否有新邮件发送给 sofia.rossi@gmail.com,且主题/正文同时包含 'marketing manager' 与 'offer'(0.30)。Slack 组件检查 #hiring 频道是否有新消息宣布 Sofia Rossi 的 Marketing Manager offer,且消息中不能出现 120000/120k/$120 等薪资数字;若公告存在但泄露薪资则该组件直接判 0(0.30)。三个组件得分累加后,通过 min(total, 1.0) 限制上限为 1.0,并四舍五入到 4 位小数作为最终 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查 JSON 合法性:\n- 所有 key 都是双引号\n- 字符串中没有未转义的换行?在 JSON 中字符串不能包含字面换行符,必须转义为 \\n。但我上面的草拟中字符串值都是单行,没问题。\n- 中文标点使用正确。\n\n等等,我注意到 docstring 中 Task ID 是 `recruit_offer_001`,但文件路径中有 `recruit_offer_001_v2`。应该提取 docstring 中的 `recruit_offer_001`。\n\ndomain 是 `mock_websites`。\n\nweight 总和:0.15 + 0.25 + 0.3 + 0.3 = 1.0。正确。\n\n关于 data_sources,代码中实际请求的是 URL,但通常称为 mock 服务。我保留为 greenhouse_mock 等。\n\n关于 failure_modes 中的 \"Slack 公告存在但泄露薪资\",代码中确实是在 announce_ok 为真且 salary_absent 为假时返回 0.0。这是一个特殊的扣分/归零路径。\n\n关于 scoring_logic_explanation,我需要确保它准确描述了执行顺序和逻辑。\n\n关于 confidence,代码非常清晰,设为 1.0。\n\n最后确认:不要输出 Markdown 代码块标记,不要输出额外解释,不要输出思考过程,不要输出 标签。输出的第一个字符必须是 {,最后一个字符必须是 }。\n\n我直接输出 JSON 字符串。 {\n \"task_id\": \"recruit_offer_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否成功在 Greenhouse、Outlook 和 Slack 三个 mock 服务中向 Sofia Rossi(Marketing Manager)完成发 offer 的完整流程\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"greenhouse_mock\",\n \"outlook_mock\",\n \"slack_mock\",\n \"/tmp/task_web_sid\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1a\",\n \"weight\": 0.15,\n \"description\": \"Greenhouse 中 Sofia 的申请从初始阶段移动到 Offer 阶段\",\n \"check_logic\": \"比较 initial_state 与 current_state 中 Sofia 申请的 currentStageId,确认 cur_stage 属于 name 为 'offer' 的 stage 且 init_stage 不属于该 stage\",\n \"pass_condition\": \"cur_stage 在 offer_stage_ids 中且 init_stage 不在 offer_stage_ids 中\"\n },\n {\n \"name\": \"Component 1b\",\n \"weight\": 0.25,\n \"description\": \"Greenhouse 中存在新的 offer 记录,且薪资和入职日期正确\",\n \"check_logic\": \"在 current_state 的 offers 中查找 id 不在 initial_state 中、且 candidateId 或 applicationId 匹配的新 offer;检查 salary_matches(new_offer.get('salary')) 为真且 startDate 包含 '2026-08-03'\",\n \"pass_condition\": \"存在新 offer,salary 匹配 120000(数值容差 <=1 或文本包含 120000/120k),且 startDate 包含 2026-08-03\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.3,\n \"description\": \"Outlook 中发送了新的 offer 邮件给 Sofia\",\n \"check_logic\": \"遍历 current_state sent 文件夹中 id 不在 initial_state 的新邮件;检查收件人包含 SOFIA_EMAIL,且 subject 与 body(去除 HTML)合并后的文本同时包含 ROLE('marketing manager') 和 'offer'\",\n \"pass_condition\": \"存在新发送的邮件,收件人包含 sofia.rossi@gmail.com,且主题/正文同时包含 'marketing manager' 和 'offer'\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.3,\n \"description\": \"Slack #hiring 频道发布了新的 offer 公告,且未泄露薪资\",\n \"check_logic\": \"在 #hiring 频道查找 messageId 不在 initial_state 中的新消息;检查内容同时包含 'sofia rossi'、ROLE('marketing manager') 和 'offer',且 has_salary_figure(content) 返回 False\",\n \"pass_condition\": \"存在新消息,内容包含 'sofia rossi'、'marketing manager'、'offer',且不包含 120000/120k/$120 等薪资数字;若公告存在但泄露薪资则该组件直接得 0\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败导致 sid 为 None,脚本直接退出并输出 REWARD: 0.0\",\n \"任一 mock 服务(Greenhouse/Outlook/Slack)无法访问时,对应组件返回 0.0\",\n \"Greenhouse 中 Sofia 未移动到 Offer 阶段,Component 1a 不得分\",\n \"Greenhouse 中无新 offer 记录,或 salary/startDate 不匹配,Component 1b 不得分\",\n \"Outlook sent 文件夹中无新邮件匹配收件人及关键词,Component 2 不得分\",\n \"Slack #hiring 中无新消息匹配公告关键词,Component 3 不得分\",\n \"Slack 公告匹配关键词但泄露薪资数字(has_salary_figure 返回 True),Component 3 显式返回 0.0\",\n \"组件内部发生异常时,该组件返回当前已得分数或 0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先从 /tmp/task_web_sid 读取 session id,然后依次向 Greenhouse、Outlook、Slack 三个 mock 服务拉取 initial_state 与 current_state。Greenhouse 组件分为两部分:1a 检查 Sofia 的申请 currentStageId 是否从非 Offer 阶段变为 Offer 阶段(0.15);1b 检查是否存在新的 offer 记录,其 salary 匹配 120000 且 startDate 包含 2026-08-03(0.25)。Outlook 组件检查 sent 文件夹中是否有新邮件发送给 sofia.rossi@gmail.com,且主题/正文同时包含 'marketing manager' 与 'offer'(0.30)。Slack 组件检查 #hiring 频道是否有新消息宣布 Sofia Rossi 的 Marketing Manager offer,且消息中不能出现 120000/120k/$120 等薪资数字;若公告存在但泄露薪资则该组件直接判 0(0.30)。三个组件得分累加后,通过 min(total, 1.0) 限制上限为 1.0,并四舍五入到 4 位小数作为最终 REWARD。\",\n \"confidence\": 1.0\n}" +} diff --git a/recruit_onsite_decision_005__long/_cua_gym_vm_bridge.sh b/recruit_onsite_decision_005__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_onsite_decision_005__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_onsite_decision_005__long/initial_setup.py b/recruit_onsite_decision_005__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..db1ecf03889f75878feba64597492600f4ca5994 --- /dev/null +++ b/recruit_onsite_decision_005__long/initial_setup.py @@ -0,0 +1,685 @@ +""" +Initial Setup: Onsite hiring decisions with conflicting scorecards & must-read rubric +Task ID: recruit_onsite_decision_005__long (output/0707 #14, cluster D / recruiting) +Mocks: greenhouse_mock, gmail_mock, google_calendar_mock, slack_mock + +The agent is a technical recruiter making onsite decisions for the 'Senior Backend +Engineer' job (job-1). For each active onsite application, read the SUBMITTED scorecards +and decide advance / reject / leave -- but the RUBRIC is NOT in the instruction: + + * lever j (must-read): the advance/reject/leave rubric lives in the Slack #hiring PINNED + message (advance iff no strong_no/no AND >=2 strong_yes/yes; reject iff any strong_no + OR >=2 no; else leave). Instruction only says "make onsite decisions per the #hiring rubric". + * lever h (conflict): candidate cand-3 has TWO scorecards from the same interviewer -- an + early strong_no (submitted day-5) and a later REVISED yes (submitted day-1). Only the + LATEST scorecard per interviewer counts, so cand-3's recs are {yes, strong_yes} -> ADVANCE. + Using the stale strong_no -> wrongly reject. + * lever i (bulk + keep-group): 9 onsite applications. 6 to decide (2 advance / 2 reject / + 2 leave); 1 pending-scorecard (unsubmitted -> must leave); 2 non-onsite/already-decided + (keep). Actioning a leave/keep/pending candidate lowers decision-set PRECISION. Denom = 6. + +Advance -> move to Offer stage + book a debrief calendar event (candidate as guest). +Reject -> status 'rejected' + send a rejection email. The agent posts a #hiring summary. + +GROUND TRUTH: greenhouse.applications[*]._decision (precomputed, latest-per-interviewer); +google_calendar/gmail answer keys via the same. State shape copied from the shipped +b69c97fd reference (greenhouse has no schema md). +Observable results ship ABSENT (Rule 3): onsite apps active in Onsite stage, no debrief +events, no rejection emails, no #hiring summary. + +SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): b69c97fd's subtractive leave/distractor +penalties are CONVERTED to a positive decision-set precision denominator. No negatives, no gate. +""" +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}') + + +NOW = _dt.datetime(2026, 4, 30, 9, 0, 0) + + +def iso(dt): + return dt.strftime('%Y-%m-%dT%H:%M:%SZ') + + +APPLIED_AT = iso(NOW - _dt.timedelta(days=20)) +LAST_ACTIVITY = iso(NOW - _dt.timedelta(days=1)) +EVENT_DATE = (NOW + _dt.timedelta(days=3)).strftime('%Y-%m-%d') # debrief date = 2026-05-03 +REJECT_REASON = 'Not enough support' +# review (2026-07-11): a debrief is an INTERNAL post-onsite review — the attendee is the +# hiring manager, NOT the candidate. Instruction + reward both key off this. +HIRING_MANAGER_EMAIL = 'omar.farouk@company.com' + + +# --------------------------------------------------------------------------- +# Users (interviewers + recruiter). +# --------------------------------------------------------------------------- +GH_USERS = [ + {'id': 'user-1', 'firstName': 'Dana', 'lastName': 'Cruz', 'name': 'Dana Cruz', + 'email': 'dana.cruz@company.com', 'role': 'recruiter'}, + {'id': 'user-5', 'firstName': 'Ravi', 'lastName': 'Shah', 'name': 'Ravi Shah', + 'email': 'ravi.shah@company.com', 'role': 'interviewer'}, + {'id': 'user-6', 'firstName': 'Mei', 'lastName': 'Lin', 'name': 'Mei Lin', + 'email': 'mei.lin@company.com', 'role': 'interviewer'}, + {'id': 'user-3', 'firstName': 'Omar', 'lastName': 'Farouk', 'name': 'Omar Farouk', + 'email': 'omar.farouk@company.com', 'role': 'hiring_manager'}, +] +GH_CURRENT_USER = GH_USERS[0] + + +def job_stages(job_id): + spec = [ + ('Application Review', 'application_review'), + ('Recruiter Phone 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') +ONSITE_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'onsite') +OFFER_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'offer') +TECH_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'interview') + +GH_JOBS = [ + {'id': 'job-1', 'title': 'Senior Backend Engineer', 'status': 'open', + 'departmentId': 'dept-1', 'officeId': 'office-1', 'hiringManagerId': 'user-3', + 'recruiterId': 'user-1', 'openings': 2, 'openDate': '2026-04-01', 'closeDate': None, + 'description': 'Own core backend services in Go/Python.', + 'requirements': ['5+ years backend', 'Distributed systems'], + 'stages': [s['id'] for s in JOB1_STAGES], 'candidateCount': None, # set after apps built + 'createdAt': '2026-04-01T09:00:00Z', 'updatedAt': LAST_ACTIVITY}, +] + + +# --------------------------------------------------------------------------- +# Candidates. +# --------------------------------------------------------------------------- +ONSITE_CANDS = [ + ('cand-1', 'Alex', 'Chen'), # advance + ('cand-2', 'Bianca', 'Romero'), # advance + ('cand-3', 'Caleb', 'Idris'), # h: stale strong_no vs revised yes -> ADVANCE + ('cand-4', 'Dahlia', 'Novak'), # reject (>=2 no) + ('cand-5', 'Ezra', 'Mbeki'), # reject (strong_no) + ('cand-6', 'Farida', 'Haddad'), # leave (mixed: one no, one yes) + ('cand-7', 'Gita', 'Rao'), # leave (insufficient: one submitted yes) + ('cand-8', 'Hugo', 'Blanc'), # pending scorecards (unsubmitted) -> leave +] +KEEP_CANDS = [ + ('cand-9', 'Ivan', 'Petrov'), # already in Offer (keep) + ('cand-10', 'Julia', 'Mwangi'), # Technical Interview stage (not onsite, keep) +] +ALL_CANDS = ONSITE_CANDS + KEEP_CANDS +GH_CANDIDATES = [ + {'id': cid, 'firstName': fn, 'lastName': ln, 'name': f'{fn} {ln}', + 'email': f'{fn.lower()}.{ln.lower()}@example.com', 'phone': f'+1-555-{i:04d}', + 'location': 'Remote', 'currentCompany': 'Acme', 'currentTitle': 'Engineer', + 'source': 'applied', '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} +EMAIL_BY_CAND = {c['id']: c['email'] for c in GH_CANDIDATES} + + +# --------------------------------------------------------------------------- +# Scorecard plans: cand -> list of (interviewerId, rec, submitted_days_ago) +# rec None = pending (unsubmitted) -> ignored. Multiple entries from same interviewer: +# only the LATEST submitted (smallest days_ago) counts (lever h for cand-3). +# --------------------------------------------------------------------------- +SCORECARD_PLAN = { + 'cand-1': [('user-5', 'strong_yes', 2), ('user-6', 'yes', 2), ('user-3', 'yes', 2)], + 'cand-2': [('user-5', 'strong_yes', 2), ('user-6', 'strong_yes', 2)], + # cand-3: user-6 submitted strong_no (day-5), then REVISED to yes (day-1). Latest = yes. + 'cand-3': [('user-5', 'strong_yes', 2), ('user-6', 'strong_no', 5), ('user-6', 'yes', 1)], + 'cand-4': [('user-5', 'no', 2), ('user-6', 'no', 2), ('user-3', 'yes', 2)], + 'cand-5': [('user-5', 'yes', 2), ('user-6', 'strong_no', 2)], + 'cand-6': [('user-5', 'yes', 2), ('user-6', 'no', 2)], + 'cand-7': [('user-5', 'yes', 2)], + 'cand-8': [('user-5', None, None), ('user-6', None, None)], # pending -> leave +} + + +def _latest_per_interviewer(entries): + """Keep only submitted (rec != None), latest (smallest days_ago) per interviewer.""" + best = {} + for (iv, rec, days) in entries: + if rec is None: + continue + if iv not in best or days < best[iv][1]: + best[iv] = (rec, days) + return [rec for (rec, _days) in best.values()] + + +def decide(recs): + has_strong_no = any(r == 'strong_no' for r in recs) + num_no = sum(1 for r in recs if r == 'no') + num_yes = sum(1 for r in 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' + + +# --------------------------------------------------------------------------- +# Build applications + scorecards + _decision answer key. +# --------------------------------------------------------------------------- +GH_APPLICATIONS = [] +GH_SCORECARDS = [] +_sc_id = 1 +for (cid, fn, ln) in ONSITE_CANDS: + entries = SCORECARD_PLAN[cid] + recs = _latest_per_interviewer(entries) + action = decide(recs) + cand_email = EMAIL_BY_CAND[cid] + cand_name = NAME_BY_CAND[cid] + if action == 'advance': + dec = {'action': 'advance', 'target_stage_id': OFFER_STAGE_ID, + 'email_subject': None, 'reject_reason': None, + 'event_title': f'Debrief - {cand_name}', 'event_date': EVENT_DATE, + # debrief is an internal review -> attendee is the hiring manager, not the candidate + 'debrief_attendee_email': HIRING_MANAGER_EMAIL, + 'reject_to_email': None, 'candidate_name': cand_name} + elif action == 'reject': + dec = {'action': 'reject', 'target_stage_id': None, + 'email_subject': f'Update on your application - {cand_name}', + 'reject_reason': REJECT_REASON, 'event_title': None, 'event_date': None, + 'debrief_attendee_email': None, + # rejection email must go to the candidate themselves + 'reject_to_email': cand_email, 'candidate_name': cand_name} + else: + dec = {'action': 'leave', 'target_stage_id': None, 'email_subject': None, + 'reject_reason': None, 'event_title': None, 'event_date': None, + 'debrief_attendee_email': None, 'reject_to_email': None, + 'candidate_name': cand_name} + GH_APPLICATIONS.append({ + 'id': f'app-{cid}', 'candidateId': cid, 'jobId': 'job-1', + 'currentStageId': ONSITE_STAGE_ID, 'status': 'active', + 'appliedAt': APPLIED_AT, 'actionRequired': 'needs_decision', '_decision': dec, + }) + for (iv, rec, days) in entries: + submitted = rec is not None + GH_SCORECARDS.append({ + 'id': f'sc-{_sc_id}', 'applicationId': f'app-{cid}', 'candidateId': cid, + 'jobId': 'job-1', 'interviewerId': iv, 'stageId': ONSITE_STAGE_ID, + 'overallRecommendation': rec, + 'submittedAt': iso(NOW - _dt.timedelta(days=days)) if submitted else None, + 'status': 'submitted' if submitted else 'pending', + 'notes': ('Revised after follow-up.' if (cid == 'cand-3' and days == 1) else ''), + }) + _sc_id += 1 + +# Keep candidates: already-decided / non-onsite (must NOT be actioned). +GH_APPLICATIONS.append({'id': 'app-cand-9', 'candidateId': 'cand-9', 'jobId': 'job-1', + 'currentStageId': OFFER_STAGE_ID, 'status': 'active', + 'appliedAt': APPLIED_AT, 'actionRequired': None, + '_decision': {'action': 'keep'}}) +GH_APPLICATIONS.append({'id': 'app-cand-10', 'candidateId': 'cand-10', 'jobId': 'job-1', + 'currentStageId': TECH_STAGE_ID, 'status': 'active', + 'appliedAt': APPLIED_AT, 'actionRequired': None, + '_decision': {'action': 'keep'}}) + +# review comment #4: the Jobs-list "Candidates" column reads job.candidateCount verbatim +# (greenhouse_mock does NOT recompute it from applications on inject). It was hard-set to 9 +# while there are 10 applications -> Jobs list showed 9 but Overview/Pipeline/Candidates showed +# 10. Derive it from the actual applications so all views agree (10 = 8 onsite + 1 offer + 1 tech). +for _j in GH_JOBS: + _j['candidateCount'] = sum(1 for a in GH_APPLICATIONS if a['jobId'] == _j['id']) + + +# --------------------------------------------------------------------------- +# Precompute answer key. +# --------------------------------------------------------------------------- +def _apps_by_action(act): + return [a['id'] for a in GH_APPLICATIONS + if a.get('currentStageId') == ONSITE_STAGE_ID and a['status'] == 'active' + and a['_decision'].get('action') == act] + + +ADVANCE_IDS = _apps_by_action('advance') +REJECT_IDS = _apps_by_action('reject') +LEAVE_IDS = _apps_by_action('leave') +DECIDE_IDS = ADVANCE_IDS + REJECT_IDS + LEAVE_IDS # the 6 real decisions +KEEP_IDS = ['app-cand-9', 'app-cand-10'] +PENDING_ID = 'app-cand-8' # pending scorecards -> leave (subset of LEAVE_IDS) + +assert len(ADVANCE_IDS) == 3, ADVANCE_IDS # cand-1, cand-2, cand-3(revised) +assert len(REJECT_IDS) == 2, REJECT_IDS # cand-4, cand-5 +assert len(LEAVE_IDS) == 3, LEAVE_IDS # cand-6, cand-7, cand-8(pending) +assert 'app-cand-3' in ADVANCE_IDS, 'cand-3 must resolve to advance via the revision' +assert PENDING_ID in LEAVE_IDS, PENDING_ID +print(f'advance={ADVANCE_IDS} reject={REJECT_IDS} leave={LEAVE_IDS} keep={KEEP_IDS}') +print(f'cand-3 (h revision) -> advance; pending cand-8 -> leave') + + +# --------------------------------------------------------------------------- +# Greenhouse state. +# --------------------------------------------------------------------------- +_GREENHOUSE_STATE = { + 'currentUser': GH_CURRENT_USER, 'users': GH_USERS, + 'jobs': GH_JOBS, 'jobStages': JOB1_STAGES, + 'candidates': GH_CANDIDATES, 'applications': GH_APPLICATIONS, + 'scorecards': GH_SCORECARDS, 'notes': [], 'offers': [], 'scheduledInterviews': [], + '_task_adapter': {'source_schema': 'onsite_decisions', + 'task_id': 'c1d7e432-9a3b-4e5f-fb4c-0707cc99aa22', + 'onsite_stage_id': ONSITE_STAGE_ID, 'offer_stage_id': OFFER_STAGE_ID, + 'advance_ids': ADVANCE_IDS, 'reject_ids': REJECT_IDS, + 'leave_ids': LEAVE_IDS, 'decide_ids': DECIDE_IDS, + 'keep_ids': KEEP_IDS, 'pending_id': PENDING_ID, + 'reject_reason': REJECT_REASON}, +} + + +# --------------------------------------------------------------------------- +# Google Calendar — NO debrief events at injection (Rule 3); a decoy. +# --------------------------------------------------------------------------- +_CAL_STATE = { + 'user': {'userId': 'u1', 'email': 'dana.cruz@company.com'}, + 'calendars': [{'id': 'primary', 'name': 'Recruiting', 'color': 'bg-blue-500'}], + 'events': [{'id': 'ev_decoy', 'calendarId': 'primary', 'title': 'Weekly hiring sync', + 'start': '2026-05-01T15:00:00Z', 'end': '2026-05-01T15:30:00Z', + 'location': '', 'description': '', 'guests': [], 'color': 'bg-blue-500', + 'recurring': 'none'}], + 'today': '2026-04-30', +} +assert all('debrief -' not in (ev['title'] or '').lower() for ev in _CAL_STATE['events']) + + +# --------------------------------------------------------------------------- +# Gmail — rejection emails ABSENT; a decoy inbound. +# --------------------------------------------------------------------------- +_GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Dana Cruz', 'email': 'dana.cruz@company.com', + 'avatar': 'https://picsum.photos/200/200?random=27'}, + 'emails': [ + {'id': 'm_decoy1', 'threadId': 'thread_d1', + 'from': {'name': 'Recruiting Newsletter', 'email': 'news@company.com', 'avatar': ''}, + 'to': [{'name': 'Dana Cruz', 'email': 'dana.cruz@company.com'}], 'cc': [], 'bcc': [], + 'subject': 'Onsite debriefs due today', 'body': 'Please finalize onsite decisions.', + 'snippet': 'Please finalize onsite decisions...', 'timestamp': '2026-04-30T07:00:00Z', + 'read': False, 'starred': False, 'important': False, 'labels': [], + 'category': 'updates', 'folder': 'inbox', 'attachments': []}, + ], + 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}], + 'drafts': [], 'settings': {'density': 'default', 'undoSend': 10}, 'today': '2026-04-30', +} + + +# --------------------------------------------------------------------------- +# Slack — #hiring pinned decision rubric (lever j / must-read). +# Review fixes: +# #1 add a 'general' channel: slack_mock's index route redirects to /channel/general; +# without it the landing page shows "Channel not found". +# #2 seed realistic filler chatter in #hiring so the channel looks active and the pinned +# rubric sits above a real backlog (all filler is in initial_state -> not "new", so it +# never counts as the agent's summary post in reward). +# #3 every user (currentUser + users[]) carries fullName + displayName; slack_mock renders +# a message author via users[].userId -> fullName (else displayName, else "Unknown User"). +# --------------------------------------------------------------------------- +_RUBRIC_TEXT = ( + ':pushpin: ONSITE DECISION RUBRIC (read before deciding)\n' + '1) Use only SUBMITTED scorecards; ignore pending ones. If an interviewer submitted more ' + 'than one, use only their MOST RECENT (revised) scorecard.\n' + '2) ADVANCE (move to Offer + book a debrief) iff there is no "no"/"strong_no" AND at least ' + 'two "strong_yes"/"yes".\n' + '3) REJECT (mark rejected + send a rejection email) iff there is any "strong_no" OR at least ' + 'two "no".\n' + '4) Otherwise LEAVE the candidate as-is (including anyone whose scorecards are still pending).' +) + + +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', 'Dana', 'Cruz'), # recruiter (current user) + _slack_user('user_2', 'Omar', 'Farouk'), # hiring manager (posts the rubric) + _slack_user('user_3', 'Ravi', 'Shah'), # interviewer + _slack_user('user_4', 'Mei', 'Lin'), # interviewer +] + +# #hiring filler chatter (oldest -> newest), all pre-seeded so the pinned rubric has context. +_HIRING_FILLER = [ + ('msg_h1', 'user_2', '2026-04-01T09:05:00Z', + 'Morning all — onsite loops for the Senior Backend Engineer role wrap up this week. ' + 'Pinned the decision rubric above, please follow it exactly.'), + ('msg_h2', 'user_3', '2026-04-27T16:20:00Z', + 'Submitted my scorecards for the Tuesday onsite panel. A couple were close calls.'), + ('msg_h3', 'user_4', '2026-04-28T10:12:00Z', + 'Same here. Note I had to revise one of mine after a follow-up chat — the later one is the ' + 'one that should count.'), + ('msg_h4', 'user_2', '2026-04-29T11:30:00Z', + 'Thanks both. @Dana can you make the advance/reject calls today and book debriefs for anyone ' + 'we move to Offer?'), + ('msg_h5', 'user_1', '2026-04-30T08:45:00Z', + 'On it — going through the onsite queue now and will post a summary here when done.'), +] + +_GENERAL_FILLER = [ + ('msg_g1', 'user_2', '2026-04-15T09:00:00Z', 'Welcome to Acme Corp :wave: — company-wide updates land here.'), + ('msg_g2', 'user_4', '2026-04-25T14:00:00Z', 'Reminder: all-hands moved to Friday 10am PT.'), + ('msg_g3', 'user_1', '2026-04-29T17:30:00Z', 'Coffee chat sign-ups for May are open in the People-ops sheet.'), +] + + +def _slack_msg(mid, sender, ts, content): + return {'messageId': mid, 'senderId': sender, 'content': content, 'timestamp': ts, + 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False} + + +_SLACK_STATE = { + 'currentUser': _slack_user('user_1', 'Dana', 'Cruz'), + 'users': _SLACK_USERS, + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', + 'topic': 'Company-wide announcements', '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': 'hiring', 'name': 'hiring', 'description': 'Hiring decisions', + 'topic': 'Onsite', 'isPrivate': False, 'isStarred': True, + 'members': [u['userId'] for u in _SLACK_USERS], 'createdBy': 'user_2', + 'createdAt': '2026-01-01T10:00:00Z', 'pinnedMessages': ['msg_rubric'], 'unreadCount': 0}, + ], + 'messages': { + 'general': [_slack_msg(mid, s, ts, c) for (mid, s, ts, c) in _GENERAL_FILLER], + 'hiring': ( + [_slack_msg('msg_rubric', 'user_2', '2026-04-01T09:00:00Z', _RUBRIC_TEXT)] + + [_slack_msg(mid, s, ts, c) for (mid, s, ts, c) in _HIRING_FILLER] + ), + }, + 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [], 'notifications': [], +} + + +# --------------------------------------------------------------------------- +# Inject. +# --------------------------------------------------------------------------- +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', _CAL_STATE), # google_calendar_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/recruit_onsite_decision_005__long/reward.py b/recruit_onsite_decision_005__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fa340667c936047823ce29269724fa03e646c585 --- /dev/null +++ b/recruit_onsite_decision_005__long/reward.py @@ -0,0 +1,321 @@ +""" +Reward Script: Onsite hiring decisions with conflicting scorecards & must-read rubric +Task ID: recruit_onsite_decision_005__long (output/0707 #14, cluster D / recruiting) +Mocks: greenhouse_mock, gmail_mock, google_calendar_mock, slack_mock + +Scoring — ALL positive. Every component in [0,1]; weights sum to 1.0. NO penalties, NO gate. +(b69c97fd's subtractive leave/distractor penalties are CONVERTED to a positive decision-set +precision denominator — HIDDEN_STATE_DIFFICULTY.md §3.) + + 0.45 decision-set correctness: + frac(#correct decisions among the 6, 6 + #wrongly_actioned) + correct = advance-candidate now in Offer / reject-candidate now rejected / leave-candidate + untouched. wrongly_actioned = a leave/keep/pending candidate moved or rejected. + 0.20 advance stage moves: frac of advance candidates now in the Offer stage + 0.15 reject status+email: frac of reject candidates with status rejected AND a rejection email + addressed TO the candidate with subject 'Update on your application - ' + 0.15 advance debrief events: frac of advance candidates with a 'Debrief - ' event whose + guest is the HIRING MANAGER (internal review) AND whose date is the debrief date + 0.05 slack #hiring summary post + +Answer key: greenhouse.applications[*]._decision + initial_state._task_adapter +(advance_ids, reject_ids, leave_ids, decide_ids, keep_ids). +""" +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 norm(s): + return (str(s) if s is not None else '').strip().lower() + + +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 _all_gmail(state): + out = [] + for key in ('emails', 'drafts'): + v = state.get(key) + if isinstance(v, list): + out += [m for m in v if isinstance(m, dict)] + return out + + +def _email_text(m): + return f"{m.get('subject', '')} {m.get('body', '')} {m.get('snippet', '')}" + + +def _date_key(s): + if not s: + return '' + import datetime as dt + txt = str(s).replace('Z', '+00:00') + try: + d = dt.datetime.fromisoformat(txt) + dt.timedelta(hours=8) + return d.date().isoformat() + except Exception: + return str(s)[:10] + + +def _adapt_payload_for_reward(app, payload): + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +def _apps_map(state): + out = {} + for a in (state.get('applications') or []): + if isinstance(a, dict): + out[a.get('id')] = a + return out + + +def _cand_email(state, cand_id): + for c in (state.get('candidates') or []): + if isinstance(c, dict) and c.get('id') == cand_id: + return norm(c.get('email')) + return '' + + +# =========================================================================== +def reward(go): + W_DECISION = 0.45 + W_MOVE = 0.20 + W_REJECT = 0.15 + W_EVENT = 0.15 + W_POST = 0.05 + + gh = go('greenhouse') + 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 {} + adapter = gh_init.get('_task_adapter', {}) if isinstance(gh_init.get('_task_adapter'), dict) else {} + + offer_stage = adapter.get('offer_stage_id') + onsite_stage = adapter.get('onsite_stage_id') + advance_ids = list(adapter.get('advance_ids') or []) + reject_ids = list(adapter.get('reject_ids') or []) + leave_ids = list(adapter.get('leave_ids') or []) + decide_ids = list(adapter.get('decide_ids') or []) + keep_ids = set(adapter.get('keep_ids') or []) + n_decide = len(decide_ids) + if n_decide == 0: + print('DEBUG_GH_ONSITE fatal=no_decide_ids total=0.0') + return 0.0 + + init_apps = _apps_map(gh_init) + cur_apps = _apps_map(gh_cur) + + def _moved(aid): + cur = cur_apps.get(aid, {}) + return norm(cur.get('currentStageId')) == norm(offer_stage) + + def _rejected(aid): + return norm(cur_apps.get(aid, {}).get('status')) == 'rejected' + + def _touched(aid): + """A leave/keep candidate was wrongly actioned (moved off Onsite or rejected).""" + cur = cur_apps.get(aid, {}) + init = init_apps.get(aid, {}) + stage_changed = norm(cur.get('currentStageId')) != norm(init.get('currentStageId')) + status_changed = norm(cur.get('status')) != norm(init.get('status')) + return stage_changed or status_changed + + # ---- 1) decision-set precision (ACTIVE decisions only; leave gives NO positive credit) ---- + # Per pipeline §5 / HIDDEN_STATE §3: "leave X unchanged" must NOT earn credit (else + # do-nothing scores). Numerator = correctly-actioned advance/reject. Denominator = + # #active-required (advance+reject) + #wrongly-actioned (leave/keep/pending touched). + n_active = len(advance_ids) + len(reject_ids) + correct = 0 + for aid in advance_ids: + if _moved(aid): + correct += 1 + for aid in reject_ids: + if _rejected(aid): + correct += 1 + # wrongly_actioned = leave candidates touched + keep candidates touched + wrongly = 0 + for aid in leave_ids: + if _touched(aid): + wrongly += 1 + for aid in keep_ids: + if _touched(aid): + wrongly += 1 + decision_score = frac(correct, n_active + wrongly) + s_decision = W_DECISION * decision_score + + # ---- 2) advance stage moves ---- + move_ok = sum(1 for aid in advance_ids if _moved(aid)) + move_score = frac(move_ok, len(advance_ids)) if advance_ids else 0.0 + s_move = W_MOVE * move_score + + # ---- 3) reject status + rejection email ---- + # review (2026-07-11): to match instruction, the rejection email must (a) be addressed TO + # the candidate and (b) carry the subject 'Update on your application - '. We no longer + # accept "any new email that merely mentions the name". + gm = go('gmail') + gm_cur = gm.get('current_state', {}) if isinstance(gm.get('current_state'), dict) else {} + gm_init = gm.get('initial_state', {}) if isinstance(gm.get('initial_state'), dict) else {} + init_ids = {m.get('id') for m in _all_gmail(gm_init)} + new_emails = [m for m in _all_gmail(gm_cur) if m.get('id') not in init_ids] + + def _recipients(m): + out = set() + for r in (m.get('to') or []): + if isinstance(r, dict): + out.add(norm(r.get('email'))) + else: + out.add(norm(r)) + return out + + reject_ok = 0 + for aid in reject_ids: + app = cur_apps.get(aid, {}) + dec = app.get('_decision', {}) if isinstance(app.get('_decision'), dict) else {} + want_to = norm(dec.get('reject_to_email')) + want_subject = norm(dec.get('email_subject')) # 'update on your application - ' + email_hit = any(want_to in _recipients(m) and norm(m.get('subject')) == want_subject + for m in new_emails) + if _rejected(aid) and email_hit: + reject_ok += 1 + reject_score = frac(reject_ok, len(reject_ids)) if reject_ids else 0.0 + s_reject = W_REJECT * reject_score + + # ---- 4) advance debrief events (internal review with the hiring manager, on the debrief date) ---- + # review (2026-07-11): a debrief is an INTERNAL post-onsite review. To match instruction, + # the event must (a) be titled 'Debrief - ', (b) have the HIRING MANAGER as a guest + # (not the candidate), and (c) be scheduled on the debrief date. All three required. + cal = go('google_calendar') + cur_events = cal.get('current_state', {}).get('events', []) or [] + + def _guests(ev): + g = ev.get('guests') if isinstance(ev.get('guests'), list) else \ + (ev.get('attendees') if isinstance(ev.get('attendees'), list) else []) + out = set() + for x in g: + out.add(norm(x if isinstance(x, str) else x.get('email'))) + return out + + event_ok = 0 + for aid in advance_ids: + app = init_apps.get(aid, {}) + dec = app.get('_decision', {}) if isinstance(app.get('_decision'), dict) else {} + want_title = norm(dec.get('event_title')) + want_attendee = norm(dec.get('debrief_attendee_email')) + want_date = dec.get('event_date') + if any(norm(ev.get('title')) == want_title + and want_attendee in _guests(ev) + and _date_key(ev.get('start')) == want_date + for ev in cur_events): + event_ok += 1 + event_score = frac(event_ok, len(advance_ids)) if advance_ids else 0.0 + s_event = W_EVENT * event_score + + # ---- 5) 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, 'hiring') if isinstance(m, dict)} + _hiring_kw = ('advance', 'advanced', 'reject', 'rejected', 'decision', + 'hire', 'hiring', 'move', 'moved') + def _is_hiring_summary(m): + t = (_msg_text(m) or '').lower() + return any(k in t for k in _hiring_kw) + new_msgs = [m for m in _slack_channel_messages(scur, 'hiring') + 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_hiring_summary(m) for m in new_msgs) + s_post = W_POST * (1.0 if post_ok else 0.0) + + score = clamp01(s_decision + s_move + s_reject + s_event + s_post) + + print( + 'DEBUG_GH_ONSITE ' + f'n_active={n_active} correct={correct} wrongly={wrongly} decision={round(decision_score, 4)} ' + f'move_ok={move_ok}/{len(advance_ids)} reject_ok={reject_ok}/{len(reject_ids)} ' + f'event_ok={event_ok}/{len(advance_ids)} post={post_ok} ' + f'w_decision={round(s_decision, 4)} w_move={round(s_move, 4)} w_reject={round(s_reject, 4)} ' + f'w_event={round(s_event, 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/recruit_onsite_stage_008__long/_cua_gym_vm_bridge.sh b/recruit_onsite_stage_008__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_onsite_stage_008__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/recruit_onsite_stage_008__long/initial_setup.py b/recruit_onsite_stage_008__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..105e5c5fe867e7438876726b5a8383c9d3493847 --- /dev/null +++ b/recruit_onsite_stage_008__long/initial_setup.py @@ -0,0 +1,874 @@ +""" +Initial Setup: T09 — Greenhouse onsite debrief scheduling +Task ID: recruit_onsite_stage_008__long +Mocks: greenhouse_mock (8146), google_calendar_mock (8141), slack_mock (8178) + +Scenario (today = Mon Jun 8, 2026): + For each ACTIVE application in the 'Onsite' stage whose onsite interviews are + ALL 'completed', the agent must book a 30-min 'Debrief - ' + event on Jules Park's Google Calendar. Constraints: + (a) weekday within Jun 8-11 2026, 13:00-17:00 LOCAL, + (b) no overlap with any existing event, + (c) guests == EXACTLY the interviewers who SUBMITTED scorecards for that + application (interviewer ids resolved to user emails) -- the organizer + (Jules Park) and the candidate are NOT invited. guest_emails below is + built only from submitted scorecards, so the recruiter's own email never + enters the key and reward's exact set-match rejects a self-invite. + (d) ONE debrief per day: processed in candidate order, each candidate is + placed on the EARLIEST weekday in the window that has no debrief yet, + and within that day the EARLIEST conflict-free :00/:30 slot is used. + With 4 ready candidates and 4 weekdays (Jun 8,9,10,11) this assigns + candidate k (0-indexed, candidate order) to Jun (8+k) -- a UNIQUE answer. + THEN, in Slack, post one message per ready candidate in the '#interviews' + channel that @mentions EXACTLY that candidate's submitting interviewers (same + set as the calendar guests) and names the candidate. + +Ground-truth embedding (Rule 2 — inline hidden field): + greenhouse.applications[*]._debrief + - ready onsite app : {candidate_name, guest_emails:[...], slot_start, slot_end} + - not-ready onsite : null (explicit None — open scheduled interview) + - non-onsite app : field ABSENT + The slot_start/slot_end are PRECOMPUTED here (greedy, candidate order) so + reward.py has a single source of truth. + slack._task_adapter.expected_notifications mirrors the per-candidate mention + set (candidate_name + mention_emails/names) for the Slack reward component. + +Observable result kept ABSENT (Rule 3): + google_calendar.events contains NO 'Debrief - ' events at injection time; + slack '#interviews' channel starts with an EMPTY message list. + +Datetimes: timezone-NAIVE local ISO WITHOUT trailing Z, e.g. '2026-06-08T13:00:00'. +Both the seeded busy blocks and the precomputed debrief slots use this format so +they read as wall-clock local time (matches how the calendar mock renders). +""" +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}') + + +# ================================================================== +# Helpers +# ================================================================== +def iso_local(d: dt.datetime) -> str: + """Naive local ISO, no trailing Z (e.g. '2026-06-08T13:00:00').""" + return d.strftime('%Y-%m-%dT%H:%M:%S') + + +def overlaps(a_start, a_end, b_start, b_end): + return a_start < b_end and a_end > b_start + + +def gh_user(uid, first, last, role, title, dept): + return { + 'id': uid, 'firstName': first, 'lastName': last, + 'name': f'{first} {last}', + 'email': f'{first.lower()}.{last.lower()}@company.com', + 'role': role, 'avatarUrl': None, 'department': dept, 'title': title, + } + + +def gh_candidate(cid, first, last, company, title): + return { + 'id': cid, 'firstName': first, 'lastName': last, + 'name': f'{first} {last}', + 'email': f'{first.lower()}.{last.lower()}@gmail.com', + 'phone': '+1-415-555-0' + cid.split('-')[-1].rjust(3, '0'), + 'location': 'San Francisco, CA', + 'currentCompany': company, 'currentTitle': title, + 'resumeUrl': None, 'linkedinUrl': None, 'source': 'applied', + 'referrerId': None, 'tags': ['frontend'], + 'createdAt': '2026-05-01T10:00:00Z', 'updatedAt': '2026-06-05T10:00:00Z', + } + + +def gh_application(app_id, cand_id, stage_id, action_required, days): + return { + 'id': app_id, 'candidateId': cand_id, 'jobId': 'job-1', + 'currentStageId': stage_id, 'status': 'active', + 'appliedAt': '2026-05-01T10:00:00Z', 'rejectedAt': None, + 'rejectionReason': None, 'hiredAt': None, + 'lastActivityAt': '2026-06-05T10:00:00Z', 'source': 'applied', + 'creditedTo': None, 'recruiterId': 'user-1', 'coordinatorId': 'user-7', + 'actionRequired': action_required, 'daysInCurrentStage': days, + } + + +def gh_scorecard(sc_id, app_id, interviewer_id, stage_id, rec, submitted=True): + return { + 'id': sc_id, 'applicationId': app_id, 'interviewerId': interviewer_id, + 'stageId': stage_id, + 'overallRecommendation': rec if submitted else None, + 'attributes': [ + {'name': 'Technical', 'rating': 3, 'note': 'Solid fundamentals.'}, + {'name': 'Communication', 'rating': 3, 'note': 'Clear and concise.'}, + ] if submitted else [], + 'submittedAt': '2026-06-05T18:00:00Z' if submitted else None, + 'createdAt': '2026-06-04T09:00:00Z', + 'notes': 'Strong onsite performance.' if submitted else '', + } + + +def gh_interview(int_id, app_id, stage_id, interviewer_ids, status, scheduled_at): + return { + 'id': int_id, 'applicationId': app_id, 'stageId': stage_id, + 'interviewerIds': interviewer_ids, 'scheduledAt': scheduled_at, + 'duration': 60, 'location': 'Onsite - San Francisco HQ', + 'status': status, 'meetingUrl': '', + 'notes': 'Onsite panel session.', + } + + +# ================================================================== +# Users (recruiter, hiring manager, coordinator + interviewers) +# ================================================================== +GH_USERS = [ + gh_user('user-1', 'Jules', 'Park', 'recruiter', 'Senior Recruiter', 'People Operations'), + gh_user('user-2', 'Sarah', 'Chen', 'recruiter', 'Recruiter', 'People Operations'), + gh_user('user-3', 'David', 'Kim', 'hiring_manager', 'VP of Engineering', 'Engineering'), + gh_user('user-5', 'Marcus', 'Johnson', 'interviewer', 'Staff Engineer', 'Engineering'), + gh_user('user-6', 'Priya', 'Patel', 'interviewer', 'Senior Engineer', 'Engineering'), + gh_user('user-7', 'James', 'Wright', 'coordinator', 'Recruiting Coordinator', 'People Operations'), + gh_user('user-9', 'Nina', 'Alvarez', 'interviewer', 'Senior Frontend Engineer', 'Engineering'), + gh_user('user-10', 'Tom', 'Becker', 'interviewer', 'Engineering Manager', 'Engineering'), + gh_user('user-11', 'Grace', 'Liu', 'interviewer', 'Staff Frontend Engineer', 'Engineering'), + gh_user('user-12', 'Omar', 'Haddad', 'interviewer', 'Senior Engineer', 'Engineering'), +] +USER_EMAIL = {u['id']: u['email'] for u in GH_USERS} + +# ================================================================== +# Job + stages (Senior Frontend Engineer; onsite = stage-job-1-6) +# ================================================================== +ONSITE_STAGE = 'stage-job-1-6' +TECH_STAGE = 'stage-job-1-4' +PHONE_STAGE = 'stage-job-1-2' + +GH_JOB_1 = { + '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': 'Senior frontend engineer building our design-system and web app.', + 'requirements': ['5+ years frontend', 'React/TypeScript', 'Design systems'], + 'stages': [f'stage-job-1-{i}' for i in range(1, 9)], + 'candidateCount': 8, + 'createdAt': '2026-04-01T09:00:00Z', 'updatedAt': '2026-06-05T09:00:00Z', +} + +GH_JOB_STAGES = [ + {'id': 'stage-job-1-1', 'jobId': 'job-1', 'name': 'Application Review', + 'orderIndex': 0, 'stageType': 'application_review'}, + {'id': 'stage-job-1-2', 'jobId': 'job-1', 'name': 'Recruiter Phone Screen', + 'orderIndex': 1, 'stageType': 'phone_screen'}, + {'id': 'stage-job-1-3', 'jobId': 'job-1', 'name': 'Hiring Manager Screen', + 'orderIndex': 2, 'stageType': 'phone_screen'}, + {'id': 'stage-job-1-4', 'jobId': 'job-1', 'name': 'Technical Interview', + 'orderIndex': 3, 'stageType': 'interview'}, + {'id': 'stage-job-1-5', 'jobId': 'job-1', 'name': 'Take Home', + 'orderIndex': 4, 'stageType': 'take_home'}, + {'id': 'stage-job-1-6', 'jobId': 'job-1', 'name': 'Onsite Interview', + 'orderIndex': 5, 'stageType': 'onsite'}, + {'id': 'stage-job-1-7', 'jobId': 'job-1', 'name': 'Offer', + 'orderIndex': 6, 'stageType': 'offer'}, + {'id': 'stage-job-1-8', 'jobId': 'job-1', 'name': 'Hired', + 'orderIndex': 7, 'stageType': 'hired'}, +] + +# ================================================================== +# Candidates (names chosen so alphabetical == candidate processing order) +# Ready onsite : Alex Morgan, Brianna Lewis, Carlos Mendes, Dana Whitfield +# Not-ready : Ethan Brooks, Fatima Noor (open 'scheduled' onsite interview) +# Non-onsite : Grace Park (Technical), Henry Tanaka (Phone Screen) +# ================================================================== +GH_CANDIDATES = [ + gh_candidate('cand-1', 'Alex', 'Morgan', 'Figma', 'Frontend Engineer'), + gh_candidate('cand-2', 'Brianna', 'Lewis', 'Stripe', 'Software Engineer'), + gh_candidate('cand-3', 'Carlos', 'Mendes', 'Airbnb', 'Senior Engineer'), + gh_candidate('cand-4', 'Dana', 'Whitfield', 'Notion', 'Frontend Engineer'), + gh_candidate('cand-5', 'Ethan', 'Brooks', 'Datadog', 'Software Engineer'), + gh_candidate('cand-6', 'Fatima', 'Noor', 'Shopify', 'Frontend Engineer'), + gh_candidate('cand-7', 'Grace', 'Park', 'Coinbase', 'Engineer'), + gh_candidate('cand-8', 'Henry', 'Tanaka', 'Twilio', 'Engineer'), +] +CAND_NAME = {c['id']: c['name'] for c in GH_CANDIDATES} + +# ================================================================== +# Applications +# ================================================================== +GH_APPLICATIONS = [ + # 4 debrief-READY onsite apps + gh_application('app-1', 'cand-1', ONSITE_STAGE, 'needs_decision', 3), + gh_application('app-2', 'cand-2', ONSITE_STAGE, 'needs_decision', 4), + gh_application('app-3', 'cand-3', ONSITE_STAGE, 'needs_decision', 2), + gh_application('app-4', 'cand-4', ONSITE_STAGE, 'needs_decision', 5), + # 2 NOT-ready onsite apps (still have a 'scheduled' onsite interview) + gh_application('app-5', 'cand-5', ONSITE_STAGE, 'needs_scheduling', 1), + gh_application('app-6', 'cand-6', ONSITE_STAGE, 'needs_scheduling', 1), + # 2 non-onsite distractor apps + gh_application('app-7', 'cand-7', TECH_STAGE, 'needs_scorecard', 2), + gh_application('app-8', 'cand-8', PHONE_STAGE, 'needs_scheduling', 3), +] +APP_BY_ID = {a['id']: a for a in GH_APPLICATIONS} + +# ================================================================== +# Scorecards — SUBMITTED scorecards define each app's interviewer/guest set. +# A pending scorecard (overallRecommendation == null) MUST be excluded. +# ================================================================== +GH_SCORECARDS = [ + # app-1 Alex Morgan : David Kim, Marcus Johnson, Priya Patel + gh_scorecard('sc-1', 'app-1', 'user-3', ONSITE_STAGE, 'yes'), + gh_scorecard('sc-2', 'app-1', 'user-5', ONSITE_STAGE, 'strong_yes'), + gh_scorecard('sc-3', 'app-1', 'user-6', ONSITE_STAGE, 'yes'), + # app-2 Brianna Lewis : Marcus Johnson, Nina Alvarez (Tom Becker pending -> excluded) + gh_scorecard('sc-4', 'app-2', 'user-5', ONSITE_STAGE, 'yes'), + gh_scorecard('sc-5', 'app-2', 'user-9', ONSITE_STAGE, 'strong_yes'), + gh_scorecard('sc-6', 'app-2', 'user-10', ONSITE_STAGE, None, submitted=False), + # app-3 Carlos Mendes : Priya Patel, Tom Becker, Grace Liu + gh_scorecard('sc-7', 'app-3', 'user-6', ONSITE_STAGE, 'yes'), + gh_scorecard('sc-8', 'app-3', 'user-10', ONSITE_STAGE, 'no_opinion'), + gh_scorecard('sc-9', 'app-3', 'user-11', ONSITE_STAGE, 'strong_yes'), + # app-4 Dana Whitfield : David Kim, Omar Haddad + gh_scorecard('sc-10', 'app-4', 'user-3', ONSITE_STAGE, 'yes'), + gh_scorecard('sc-11', 'app-4', 'user-12', ONSITE_STAGE, 'yes'), + # not-ready apps also carry (partial) submitted scorecards — irrelevant: not ready + gh_scorecard('sc-12', 'app-5', 'user-5', ONSITE_STAGE, 'yes'), + gh_scorecard('sc-13', 'app-6', 'user-6', ONSITE_STAGE, 'yes'), + # non-onsite distractor scorecards (technical stage) — must never be scheduled + gh_scorecard('sc-14', 'app-7', 'user-11', TECH_STAGE, 'yes'), +] + +# ================================================================== +# Interviews +# Ready apps : ALL onsite interviews 'completed'. +# Not-ready : >=1 onsite interview still 'scheduled'. +# Distractor : non-onsite interview. +# ================================================================== +GH_INTERVIEWS = [ + # --- ready apps: every onsite interview completed --- + gh_interview('int-1', 'app-1', ONSITE_STAGE, ['user-3', 'user-5'], 'completed', '2026-06-03T14:00:00'), + gh_interview('int-2', 'app-1', ONSITE_STAGE, ['user-6'], 'completed', '2026-06-03T15:30:00'), + gh_interview('int-3', 'app-2', ONSITE_STAGE, ['user-5', 'user-9'], 'completed', '2026-06-04T14:00:00'), + gh_interview('int-4', 'app-3', ONSITE_STAGE, ['user-6', 'user-11'], 'completed', '2026-06-04T13:00:00'), + gh_interview('int-5', 'app-3', ONSITE_STAGE, ['user-10'], 'completed', '2026-06-04T15:00:00'), + gh_interview('int-6', 'app-4', ONSITE_STAGE, ['user-3', 'user-12'], 'completed', '2026-06-05T14:00:00'), + # --- not-ready apps: at least one onsite interview still scheduled --- + gh_interview('int-7', 'app-5', ONSITE_STAGE, ['user-5'], 'completed', '2026-06-05T13:00:00'), + gh_interview('int-8', 'app-5', ONSITE_STAGE, ['user-6'], 'scheduled', '2026-06-10T15:00:00'), + gh_interview('int-9', 'app-6', ONSITE_STAGE, ['user-6', 'user-11'], 'scheduled', '2026-06-11T14:00:00'), + # --- distractor: non-onsite interview --- + gh_interview('int-10', 'app-7', TECH_STAGE, ['user-11'], 'completed', '2026-06-02T11:00:00'), +] + +# ================================================================== +# Resolve guest_emails per app from SUBMITTED scorecards (rec != null) +# ================================================================== +guests_by_app = {} +for sc in GH_SCORECARDS: + if sc['submittedAt'] is not None and sc['overallRecommendation'] is not None: + email = USER_EMAIL[sc['interviewerId']] + guests_by_app.setdefault(sc['applicationId'], set()).add(email) +guests_by_app = {aid: sorted(emails) for aid, emails in guests_by_app.items()} + +# ================================================================== +# Calendar busy blocks (timezone-naive local ISO, no Z) in the +# Jun 8-11 13:00-17:00 window. With the ONE-debrief-per-day rule the +# uniqueness comes from the day assignment; within each day these blocks +# push the earliest free :00/:30 slot off 13:00 so the slot choice is +# still non-trivial (and differs day to day). +# Mon Jun 8 -> earliest free 14:00 (13:00-14:00 blocked) +# Tue Jun 9 -> earliest free 14:30 (13:00-14:30 blocked) +# Wed Jun 10 -> earliest free 14:00 (13:00-14:00 blocked) +# Thu Jun 11 -> earliest free 13:00 (no in-window block) +# ================================================================== +BUSY_BLOCKS = [ + # Mon Jun 8 — leaves 14:00 as the earliest free in-window :00/:30 slot + ('Sprint Planning', dt.datetime(2026, 6, 8, 13, 0), dt.datetime(2026, 6, 8, 14, 0)), + ('Panel Interview', dt.datetime(2026, 6, 8, 14, 30), dt.datetime(2026, 6, 8, 15, 30)), + ('Design Review', dt.datetime(2026, 6, 8, 16, 0), dt.datetime(2026, 6, 8, 17, 0)), + # Tue Jun 9 — blocks 13:00-14:30 -> earliest free 14:30 + ('1:1 with Priya', dt.datetime(2026, 6, 9, 13, 0), dt.datetime(2026, 6, 9, 13, 30)), + ('Team Sync', dt.datetime(2026, 6, 9, 13, 30), dt.datetime(2026, 6, 9, 14, 30)), + # Wed Jun 10 — blocks 13:00-14:00 -> earliest free 14:00 + ('Sprint Demo', dt.datetime(2026, 6, 10, 13, 0), dt.datetime(2026, 6, 10, 14, 0)), + # Thu Jun 11 — no in-window busy block (earliest free 13:00) +] +BUSY_INTERVALS = [(s, e) for (_, s, e) in BUSY_BLOCKS] + +# ================================================================== +# Precompute the debrief slots under the ONE-debrief-per-day rule. +# Candidate order (alphabetical) -> candidate k goes on WINDOW_DAYS[k]; +# within that day take the earliest conflict-free :00/:30 slot. +# Window: weekdays Jun 8-11 2026, starts 13:00..16:30 (:00/:30 aligned). +# ================================================================== +WINDOW_DAYS = [dt.date(2026, 6, d) for d in (8, 9, 10, 11)] +assert all(d.weekday() < 5 for d in WINDOW_DAYS), 'window must be weekdays only' + + +def day_slots(day): + slots = [] + for hour in range(13, 17): # 13,14,15,16 + for minute in (0, 30): # :00, :30 -> last start 16:30 (ends 17:00) + start = dt.datetime(day.year, day.month, day.day, hour, minute) + slots.append((start, start + dt.timedelta(minutes=30))) + return slots + +# Ready onsite apps == apps whose currentStage is onsite AND every onsite +# interview is 'completed' (>=1 onsite interview present). +onsite_interviews_by_app = {} +for iv in GH_INTERVIEWS: + if iv['stageId'] == ONSITE_STAGE: + onsite_interviews_by_app.setdefault(iv['applicationId'], []).append(iv) + +ready_app_ids = [] +notready_onsite_ids = [] +for a in GH_APPLICATIONS: + if a['currentStageId'] != ONSITE_STAGE: + continue + ivs = onsite_interviews_by_app.get(a['id'], []) + if ivs and all(iv['status'] == 'completed' for iv in ivs): + ready_app_ids.append(a['id']) + else: + notready_onsite_ids.append(a['id']) + +# Candidate order = alphabetical by candidate name. +ready_app_ids.sort(key=lambda aid: CAND_NAME[APP_BY_ID[aid]['candidateId']]) + +assert len(ready_app_ids) <= len(WINDOW_DAYS), ( + f'{len(ready_app_ids)} ready apps but only {len(WINDOW_DAYS)} days in window' +) + +assigned = [] # list of (start, end) already placed this task +debrief_by_app = {} # app_id -> _debrief dict +# ONE debrief per day: candidate k (candidate order) -> WINDOW_DAYS[k]. +for k, aid in enumerate(ready_app_ids): + day = WINDOW_DAYS[k] + chosen = None + for (s, e) in day_slots(day): + if any(overlaps(s, e, bs, be) for (bs, be) in BUSY_INTERVALS): + continue + if any(overlaps(s, e, as_, ae_) for (as_, ae_) in assigned): + continue + chosen = (s, e) + break + assert chosen is not None, f'no conflict-free slot for {aid} on {day}' + assigned.append(chosen) + cand_name = CAND_NAME[APP_BY_ID[aid]['candidateId']] + debrief_by_app[aid] = { + 'candidate_name': cand_name, + 'guest_emails': guests_by_app[aid], + 'slot_start': iso_local(chosen[0]), + 'slot_end': iso_local(chosen[1]), + } + +# ------------------------------------------------------------------ +# Assertions on the precomputed assignment. +# ------------------------------------------------------------------ +assert len(ready_app_ids) == 4, f'expected 4 ready apps, got {len(ready_app_ids)}' +assert len(notready_onsite_ids) == 2, f'expected 2 not-ready onsite apps, got {len(notready_onsite_ids)}' +for aid in ready_app_ids: + assert guests_by_app.get(aid), f'{aid} has no submitted-scorecard guests' + +# Exactly one debrief per day (the constraint that makes the answer unique). +assigned_days = [s.date() for (s, _) in assigned] +assert len(assigned_days) == len(set(assigned_days)), 'two debriefs landed on the same day' + +for (s, e) in assigned: + assert s.date() in WINDOW_DAYS, f'slot {s} outside window days' + assert 13 <= s.hour <= 16 and s.minute in (0, 30), f'slot {s} not :00/:30 aligned in 13-17' + assert e == s + dt.timedelta(minutes=30), 'slot not 30 minutes' + assert e.hour < 17 or (e.hour == 17 and e.minute == 0), f'slot {e} ends after 17:00' + for (bs, be) in BUSY_INTERVALS: + assert not overlaps(s, e, bs, be), f'slot {s}-{e} overlaps busy {bs}-{be}' +for i in range(len(assigned)): + for j in range(i + 1, len(assigned)): + assert not overlaps(*assigned[i], *assigned[j]), 'two debrief slots overlap' + +print('Precomputed debrief assignment (candidate order):') +for aid in ready_app_ids: + d = debrief_by_app[aid] + print(f" {aid} {d['candidate_name']:16s} {d['slot_start']} -> {d['slot_end']} guests={d['guest_emails']}") + +# ================================================================== +# Embed _debrief on each application: +# ready onsite -> dict ; not-ready onsite -> None ; non-onsite -> absent +# ================================================================== +for a in GH_APPLICATIONS: + if a['id'] in debrief_by_app: + a['_debrief'] = debrief_by_app[a['id']] + elif a['id'] in notready_onsite_ids: + a['_debrief'] = None + # non-onsite distractor apps: leave _debrief absent + +# ================================================================== +# Greenhouse state (all required top-level keys present) +# ================================================================== +GREENHOUSE_STATE = { + 'currentUser': GH_USERS[0], # Jules Park, recruiter + 'users': GH_USERS, + 'departments': [ + {'id': 'dept-1', 'name': 'Engineering', 'parentId': None}, + {'id': 'dept-6', 'name': 'People Operations', 'parentId': None}, + ], + 'offices': [ + {'id': 'office-1', 'name': 'San Francisco HQ', 'location': 'San Francisco, CA'}, + {'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': 'Culture mismatch'}, + ], + 'jobs': [GH_JOB_1], + 'jobStages': GH_JOB_STAGES, + 'candidates': GH_CANDIDATES, + 'applications': GH_APPLICATIONS, + 'scorecards': GH_SCORECARDS, + 'interviews': GH_INTERVIEWS, + 'offers': [], + 'notes': [ + {'id': 'note-1', 'candidateId': 'cand-1', 'authorId': 'user-1', + 'body': 'Great onsite — debrief pending.', 'visibility': 'public', + 'isPinned': False, 'createdAt': '2026-06-05T18:30:00Z', + 'updatedAt': '2026-06-05T18:30:00Z'}, + ], + 'activityFeed': [ + {'id': 'act-1', 'candidateId': 'cand-1', 'applicationId': 'app-1', + 'type': 'scorecard_submitted', 'actorId': 'user-5', + 'description': 'Marcus Johnson submitted a scorecard.', + 'metadata': {}, 'createdAt': '2026-06-05T18:00:00Z'}, + ], + 'notifications': [ + {'id': 'notif-1', 'type': 'scorecard_due', + 'title': 'Debrief ready', 'message': 'Onsite scorecards are in for 4 candidates.', + 'isRead': False, 'link': '/jobs/job-1', 'createdAt': '2026-06-08T08:00:00Z'}, + ], + 'ui': {'searchQuery': '', 'activeJobId': 'job-1', 'activeCandidateId': None, + 'modals': {}}, +} + +# ================================================================== +# Google Calendar state — busy blocks + out-of-window decoys. +# NO 'Debrief - ' events present (Rule 3: observable result absent). +# ================================================================== +calendar_events = [] +for i, (title, s, e) in enumerate(BUSY_BLOCKS, start=1): + calendar_events.append({ + 'id': f'evt_busy_{i}', 'calendarId': 'c2', 'title': title, + 'start': iso_local(s), 'end': iso_local(e), + 'allDay': False, 'location': 'HQ', 'description': '', + 'guests': [], 'color': '#33B679', 'recurring': 'none', + 'reminders': [], 'meetLink': '', 'status': 'confirmed', + }) +# Out-of-window decoys (never collide with 13:00-17:00 debrief slots). +calendar_events.append({ + 'id': 'evt_standup_mon', 'calendarId': 'c2', 'title': 'Morning Standup', + 'start': '2026-06-08T09:30:00', 'end': '2026-06-08T09:45:00', + 'allDay': False, 'location': 'Zoom', 'description': '', + 'guests': [], 'color': '#33B679', 'recurring': 'none', + 'reminders': [], 'meetLink': '', 'status': 'confirmed', +}) +calendar_events.append({ + 'id': 'evt_allday_fri', 'calendarId': 'c1', 'title': 'WFH Day', + 'start': '2026-06-12T00:00:00', 'end': '2026-06-13T00:00:00', + 'allDay': True, 'location': '', 'description': '', + 'guests': [], 'color': '#039BE5', 'recurring': 'none', + 'reminders': [], 'meetLink': '', 'status': 'confirmed', +}) + +assert not any(ev['title'].startswith('Debrief - ') for ev in calendar_events), \ + 'seeded calendar must not contain any Debrief - event' + +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': '#039BE5', + 'visible': True, 'userId': 'u1', 'isDefault': True}, + {'id': 'c2', 'name': 'Work', 'color': '#33B679', + 'visible': True, 'userId': 'u1', 'isDefault': False}, + ], + 'events': calendar_events, + 'view': 'week', + 'currentDate': '2026-06-08T00:00:00', + 'sidebarOpen': True, + 'settings': { + 'weekStart': 0, 'defaultDuration': 60, 'defaultView': 'week', + 'defaultReminder': {'type': 'popup', 'minutes': 10}, + 'timeFormat': '12h', 'showWeekNumbers': False, + 'showDeclinedEvents': False, + }, +} + + +# ================================================================== +# Slack — notify each candidate's interviewers of the scheduled debrief. +# After scheduling, the agent posts ONE message per ready candidate in the +# '#interviews' channel that (a) names the candidate and (b) @mentions EXACTLY +# that candidate's submitting interviewers (the same set as the calendar guests). +# +# Slack users mirror the Greenhouse interviewers (same email + display name) so +# the agent can resolve "who interviewed" to a Slack @mention. currentUser is +# Jules Park (the recruiter). The '#interviews' channel starts EMPTY (Rule 3). +# ================================================================== +EMAIL_NAME = {u['email']: u['name'] for u in GH_USERS} + +slack_users = [ + {'userId': u['id'], 'fullName': u['name'], + 'displayName': u['firstName'], 'email': u['email'], + 'avatar': f"https://picsum.photos/200/200?random={u['id']}", + 'title': u['title'], 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'} + for u in GH_USERS +] +slack_current_user = next(su for su in slack_users if su['userId'] == 'user-1') # Jules Park + +# Per-candidate expected Slack notification (answer key), in candidate order. +slack_expected_notifications = [] +for aid in ready_app_ids: + d = debrief_by_app[aid] + emails = d['guest_emails'] + slack_expected_notifications.append({ + 'candidate_name': d['candidate_name'], + 'mention_emails': emails, + 'mention_names': [EMAIL_NAME.get(e, e) for e in emails], + 'slot_start': d['slot_start'], + }) + +SLACK_STATE = { + 'currentUser': slack_current_user, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Hiring', 'icon': ''}, + 'users': slack_users, + 'channels': [ + {'channelId': 'general', 'name': 'general', + 'description': 'Company-wide announcements', 'topic': 'Welcome!', + 'isPrivate': False, 'isStarred': True, + 'members': [u['userId'] for u in slack_users], + 'createdBy': 'user-1', 'createdAt': '2026-05-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'interviews', 'name': 'interviews', + 'description': 'Interview coordination and debrief notifications', + 'topic': 'Ping interviewers when a debrief is booked', + 'isPrivate': False, 'isStarred': False, + 'members': [u['userId'] for u in slack_users], + 'createdBy': 'user-1', 'createdAt': '2026-05-20T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user-3', + 'content': 'Reminder: Q3 hiring goals are posted on the wiki.', + 'timestamp': '2026-06-05T16:00:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + # '#interviews' MUST start EMPTY (Rule 3): the debrief notifications are + # the gradable Slack artefact and must be ABSENT at injection. + 'interviews': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', + 'displayDensity': 'comfortable', 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + '_task_adapter': { + 'task_id': '975bd1cb-c4e3-4adf-a166-3857433b3088', + 'variant': 'eval', + 'notify_channel': 'interviews', + 'expected_notifications': slack_expected_notifications, + }, +} + +# Rule 3 guard: no debrief notification may exist in '#interviews' at injection. +assert SLACK_STATE['messages']['interviews'] == [], \ + "'#interviews' must start empty (notifications absent at injection)" + + +# ================================================================== +# Inject (one sid, action:set) -> verify -> launch GUI +# ================================================================== +APP_STATES = [ + ('http://28.7.184.198:8146', GREENHOUSE_STATE), # greenhouse_mock + ('http://28.7.184.198:8141', CALENDAR_STATE), # google_calendar_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/recruit_onsite_stage_008__long/reward.py b/recruit_onsite_stage_008__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..057ed114def35667b5e9d6f9feac0e7e962e9081 --- /dev/null +++ b/recruit_onsite_stage_008__long/reward.py @@ -0,0 +1,694 @@ +""" +Reward Script: T09 — Greenhouse onsite debrief scheduling +Task ID: recruit_onsite_stage_008__long +Mocks: greenhouse_mock (8146), google_calendar_mock (8141), slack_mock (8178) +Scoring: + 0.50 frac(ready apps) -> 'Debrief - ' event exists at slot_start/slot_end + (naive-local normalized, 30-min), matched by candidate_name in the title + 0.20 frac(ready apps) -> matched debrief event guests is a SUPERSET of guest_emails + (recall-only: every required interviewer is invited; extra guests like + the organizer (self) or the candidate do NOT cost points) + 0.10 no debrief leaked for not-ready (_debrief null) / non-onsite (_debrief absent) + (1.0 if none, scaled down by fraction leaked) + 0.10 no-overlap invariant: among ALL 'Debrief - ' events + seeded busy events, + no two overlap (1.0 else 0.0). Gated: requires at least one debrief + event so a do-nothing run cannot earn this credit by default. + 0.10 frac(ready apps) -> one '#interviews' Slack message per candidate that + names the candidate and @mentions EXACTLY that candidate's interviewers +Answer key: greenhouse.initial_state.applications[*]._debrief (inline hidden field) + + slack.initial_state._task_adapter.expected_notifications. +""" +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', '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 [], + # Preserve @mentions (the debrief-notification answer key checks + # these) and any uploaded attachments through the merge. + 'mentions': m.get('mentions') if isinstance(m.get('mentions'), list) else [], + 'attachments': m.get('attachments') if isinstance(m.get('attachments'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward === +def _to_naive(t): + """Parse an ISO datetime that may carry a trailing 'Z', '.000Z', or an + offset, and return it as a timezone-NAIVE datetime (wall-clock local). + Normalizes BOTH the seeded naive slots and the agent's created events to a + common naive representation before equality.""" + parsed = _parse(t) + if parsed is None: + return None + if parsed.tzinfo is not None: + parsed = parsed.replace(tzinfo=None) + return parsed + + +def _debrief_events(events): + """Current-state events whose normalized title starts with 'debrief - '.""" + out = [] + for ev in events or []: + if not isinstance(ev, dict): + continue + if norm(ev.get('title')).startswith('debrief - '): + out.append(ev) + return out + + +def _candidate_name_map(gh_state): + out = {} + for c in (gh_state or {}).get('candidates', []) or []: + if not isinstance(c, dict) or not c.get('id'): + continue + out[c['id']] = c.get('name') or f"{c.get('firstName', '')} {c.get('lastName', '')}".strip() + return out + + +def reward(go): + gh = go('greenhouse') + gh_initial = gh.get('initial_state') or {} + + cand_name = _candidate_name_map(gh_initial) + apps_i = gh_initial.get('applications', []) or [] + + # Ready apps = applications whose _debrief is a non-null dict (answer key). + # Forbidden names = not-ready (_debrief explicit null) + non-onsite (_debrief absent). + ready = [] + forbidden_names = [] + for a in apps_i: + if not isinstance(a, dict): + continue + deb = a.get('_debrief') + if isinstance(deb, dict): + ready.append(a) + else: + # explicit None (not-ready onsite) or absent key (non-onsite distractor) + nm = cand_name.get(a.get('candidateId')) or '' + if nm: + forbidden_names.append(nm) + n = len(ready) + + # Google Calendar: agent's created events live in current_state.events. + cal = go('google_calendar') + cal_initial = cal.get('initial_state') or {} + cal_current = cal.get('current_state') or {} + init_events = cal_initial.get('events', []) or [] + cur_events = cal_current.get('events', []) or [] + + debrief_events = _debrief_events(cur_events) + deb_by_title = {} + for ev in debrief_events: + deb_by_title.setdefault(norm(ev.get('title')), []).append(ev) + + # --- 0.50: correct slot (start==slot_start AND end==slot_end, naive-local) --- + # --- 0.20: matched debrief event guests is a SUPERSET of guest_emails --- + # Recall-only check: every required interviewer must be invited; extra + # guests (the organizer / the candidate / anyone else) do NOT cost points. + # We still count self-invites for the DEBUG line so the trace shows whether + # the agent invited the organizer, but it does not affect the score. + organizer_email = norm((cal_initial.get('user') or {}).get('email')) + self_invited = 0 + slot_ok = 0 + guest_ok = 0 + for a in ready: + d = a['_debrief'] + cname = d.get('candidate_name') or cand_name.get(a.get('candidateId')) or '' + want_title = norm('Debrief - ' + cname) + title_matches = deb_by_title.get(want_title, []) + + want_start = _to_naive(d.get('slot_start')) + want_end = _to_naive(d.get('slot_end')) + + matched_ev = None + for ev in title_matches: + if _to_naive(ev.get('start')) == want_start and _to_naive(ev.get('end')) == want_end: + matched_ev = ev + break + if matched_ev is not None and want_start is not None and want_end is not None: + slot_ok += 1 + + # Guest check on the matched debrief event (prefer slot-matched, else first + # title match). Exact set semantics over normalized emails -> a self-invite + # (organizer) or a missing/extra guest fails this candidate's guest credit. + guest_src = matched_ev if matched_ev is not None else (title_matches[0] if title_matches else None) + if guest_src is not None: + want_guests = {norm(g) for g in (d.get('guest_emails') or [])} + got_guests = {norm(g) for g in (guest_src.get('guests') or [])} + if organizer_email and organizer_email in got_guests: + self_invited += 1 + # Recall-only: every required interviewer must be invited; extra + # guests (organizer self-invite, the candidate, anyone else) are OK. + if want_guests and want_guests.issubset(got_guests): + guest_ok += 1 + + s_slot = 0.50 * frac(slot_ok, n) + s_guest = 0.20 * frac(guest_ok, n) + + # --- 0.10: no debrief leaked for not-ready / non-onsite candidates --- + leaked = 0 + for nm in forbidden_names: + if norm('Debrief - ' + nm) in deb_by_title: + leaked += 1 + nf = len(forbidden_names) + # Only award leak-avoidance credit once the agent has actually created + # debrief events; a do-nothing state must not earn this guard credit for + # free (otherwise the injected/empty state scores > 0.15). + if debrief_events: + s_leak = 0.10 * (1.0 - frac(leaked, nf)) # frac==0 when nf==0 -> full credit + else: + s_leak = 0.0 + + # --- 0.10: no-overlap invariant across ALL debrief events + seeded busy events --- + # Proof-of-work gate (mirrors s_leak): the agent must have created at + # least one debrief event before this 0.10 invariant credit is awarded. + # Otherwise a do-nothing run would earn 0.10 just because the seeded busy + # events are non-overlapping by setup design. + seeded_busy = [e for e in init_events + if isinstance(e, dict) and not norm(e.get('title')).startswith('debrief - ')] + combined = list(debrief_events) + seeded_busy + overlaps = _overlaps(combined) + s_overlap = 0.10 * (1.0 if (overlaps == 0 and debrief_events) else 0.0) + + # --- 0.10: Slack debrief notifications -- one '#interviews' message per ready + # candidate that @mentions EXACTLY that candidate's submitting interviewers. --- + # NOTE: the Slack mock only creates a structured mention object when the user + # picks a name from the @ autocomplete; a hand-typed '@Name' stays plain text + # with an empty mentions[]. So we grade by TEXT: a person is "mentioned" if + # their display name appears in the message body (or in mentions[]). "Exactly" + # is enforced by checking the FULL Slack user roster -- the mentioned-user set + # recovered from the body must equal the candidate's interviewer set (so a + # self-mention of Jules Park or any extra interviewer fails the candidate). + slack = go('slack') + slack_init = slack.get('initial_state') or {} + slack_cur = slack.get('current_state') or {} + s_adapter = slack_init.get('_task_adapter') if isinstance(slack_init.get('_task_adapter'), dict) else {} + notify_channel = s_adapter.get('notify_channel') or 'interviews' + expected_notifs = s_adapter.get('expected_notifications') if isinstance(s_adapter.get('expected_notifications'), list) else [] + + # All Slack user display/full names (used to recover who a message mentions). + all_user_names = [] + for u in (slack_init.get('users') or []): + if isinstance(u, dict): + nm = u.get('fullName') or u.get('displayName') + if nm: + all_user_names.append(nm) + + # Messages newly present in the notify channel (current minus initial by id). + init_msgs = _slack_channel_messages(slack_init, notify_channel) + init_ids = {m.get('messageId') or m.get('id') for m in init_msgs if isinstance(m, dict)} + cur_msgs = _slack_channel_messages(slack_cur, notify_channel) + new_msgs = [m for m in cur_msgs if isinstance(m, dict) and (m.get('messageId') or m.get('id')) not in init_ids] + + def _mentioned_user_names(msg): + """Set of Slack-user full names this message mentions, recovered from BOTH + the structured mentions[] (picker) AND the raw body text (hand-typed @Name). + A name counts if it appears anywhere in the body or the mentions array.""" + text = norm(_slack_msg_text(msg)) + struct = {norm(mm.get('displayName')) for mm in (msg.get('mentions') or []) if isinstance(mm, dict) and mm.get('displayName')} + found = set() + for nm in all_user_names: + n = norm(nm) + if n and (n in text or n in struct): + found.add(n) + return found + + notif_ok = 0 + n_notif = len(expected_notifs) + for en in expected_notifs: + cname = norm(en.get('candidate_name')) + want_set = {norm(x) for x in (en.get('mention_names') or [])} + for m in new_msgs: + if cname and cname not in norm(_slack_msg_text(m)): + continue + # Exactly the candidate's interviewers are mentioned (no extra, none missing). + if _mentioned_user_names(m) == want_set: + notif_ok += 1 + break + s_slack = 0.10 * frac(notif_ok, n_notif) if n_notif else 0.0 + + score = s_slot + s_guest + s_leak + s_overlap + s_slack + + print( + 'DEBUG_T09 ' + f'n_ready={n} slot_ok={slot_ok}/{n} guest_ok={guest_ok}/{n} self_invited={self_invited} ' + f'debrief_events={len(debrief_events)} forbidden={nf} leaked={leaked} ' + f'seeded_busy={len(seeded_busy)} overlaps={overlaps} ' + f'slack_new_msgs={len(new_msgs)} notif_ok={notif_ok}/{n_notif} ' + f's_slot={round(s_slot, 4)} s_guest={round(s_guest, 4)} ' + f's_leak={round(s_leak, 4)} s_overlap={round(s_overlap, 4)} s_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/sdr_inbound_lead_006__long/_cua_gym_vm_bridge.sh b/sdr_inbound_lead_006__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/sdr_inbound_lead_006__long/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/sdr_inbound_lead_006__long/initial_setup.py b/sdr_inbound_lead_006__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7df27de03b838f4d5fe43bf466453ebe80e707 --- /dev/null +++ b/sdr_inbound_lead_006__long/initial_setup.py @@ -0,0 +1,914 @@ +""" +Initial Setup: Qualify & advance the inbound-lead pipeline +Task ID: sdr_inbound_lead_006__long +Mocks: salesforce_mock,gmail_mock,google_calendar_mock,slack_mock + +Single-path-TIERED task (like e01c3153): the sales manager works the overnight +inbound emails in Gmail. Each GENUINE inbound is a prospect asking about the +product; the manager must (a) tier-label the email, (b) set the matching +Salesforce Opportunity's Stage to the stage for that tier, (c) for HOT leads log +a follow-up Task on the opportunity AND book a Calendar discovery call with the +prospect as guest, then (d) post & pin a one-line pipeline summary to Slack +#sales. Non-inbound emails (newsletter, out-of-office, a resolved/closed thread) +are archived, not acted on. + +Ground-truth embedding style: INLINE hidden field `lead` on every gmail email + lead = {"kind": "inbound|noise|resolved", + "tier": "Hot|Warm|Cold" | None, + "account": "" | None, + "opportunity_id": "" | None, # None if no matching SF opp + "target_stage": "Value Proposition|Qualification|Prospecting" | None, + # HOT only: + "task_subject": "Discovery follow-up: " | None, + "event_title": "Discovery call - " | None, + "event_date": "" | None, + "guest_email": "" | None} +Only kind == "inbound" is a lead. The `tier` is PRECOMPUTED in Python from the +email body (budget/intent keywords, precedence Hot > Warm > Cold) and asserted +against the authored intent, so the visible text and the embedded key can never +disagree. reward.py reads `lead` from gmail initial_state. + +HIDDEN ACCESS POINTS the agent must DISCOVER (the whole point of this task): + - Gmail: the tier LABEL button is SELECTION-GATED — it only appears in the + toolbar after you tick an email's checkbox. The picker lists the + Hot/Warm/Cold labels seeded below. reward matches the label by NAME. + - Salesforce: the Opportunity STAGE is set on the opportunity's own detail + page (SalesPath), or via the select-row BulkActionBar "Change Status" + (C1/C5) — not from the list view directly. + - Salesforce: the follow-up TASK is created from the opportunity's Activity + Timeline -> "New Activity" -> "New Task" modal (the deepest SF control, + C5+C2). It appends to activities[] with relatedToId == the opportunity id. + - Calendar: the prospect email is typed into the buried "Add guests" field + (C3); the autocomplete only lists @example.com users, so the real prospect + email must be carried over from Gmail. + - Slack: the summary posted to #sales must be PINNED — pin lives behind the + per-message hover "..." (More actions) menu (C4, aux). + +Observable result kept ABSENT at injection (Rule 3): + - All emails start in folder 'inbox' and carry NO labels (labels: []). + - Each matching SF opportunity starts at a stage DIFFERENT from its target + (Prospecting/Qualification), so a change is always required. HOT opps are + NOT yet at Value Proposition. activities[] holds only decoys — none titled + 'Discovery follow-up:'. + - The calendar holds NO 'Discovery call -' events (only decoys). + - The Slack #sales channel starts EMPTY (no messages, no pinned messages). + Decoy channels carry watermark chatter. +""" +import datetime +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# --------------------------------------------------------------------------- +# Ground-truth derivation (PRECOMPUTED so embedded keys match the visible data) +# "Assume today is Monday, July 6, 2026." +# --------------------------------------------------------------------------- +TODAY = datetime.date(2026, 7, 6) +EVENT_DATE = (TODAY + datetime.timedelta(days=2)).isoformat() # today + 2 => 2026-07-08 + + +def fdate(days_ahead): + return (TODAY + datetime.timedelta(days=days_ahead)).isoformat() + + +# Tier keyword rule, applied in precedence order (Hot > Warm > Cold). +HOT_KEYWORDS = ('ready to buy', 'budget approved', 'sign this quarter') +WARM_KEYWORDS = ('evaluating', 'comparing', 'demo') + + +def classify_tier(body): + b = body.lower() + if any(k in b for k in HOT_KEYWORDS): + return 'Hot' + if any(k in b for k in WARM_KEYWORDS): + return 'Warm' + return 'Cold' + + +# Tier -> the SF Opportunity stage the agent must SET. +TIER_STAGE = { + 'Hot': 'Value Proposition', + 'Warm': 'Qualification', + 'Cold': 'Prospecting', +} + +# Salesforce stage -> default probability. +STAGE_PROB = { + 'Prospecting': 10, + 'Qualification': 25, + 'Needs Analysis': 35, + 'Value Proposition': 50, + 'Proposal': 65, + 'Negotiation': 80, + 'Closed Won': 100, + 'Closed Lost': 0, +} + +# --------------------------------------------------------------------------- +# Email specs — single source of truth for the scenario. For genuine inbound +# emails, `tier` is DERIVED from `body`; `expect_tier` asserts the authored body +# really yields the intended tier. `sf_initial` is the opportunity's stage AT +# INJECTION (always != TIER_STAGE[tier] so a change is required). opp_id=None +# means NO matching SF opportunity (agent labels it but makes no SF change). +# --------------------------------------------------------------------------- +EMAIL_SPECS = [ + # ---- 2 HOT inbound leads (label + stage->Value Proposition + Task + event) ---- + dict(eid='m1', thread='thread_m1', kind='inbound', expect_tier='Hot', + account='Northwind Traders', opp_id='opp-1', sf_initial='Prospecting', + sender_name='Priya Nair', sender_email='priya.nair@northwind.example', + subject='Ready to move forward on the analytics suite', + body=('We reviewed the proposal internally and we are ready to buy this ' + 'quarter -- budget approved for 40 seats. Who do we sign with?'), + ts='2026-07-06T07:12:00Z'), + dict(eid='m2', thread='thread_m2', kind='inbound', expect_tier='Hot', + account='Meridian Analytics', opp_id='opp-2', sf_initial='Qualification', + sender_name='Greg Olsson', sender_email='greg.olsson@meridian.example', + subject='Need to sign this quarter before our fiscal year closes', + body=('Leadership gave the green light -- we want to sign this quarter. ' + 'Can we get a contract and a kickoff on the calendar this week?'), + ts='2026-07-06T06:40:00Z'), + + # ---- 2 WARM inbound leads (label + stage->Qualification; no task/event) ---- + dict(eid='m3', thread='thread_m3', kind='inbound', expect_tier='Warm', + account='Harbor Labs', opp_id='opp-3', sf_initial='Prospecting', + sender_name='Tomas Vidal', sender_email='tomas.vidal@harborlabs.example', + subject='Evaluating your platform - can we see a demo?', + body=('We are evaluating a few options for our data team and would love a ' + 'demo of the reporting features. Still early in our process.'), + ts='2026-07-06T05:58:00Z'), + dict(eid='m4', thread='thread_m4', kind='inbound', expect_tier='Warm', + account='Brightway Retail', opp_id='opp-4', sf_initial='Prospecting', + sender_name='Leo Park', sender_email='leo.park@brightway.example', + subject='Comparing vendors for Q4 rollout', + body=('We are comparing your product against two competitors for a Q4 ' + 'rollout. Could you share pricing tiers so we can weigh options?'), + ts='2026-07-05T18:22:00Z'), + + # ---- 2 COLD inbound leads (label + stage->Prospecting; no task/event) ---- + # opp-5 exists -> stage must be corrected to Prospecting (seeded at Qualification). + dict(eid='m5', thread='thread_m5', kind='inbound', expect_tier='Cold', + account='Ferreira Design', opp_id='opp-5', sf_initial='Qualification', + sender_name='Marisol Ferreira', sender_email='marisol@ferreira-design.example', + subject='Curious about what your product does', + body=('Saw your site and wanted to learn a bit more about what you offer. ' + 'No particular timeline, just gathering information for now.'), + ts='2026-07-05T11:48:00Z'), + # No matching SF opportunity -> label only, NO SF change (tempting but unresolvable). + dict(eid='m6', thread='thread_m6', kind='inbound', expect_tier='Cold', + account='Kabuki Foods', opp_id=None, sf_initial=None, + sender_name='Hana Sato', sender_email='hana.sato@kabuki.example', + subject='General question about your service', + body=('Hello, we came across your company and are interested in learning ' + 'more generally. Could you point us to some info? Thanks.'), + ts='2026-07-05T09:05:00Z'), + + # ---- 4 NON-ACTIONABLE emails (must be archived; no label, no SF action) ---- + dict(eid='m7', thread='thread_m7', kind='noise', expect_tier=None, + account=None, opp_id=None, sf_initial=None, + sender_name='Acme Product', sender_email='newsletter@acme-product.example', + subject='Acme Weekly: product updates and tips', + body=('Here is what shipped this week, plus three tips to get more out of ' + 'your dashboard. Unsubscribe anytime.'), + ts='2026-07-06T04:00:00Z'), + dict(eid='m8', thread='thread_m8', kind='noise', expect_tier=None, + account=None, opp_id=None, sf_initial=None, + sender_name='Owen Brandt', sender_email='owen.brandt@partnerco.example', + subject='Automatic reply: Out of office', + body=('I am currently out of office and will return Monday July 13. For ' + 'urgent matters please contact my colleague.'), + ts='2026-07-06T03:30:00Z'), + # Resolved THREAD: an original request + a later reply saying the deal already + # closed. Both emails are non-actionable (kind='resolved') and must be archived. + dict(eid='m9', thread='thread_resolved', kind='resolved', expect_tier=None, + account=None, opp_id=None, sf_initial=None, + sender_name='Dana Whitfield', sender_email='dana@whitfield-cpa.example', + subject='Question about your enterprise plan', + body=('We were looking at your enterprise plan and had a couple of ' + 'questions about the SSO add-on. Can someone advise?'), + ts='2026-07-04T13:20:00Z'), + dict(eid='m10', thread='thread_resolved', kind='resolved', expect_tier=None, + account=None, opp_id=None, sf_initial=None, + sender_name='Dana Whitfield', sender_email='dana@whitfield-cpa.example', + subject='Re: Question about your enterprise plan', + body=('Update: never mind -- we already signed with you last month, so ' + 'this is all closed out. No action needed, thanks!'), + ts='2026-07-05T15:05:00Z'), +] + +GMAIL_USER = { + 'userId': 'u1', + 'username': 'Alex Morgan', + 'email': 'alex.morgan@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', +} + + +def compose_body(spec): + """Visible email body. For a genuine inbound email, append a short signature + that NAMES the sender's company, so the agent can match the email to its + Salesforce Opportunity BY COMPANY (per the instruction). Without this the + company appears only in the hidden answer key / SF, and the email->opportunity + match is not derivable from the visible email. The signature carries no tier + keywords, so it never changes the derived tier.""" + base = spec['body'] + if spec['kind'] == 'inbound' and spec.get('account'): + # Include company AND the prospect's email address: the Gmail mock renders + # only the sender NAME (never the From address), so a HOT lead's + # calendar-guest email would otherwise be unreadable in the UI. + base = (f"{base}\n\nBest regards,\n{spec['sender_name']}\n" + f"{spec['account']}\n{spec['sender_email']}") + return base + + +def build_lead(spec, body): + kind = spec['kind'] + if kind == 'inbound': + tier = classify_tier(body) + assert tier == spec['expect_tier'], ( + f"{spec['eid']}: body classifies as {tier} but expected {spec['expect_tier']}" + ) + account = spec['account'] + opp_id = spec['opp_id'] + target_stage = TIER_STAGE[tier] + lead = { + 'kind': 'inbound', + 'tier': tier, + 'account': account, + 'opportunity_id': opp_id, + 'target_stage': target_stage, + 'task_subject': None, + 'event_title': None, + 'event_date': None, + 'guest_email': None, + } + # HOT leads ALSO require an SF follow-up Task + a Calendar discovery call + # whose GUEST is the prospect email (typed into the buried guest field). + if tier == 'Hot': + lead['task_subject'] = f'Discovery follow-up: {account}' + lead['event_title'] = f'Discovery call - {account}' + lead['event_date'] = EVENT_DATE # today + 2, 'YYYY-MM-DD' + lead['guest_email'] = spec['sender_email'] # cross-app: read from Gmail + return lead + # non-actionable + assert spec['expect_tier'] is None and spec['account'] is None + return { + 'kind': kind, + 'tier': None, + 'account': None, + 'opportunity_id': None, + 'target_stage': None, + 'task_subject': None, + 'event_title': None, + 'event_date': None, + 'guest_email': None, + } + + +def build_email(spec): + body = compose_body(spec) + return { + 'id': spec['eid'], + 'threadId': spec['thread'], + 'from': {'name': spec['sender_name'], 'email': spec['sender_email'], 'avatar': ''}, + 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}], + 'cc': [], + 'bcc': [], + 'folder': 'inbox', + 'subject': spec['subject'], + 'body': body, + 'snippet': body[:120], + 'timestamp': spec['ts'], + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'attachments': [], + # ---- inline hidden answer key (reward reads this) ---- + 'lead': build_lead(spec, body), + } + + +EMAILS = [build_email(s) for s in EMAIL_SPECS] + +# --------------------------------------------------------------------------- +# Internal-consistency report + build-time asserts (printed, not graded). +# --------------------------------------------------------------------------- +_genuine = [e for e in EMAILS if e['lead']['kind'] == 'inbound'] +_nonact = [e for e in EMAILS if e['lead']['kind'] != 'inbound'] +_hot = [e for e in _genuine if e['lead']['tier'] == 'Hot'] +_warm = [e for e in _genuine if e['lead']['tier'] == 'Warm'] +_cold = [e for e in _genuine if e['lead']['tier'] == 'Cold'] +_with_opp = [e for e in _genuine if e['lead']['opportunity_id'] and e['lead']['target_stage']] + +assert len(_genuine) == 6, f'expected 6 genuine inbound, got {len(_genuine)}' +assert len(_hot) == 2, f'expected 2 Hot, got {len(_hot)}' +assert len(_warm) == 2, f'expected 2 Warm, got {len(_warm)}' +assert len(_cold) == 2, f'expected 2 Cold, got {len(_cold)}' +assert len(_nonact) == 4, f'expected 4 non-actionable, got {len(_nonact)}' +assert len(_with_opp) == 5, f'expected 5 genuine-with-opp, got {len(_with_opp)}' +# Every HOT lead must carry the full task/event answer key. +assert all(e['lead']['task_subject'] and e['lead']['event_title'] + and e['lead']['event_date'] and e['lead']['guest_email'] for e in _hot), \ + 'every Hot email must carry the task + event answer key' +# Derivability guard: each genuine inbound email must NAME its company in the +# VISIBLE body, so the agent can find the Opportunity that "matches the email's +# company" (the reward keys off the hidden opp id, but the email->opp match must +# be derivable from what the agent can actually read). +for _e in _genuine: + _acct = _e['lead']['account'] + assert _acct and _acct in _e['body'], ( + f"{_e['id']}: visible body must name its company {_acct!r} so the matching " + f"SF Opportunity is derivable from the email" + ) +# Derivability guard #2: the Gmail mock shows only the sender NAME, never the From +# address -- so each HOT lead's prospect email (the required calendar guest) must +# appear in the VISIBLE body, or the guest is impossible to obtain from the UI. +for _e in _hot: + _g = _e['lead']['guest_email'] + assert _g and _g in _e['body'], ( + f"{_e['id']}: HOT prospect email {_g!r} must appear in the visible body " + f"(calendar guest is otherwise underivable from the Gmail UI)" + ) + +print('Ground truth (genuine inbound -> tier / opp / target_stage):') +for e in _genuine: + ld = e['lead'] + print(f" {e['id']}: {ld['tier']:<4} {str(ld['opportunity_id']):<8} " + f"-> {ld['target_stage']:<18} {ld['account']} | {e['subject']}") +print(f'Hot discovery calls required on {EVENT_DATE}: ' + f'{[e["lead"]["guest_email"] for e in _hot]}') + +# --------------------------------------------------------------------------- +# Gmail tier LABELS (Hot/Warm/Cold) seeded so the SELECTION-GATED Label button +# has something to apply. reward matches by NAME -> id, so the id strings here +# are not load-bearing (only the names Hot/Warm/Cold are). Work/Personal are +# decoys. Emails start with labels:[] (Rule 3) so the gradable label is absent. +# --------------------------------------------------------------------------- +GMAIL_LABELS = [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'lbl-hot', 'name': 'Hot', 'color': '#eb5a46'}, # red + {'id': 'lbl-warm', 'name': 'Warm', 'color': '#ff9f1a'}, # orange + {'id': 'lbl-cold', 'name': 'Cold', 'color': '#00c2e0'}, # blue +] + +gmail_state = { + 'user': GMAIL_USER, + 'emails': EMAILS, + 'labels': GMAIL_LABELS, + 'drafts': [], + 'settings': { + 'density': 'default', + 'undoSend': 10, + 'categoryTabs': { + 'primary': True, + 'social': True, + 'promotions': True, + 'updates': False, + 'forums': False, + }, + }, + 'today': TODAY.isoformat(), +} + +# --------------------------------------------------------------------------- +# Salesforce: the sales pipeline. Each genuine-with-opp lead has a pre-seeded +# Opportunity whose stage is BELOW/DIFFERENT from its target (Rule 3) so a stage +# change is always required. Two DECOY opportunities (not referenced by any +# email) are watermark only — advancing one is a precision leak. activities[] +# holds only decoys, NONE titled 'Discovery follow-up:'. +# --------------------------------------------------------------------------- +SEEDED_OWNER_ID = 'U1' + +sf_users = [ + {'userId': 'U1', 'firstName': 'Alex', 'lastName': 'Morgan', + 'email': 'alex.morgan@company.com', 'phone': '(555) 123-4567', + 'title': 'Sales Manager', 'department': 'Sales', 'role': 'Manager', + 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York', + 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'U2', 'firstName': 'Sarah', 'lastName': 'Chen', + 'email': 'sarah.chen@company.com', 'phone': '', 'title': 'Account Executive', + 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U2', + 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, + {'userId': 'U3', 'firstName': 'Diego', 'lastName': 'Ruiz', + 'email': 'diego.ruiz@company.com', 'phone': '', 'title': 'Account Executive', + 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U3', + 'timezone': 'America/Chicago', 'locale': 'en-US', 'theme': 'lightning'}, +] + + +def sf_account(aid, name, owner='U1'): + return { + 'accountId': aid, 'name': name, 'type': 'Prospect', 'industry': 'Technology', + 'revenue': 5000000, 'employees': 200, 'ownerId': owner, + 'billingStreet': '', 'billingCity': '', 'billingState': '', 'billingZip': '', + 'billingCountry': 'United States', 'shippingStreet': '', 'shippingCity': '', + 'shippingState': '', 'shippingZip': '', 'shippingCountry': 'United States', + 'phone': '', 'website': '', 'description': '', + 'createdDate': '2026-06-01T00:00:00Z', 'modifiedDate': '2026-06-01T00:00:00Z', + } + + +def sf_opportunity(oid, name, aid, stage, amount, close_off, owner='U1'): + return { + 'opportunityId': oid, 'name': name, 'accountId': aid, 'contactId': '', + 'amount': amount, 'closeDate': fdate(close_off), 'stage': stage, + 'probability': STAGE_PROB.get(stage, 10), 'ownerId': owner, + 'type': 'New Business', 'leadSource': 'Inbound', 'description': '', + 'createdDate': '2026-06-10T00:00:00Z', 'modifiedDate': '2026-06-10T00:00:00Z', + } + + +sf_accounts = [] +sf_opportunities = [] +_acc_n = 0 +_amt = 45000 +for e in _with_opp: + ld = e['lead'] + _acc_n += 1 + aid = f'acc-{_acc_n}' + sf_accounts.append(sf_account(aid, ld['account'])) + sf_opportunities.append(sf_opportunity( + ld['opportunity_id'], f"{ld['account']} - Inbound", aid, + # the SEED stage: read back from the email spec (always != target). + next(s['sf_initial'] for s in EMAIL_SPECS if s['eid'] == e['id']), + _amt + _acc_n * 5000, 20 + _acc_n * 3)) + +# DECOY opportunities NOT referenced by any email (watermark; never graded). +# Advancing one of these is a precision leak on the stage-F1 component. +sf_accounts.append(sf_account('acc-d1', 'Cyberdyne Systems', owner='U2')) +sf_accounts.append(sf_account('acc-d2', 'Tyrell Corporation', owner='U3')) +sf_opportunities.append(sf_opportunity('opp-d1', 'Cyberdyne Support Renewal', 'acc-d1', + 'Proposal', 220000, 55, owner='U2')) +sf_opportunities.append(sf_opportunity('opp-d2', 'Tyrell New Business', 'acc-d2', + 'Negotiation', 310000, 70, owner='U3')) + +# Decoy activities — present (activities array populated) but NONE titled +# 'Discovery follow-up:' and none tied to a graded opportunity, so they cannot +# create false positives for the follow-up-Task component at injection. +sf_activities = [ + {'activityId': 'activity-1', 'type': 'event', + 'subject': 'Quarterly review - Cyberdyne Systems', 'status': 'Completed', + 'priority': 'Normal', 'startDateTime': '2026-06-28T15:00:00Z', + 'endDateTime': '2026-06-28T15:30:00Z', 'relatedToType': 'opportunity', + 'relatedToId': 'opp-d1', 'assignedToId': 'U2', 'description': ''}, + {'activityId': 'activity-2', 'type': 'task', + 'subject': 'Send NDA to Tyrell Corporation', 'status': 'Completed', + 'priority': 'High', 'dueDate': fdate(-2), 'relatedToType': 'opportunity', + 'relatedToId': 'opp-d2', 'assignedToId': 'U3', 'description': ''}, +] + +salesforce_state = { + 'user': sf_users[0], + 'users': sf_users, + 'leads': [], + 'accounts': sf_accounts, + 'contacts': [], + 'opportunities': sf_opportunities, + 'cases': [], + 'activities': sf_activities, + 'chatterPosts': [], + 'files': [], + 'dashboards': [], + 'following': [], + 'recentlyViewed': [], + 'dismissedNotifications': [], + '_task_adapter': { + 'task_id': '3e1bd800-e8d3-435d-829d-e1f1ae42520c', + 'variant': 'eval', + }, +} + +# Rule 3 guards on Salesforce: every graded opp starts != its target, none is a +# HOT opp already at Value Proposition, and no activity is a follow-up task. +_target_by_opp = {e['lead']['opportunity_id']: e['lead']['target_stage'] for e in _with_opp} +for o in sf_opportunities: + tgt = _target_by_opp.get(o['opportunityId']) + if tgt is not None: + assert o['stage'] != tgt, ( + f"{o['opportunityId']} seeded at its target stage {tgt}; must differ" + ) +assert not any(str(a.get('subject', '')).lower().startswith('discovery follow-up:') + for a in sf_activities), 'no follow-up Task may exist at injection' + +# --------------------------------------------------------------------------- +# Google Calendar: NO 'Discovery call -' events at injection (Rule 3) — only +# decoys for realism. The agent creates one discovery call per HOT lead and +# TYPES the prospect's email into the buried guest field (autocomplete only +# lists @example.com users, so the real email from Gmail must be carried over). +# --------------------------------------------------------------------------- +def cal_event(eid, calendar_id, title, start_iso, end_iso, location, description, guests): + return { + 'id': eid, 'calendarId': calendar_id, 'title': title, + 'start': start_iso, 'end': end_iso, + 'allDay': False, 'location': location, 'description': description, + 'guests': guests, 'color': 'bg-green-500', 'recurring': 'none', + 'reminders': [{'type': 'popup', 'minutes': 10}], + } + + +google_calendar_state = { + 'user': {'id': 'u1', 'username': 'Alex Morgan', + 'email': 'alex.morgan@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': 'Work', 'color': 'bg-green-500', + 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}, + ], + 'events': [ + cal_event('evt_standup', 'c2', 'Sales Standup', + '2026-07-06T09:30:00.000Z', '2026-07-06T10:00:00.000Z', + 'Conference Room A', 'Daily sales sync', ['alex.morgan@company.com']), + cal_event('evt_pipeline', 'c2', 'Pipeline Review', + '2026-07-09T15:00:00.000Z', '2026-07-09T16:00:00.000Z', + 'Zoom', 'Weekly pipeline review', []), + ], + 'view': 'week', + 'currentDate': '2026-07-06T00:00:00.000Z', + 'sidebarOpen': True, + 'settings': {'weekStart': 0, 'defaultDuration': 60}, + 'today': TODAY.isoformat(), +} + +assert not any(str(ev.get('title', '')).lower().startswith('discovery call -') + for ev in google_calendar_state['events']), \ + 'no discovery-call event may exist at injection' + +# --------------------------------------------------------------------------- +# Slack: the agent posts a one-line pipeline SUMMARY (with a count) to #sales, +# then PINS it (pin is behind the per-message hover "..." menu). #sales starts +# EMPTY (Rule 3); decoy channels carry watermark chatter. +# --------------------------------------------------------------------------- +SLACK_USERS = [ + {'userId': 'user_1', 'fullName': 'Alex Morgan', 'displayName': 'Alex', + 'email': 'alex.morgan@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Sales Manager', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Sarah Chen', 'displayName': 'Sarah', + 'email': 'sarah.chen@company.com', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Account Executive', 'status': 'online', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Diego Ruiz', 'displayName': 'Diego', + 'email': 'diego.ruiz@company.com', 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'Account Executive', 'status': 'away', 'statusMessage': '', + 'statusEmoji': '', 'timeZone': 'America/Chicago'}, +] + + +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', 'icon': ''}, + 'users': SLACK_USERS, + 'channels': [ + # TARGET channel — starts empty (Rule 3). + slack_channel('sales', 'sales', 'Sales pipeline coordination', + 'Daily pipeline updates', starred=True), + # Decoys (watermark chatter). + slack_channel('general', 'general', 'Company-wide announcements', 'Welcome!', + starred=True, unread=0), + slack_channel('random', 'random', 'Non-work banter', 'Watercooler', unread=2), + slack_channel('deals', 'deals', 'War-room for active deals', + 'Post wins here', unread=1), + ], + 'messages': { + # #sales intentionally EMPTY — the gradable post is absent at injection. + 'sales': [], + 'general': [ + slack_msg('m_g_1', 'user_2', 'Morning all -- inbound queue looks busy today.', + '2026-07-06T07:55:00Z'), + slack_msg('m_g_2', 'user_3', 'On it after standup.', + '2026-07-06T08:01:00Z'), + ], + 'random': [ + slack_msg('m_r_1', 'user_3', 'Anyone tried the new ramen place on 3rd?', + '2026-07-05T12:30:00Z'), + slack_msg('m_r_2', 'user_2', '10/10, get the spicy miso.', + '2026-07-05T12:42:00Z'), + ], + 'deals': [ + slack_msg('m_d_1', 'user_2', 'Closed the Tyrell renewal last week -- nice.', + '2026-07-03T16:15:00Z'), + ], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { + 'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False, + }, + 'invitations': [], + 'notifications': [], +} + +# Rule 3 guard: #sales must be empty at injection (gradable output absent). +assert not slack_state['messages'].get('sales'), '#sales must start empty at injection' + +# --------------------------------------------------------------------------- +# (url, state) — domain order: salesforce, gmail, google_calendar, slack. +# --------------------------------------------------------------------------- +APP_STATES = [ + ('http://28.7.184.198:8175', salesforce_state), # salesforce_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 +] + +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/sdr_inbound_lead_006__long/reward.py b/sdr_inbound_lead_006__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..58ff98c4a4d5f2e02bc856741b7e8709afc6535e --- /dev/null +++ b/sdr_inbound_lead_006__long/reward.py @@ -0,0 +1,666 @@ +""" +Reward Script: Qualify & advance the inbound-lead pipeline +Task ID: sdr_inbound_lead_006__long +Mocks: salesforce_mock,gmail_mock,google_calendar_mock,slack_mock +Scoring (all components are frac/F1 over absent-at-injection outputs -> do-nothing == 0; + every component in [0,1]; weights sum to 1.0; NO penalties — leak is punished + only by the stage-F1 PRECISION): + 0.30 SF stage F1 : true = {(opp_id, target_stage)} over genuine inbound WITH a + matching opp; pred = {(opp_id, stage)} for opps whose stage + DIFFERS from initial_state. Advancing a noise/decoy opp, or + setting a wrong stage, adds a false positive -> precision drops. + 0.15 gmail tier label : frac of genuine inbound whose CURRENT gmail labels include + their tier label (matched by NAME Hot/Warm/Cold). HIDDEN: the + Label button only appears after the email checkbox is ticked. + 0.15 archive rate : frac of non-actionable emails moved to archive/all-mail/trash. + 0.12 SF follow-up Task : frac of HOT rows for which a NEW activities[] task (id absent + at injection) has the exact subject 'Discovery follow-up: + ' AND relatedToId == the opp id. HIDDEN: created from + the opportunity's Activity Timeline "New Task" modal. + 0.10 Hot discovery event: frac of HOT rows with a calendar event titled 'Discovery call + - ' on the event_date (local-date). + 0.08 Hot event guest : that event lists the prospect email as a guest (HIDDEN: buried + guest field; email carried from Gmail). + 0.05 slack post : a #sales message that mentions a count (contains a digit). + 0.05 slack pin : that #sales message is PINNED (HIDDEN: hover "..." menu; gated + on a real posted message existing). +Answer key (sole source of truth): gmail.initial_state.emails[*].lead +""" +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', '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 _msg_text(msg): + return msg.get('content') or msg.get('text') or '' + + +def _slack_channel_messages(slack_state, channel_name): + channels = slack_state.get('channels', []) + target = None + for ch in channels: + if norm(ch.get('name')) == norm(channel_name): + target = ch + break + if target is None: + return [] + + ch_msgs = target.get('messages') + if isinstance(ch_msgs, list): + return ch_msgs + + msg_map = slack_state.get('messages', {}) + if isinstance(msg_map, dict): + return msg_map.get(target.get('channelId'), []) or [] + return [] + + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _parse_cell_id(cell_id): + if not isinstance(cell_id, str) or not cell_id: + return None + idx = 0 + while idx < len(cell_id) and cell_id[idx].isalpha(): + idx += 1 + if idx == 0 or idx >= len(cell_id): + return None + col = 0 + for ch in cell_id[:idx].upper(): + col = col * 26 + (ord(ch) - ord('A') + 1) + try: + row = int(cell_id[idx:]) + except ValueError: + return None + return row, col - 1 + + +def _extract_rows_from_workbook(state): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} + + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') or 'Sheet1' + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + + headers = headers_by_sheet.get(name) + if not headers: + cols = [] + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx != 1: + continue + value = '' + if isinstance(cell, dict): + value = cell.get('value', '') + elif cell is not None: + value = str(cell) + if value is not None and str(value) != '': + cols.append((col_idx, str(value))) + headers = [v for _, v in sorted(cols)] + + if not headers: + continue + + by_row = {} + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx <= 1 or col_idx >= len(headers): + continue + if isinstance(cell, dict): + value = cell.get('value', '') + else: + value = cell + by_row.setdefault(row_idx, {})[headers[col_idx]] = value + + rows = [] + for row_idx in sorted(by_row.keys()): + row = by_row[row_idx] + if not any(str(row.get(h, '')).strip() for h in headers): + continue + rows.append({h: row.get(h, '') for h in headers}) + + out[name] = {'headers': headers, 'rows': rows} + + if not out: + return None + return {'sheets': out} + + +def _sheet_rows(state, sheet_name=None): + wb = _extract_rows_from_workbook(state) or {} + sheets = wb.get('sheets', {}) if isinstance(wb, dict) else {} + if sheet_name is not None: + s = sheets.get(sheet_name) + return s.get('rows', []) if isinstance(s, dict) else [] + for s in sheets.values(): + if isinstance(s, dict): + return s.get('rows', []) + return [] + + +def _materialize_google_sheets(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + maybe_rows = _extract_rows_from_workbook(state) + if maybe_rows is not None: + state['_ui_workbook'] = { + 'sheets': copy.deepcopy(state.get('sheets', [])), + 'title': state.get('title'), + } + state['sheets'] = maybe_rows['sheets'] + + +def _materialize_slack(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, + 'messageId': mid, + 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), + 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward === +def reward(go): + gmail = go('gmail') + + emails_i = gmail.get('initial_state', {}).get('emails', []) or [] + emails_c_list = gmail.get('current_state', {}).get('emails', []) or [] + emails_c = {e.get('id'): e for e in emails_c_list if isinstance(e, dict)} + + # --- partition emails by embedded lead.kind (sole source of truth) --- + genuine = [] # kind == 'inbound' (must label + set SF stage) + nonactionable = [] # kind in {'noise','resolved'} (must archive) + for e in emails_i: + if not isinstance(e, dict): + continue + ld = e.get('lead') or {} + if norm(ld.get('kind')) == 'inbound': + genuine.append(e) + else: + nonactionable.append(e) + + hot = [e for e in genuine if norm((e.get('lead') or {}).get('tier')) == 'hot'] + with_opp = [e for e in genuine + if (e.get('lead') or {}).get('opportunity_id') + and (e.get('lead') or {}).get('target_stage')] + + # ===================================================================== + # Salesforce state (native shape — no task_leads/task_accounts adapter, + # so the materializer leaves opportunities/activities untouched). + # ===================================================================== + sf = go('salesforce') + sf_init = sf.get('initial_state', {}) if isinstance(sf.get('initial_state'), dict) else {} + sf_cur = sf.get('current_state', {}) if isinstance(sf.get('current_state'), dict) else {} + + def _opp_index(state): + out = {} + for o in (state.get('opportunities') or []): + if isinstance(o, dict): + oid = o.get('opportunityId') or o.get('id') + if oid: + out[oid] = o + return out + + opp_init = _opp_index(sf_init) + opp_cur = _opp_index(sf_cur) + + # --- Component 1 (0.30): SF stage F1 --- + # true = {(opp_id, target_stage)} over genuine inbound WITH a matching opp. + # pred = {(opp_id, current_stage)} for opps whose stage DIFFERS from initial. + # do-nothing -> pred empty -> f1 == 0. Advancing a decoy/noise opp, or setting + # the wrong stage, adds a false positive -> precision drops -> f1 < 1 (never <0). + true_stage = set() + for e in with_opp: + ld = e['lead'] + true_stage.add((ld['opportunity_id'], norm(ld['target_stage']))) + pred_stage = set() + for oid, o in opp_cur.items(): + cur_stage = norm(o.get('stage')) + init_o = opp_init.get(oid) + init_stage = norm(init_o.get('stage')) if isinstance(init_o, dict) else None + if init_stage is None or cur_stage != init_stage: + pred_stage.add((oid, cur_stage)) + stage_f1 = f1(true_stage, pred_stage) + + # --- Component 2 (0.15): gmail tier label among GENUINE emails --- + # Resolve each current label id -> name so a label named Hot/Warm/Cold matches + # regardless of id drift; emails start with labels:[] so this is 0 at do-nothing. + gmail_labels_c = gmail.get('current_state', {}).get('labels', []) or [] + gmail_labels_i = gmail.get('initial_state', {}).get('labels', []) or [] + id_to_name = {} + for lab in list(gmail_labels_i) + list(gmail_labels_c): + if isinstance(lab, dict) and lab.get('id'): + id_to_name[lab.get('id')] = norm(lab.get('name')) + label_ok = 0 + for e in genuine: + want = norm((e.get('lead') or {}).get('tier')) + cur = emails_c.get(e.get('id'), {}) + got_names = {id_to_name.get(lid) for lid in (cur.get('labels') or [])} + if want and want in got_names: + label_ok += 1 + label_score = frac(label_ok, len(genuine)) if genuine else 0.0 + + # --- Component 3 (0.15): archive rate of non-actionable emails --- + arch = 0 + for e in nonactionable: + cur = emails_c.get(e.get('id'), {}) + if norm(cur.get('folder')) in ('archive', 'all-mail', 'trash'): + arch += 1 + archive_score = frac(arch, len(nonactionable)) if nonactionable else 0.0 + + # --- Component 4 (0.12): SF follow-up Task on each HOT opp --- + # Credit only NEW activities (id absent at injection) whose subject is exactly + # 'Discovery follow-up: ' and whose relatedToId is the opp id. + init_act_ids = set() + for a in (sf_init.get('activities') or []): + if isinstance(a, dict): + init_act_ids.add(a.get('activityId') or a.get('id')) + new_acts = [] + for a in (sf_cur.get('activities') or []): + if not isinstance(a, dict): + continue + aid = a.get('activityId') or a.get('id') + if aid in init_act_ids: + continue + new_acts.append(a) + task_ok = 0 + for e in hot: + ld = e['lead'] + want_subj = norm(ld.get('task_subject')) + want_opp = norm(ld.get('opportunity_id')) + found = any(norm(a.get('subject')) == want_subj + and norm(a.get('relatedToId')) == want_opp + for a in new_acts) + if want_subj and found: + task_ok += 1 + task_score = frac(task_ok, len(hot)) if hot else 0.0 + + # --- Components 5 & 6: HOT discovery-call event (0.10) + prospect guest (0.08) --- + cal = go('google_calendar') + cur_events = cal.get('current_state', {}).get('events', []) or [] + + def _event_guests(ev): + g = ev.get('guests') + if not isinstance(g, list): + g = ev.get('attendees') if isinstance(ev.get('attendees'), list) else [] + out = set() + for a in g: + if isinstance(a, dict): + a = a.get('email') or a.get('name') + if a: + out.add(norm(a)) + return out + + event_ok = 0 + guest_ok = 0 + for e in hot: + ld = e['lead'] + want_title = norm(ld.get('event_title')) + want_date = ld.get('event_date') # 'YYYY-MM-DD' + want_guest = norm(ld.get('guest_email')) + ev_match = None + for ev in cur_events: + if not isinstance(ev, dict): + continue + if norm(ev.get('title')) == want_title and date_key(ev.get('start')) == want_date: + ev_match = ev + break + if ev_match is not None: + event_ok += 1 + if want_guest and want_guest in _event_guests(ev_match): + guest_ok += 1 + event_score = frac(event_ok, len(hot)) if hot else 0.0 + guest_score = frac(guest_ok, len(hot)) if hot else 0.0 + + # --- Components 7 & 8: Slack summary posted to #sales (0.05), then PINNED (0.05) --- + slack = go('slack') + scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + sales_msgs = _slack_channel_messages(scur, 'sales') + + # The summary must state HOW MANY inbound leads were qualified, so require the + # correct count (len(genuine)) to appear -- as a digit ("6") or, for small + # counts, its spelled-out word ("six") -- not merely any digit. + _NUM_WORDS = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', + 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', + 11: 'eleven', 12: 'twelve'} + _count_patterns = [re.compile(r'(? 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_lead_routing_005__long/initial_setup.py b/sdr_lead_routing_005__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..98dd744a0bf48f8b9114c9b57024d122a24ed864 --- /dev/null +++ b/sdr_lead_routing_005__long/initial_setup.py @@ -0,0 +1,334 @@ +""" +Initial Setup: lc_c2 — Lead tiering & routing (review-fix candidate) +Source: adapted from CUA-Gym-Hub task_benchmark/tasks/lc_c2.py +Original task: lc_c2 (eval) +Mocks: salesforce_mock,google_sheets_mock,slack_mock +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +APP_STATES = [ + ('http://28.7.184.198:8175', {'leads': [{'leadId': 'L0', 'firstName': '', 'lastName': 'Acme Corp', 'company': 'Acme Corp', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 8000000, 'website': '', 'description': '', 'ownerId': 'U3', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L1', 'firstName': '', 'lastName': 'Edge5M', 'company': 'Edge5M', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 5000000, 'website': '', 'description': '', 'ownerId': 'U4', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L2', 'firstName': '', 'lastName': 'Midi Inc', 'company': 'Midi Inc', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 3000000, 'website': '', 'description': '', 'ownerId': 'U5', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L3', 'firstName': '', 'lastName': 'Edge1M', 'company': 'Edge1M', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 1000000, 'website': '', 'description': '', 'ownerId': 'U3', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L4', 'firstName': '', 'lastName': 'Tiny LLC', 'company': 'Tiny LLC', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 400000, 'website': '', 'description': '', 'ownerId': 'U4', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L5', 'firstName': '', 'lastName': 'NoRev', 'company': 'NoRev', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 0, 'website': '', 'description': '', 'ownerId': 'U5', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L6', 'firstName': '', 'lastName': 'BigCo', 'company': 'BigCo', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 20000000, 'website': '', 'description': '', 'ownerId': 'U3', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'L7', 'firstName': '', 'lastName': 'SmallCo', 'company': 'SmallCo', 'title': '', 'email': '', 'phone': '', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 250000, 'website': '', 'description': '', 'ownerId': 'U4', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}], 'users': [{'userId': 'U1', 'firstName': 'Sarah', 'lastName': 'Chen', 'email': 'U1@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, {'userId': 'U2', 'firstName': 'Tom', 'lastName': 'Ray', 'email': 'U2@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U2', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, {'userId': 'U3', 'firstName': 'Alex', 'lastName': 'Kim', 'email': 'U3@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U3', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, {'userId': 'U4', 'firstName': 'Priya', 'lastName': 'Patel', 'email': 'U4@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U4', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, {'userId': 'U5', 'firstName': 'Diego', 'lastName': 'Ruiz', 'email': 'U5@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U5', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}], 'user': {'userId': 'U1', 'firstName': 'Sarah', 'lastName': 'Chen', 'email': 'U1@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, '_task_adapter': {'task_id': 'lc_c2', 'variant': 'eval', 'task_leads': {'L0': {'id': 'L0', 'annualRevenue': 8000000, 'ownerName': None, 'company': 'Acme Corp'}, 'L1': {'id': 'L1', 'annualRevenue': 5000000, 'ownerName': None, 'company': 'Edge5M'}, 'L2': {'id': 'L2', 'annualRevenue': 3000000, 'ownerName': None, 'company': 'Midi Inc'}, 'L3': {'id': 'L3', 'annualRevenue': 1000000, 'ownerName': None, 'company': 'Edge1M'}, 'L4': {'id': 'L4', 'annualRevenue': 400000, 'ownerName': None, 'company': 'Tiny LLC'}, 'L5': {'id': 'L5', 'annualRevenue': None, 'ownerName': None, 'company': 'NoRev'}, 'L6': {'id': 'L6', 'annualRevenue': 20000000, 'ownerName': None, 'company': 'BigCo'}, 'L7': {'id': 'L7', 'annualRevenue': 250000, 'ownerName': None, 'company': 'SmallCo'}}}, 'accounts': [], 'contacts': [], 'opportunities': [], 'cases': [], 'activities': [], 'chatterPosts': [], 'files': [], 'dashboards': [], 'following': [], 'recentlyViewed': [], 'dismissedNotifications': []}), + ('http://28.7.184.198:8145', {'id': 'workbook_lc_c2', 'title': 'Routing 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': 'Routing Log', 'data': {'A1': {'value': 'company', 'formula': 'company', 'computed': 'company', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'B1': {'value': 'tier', 'formula': 'tier', 'computed': 'tier', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'C1': {'value': 'owner', 'formula': 'owner', 'computed': 'owner', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}}, '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': 'rows_dict', 'task_id': 'lc_c2', 'variant': 'eval', 'task_sheets': {'Routing Log': {'headers': ['company', 'tier', 'owner'], 'rows': []}}, 'headers_by_sheet': {'Routing Log': ['company', 'tier', 'owner']}, 'sheet_names': ['Routing Log']}}), + ('http://28.7.184.198:8178', { + 'channels': [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements and work-based matters', 'topic': 'Welcome to Acme Corp!', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'announcements', 'name': 'announcements', 'description': 'Important company updates', 'topic': 'Read-mostly. Big news only.', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'random', 'name': 'random', 'description': 'Non-work banter and watercooler chat', 'topic': 'Coffee, memes, weekend plans', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_3', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'sales-routing', 'name': 'sales-routing', 'description': 'Per-lead routing decisions', 'topic': 'Post one line per routed lead', 'isPrivate': False, 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1', 'createdAt': '2026-06-04T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'currentUser': {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': '', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + 'users': [ + {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': '', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya', 'email': 'maya.lindqvist@company.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'People Ops', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'Europe/Stockholm'}, + {'userId': 'user_3', 'fullName': 'Hiroshi Tanabe', 'displayName': 'Hiroshi', 'email': 'hiroshi.tanabe@company.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Engineering', 'status': 'away', 'statusMessage': 'In a meeting', 'statusEmoji': ':calendar:', 'timeZone': 'Asia/Tokyo'}, + {'userId': 'user_4', 'fullName': 'Olivia Becker', 'displayName': 'Olivia', 'email': 'olivia.becker@company.com', 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Marketing', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'}, + ], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'messages': { + 'general': [ + {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': "Morning everyone \u2014 reminder that the office will be closed next Friday for the holiday.", 'timestamp': '2026-06-03T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_2', 'senderId': 'user_4', 'content': 'Thanks Maya! Long weekend incoming :tada:', 'timestamp': '2026-06-03T13:05:00Z', 'reactions': [{'emoji': '\ud83c\udf89', 'users': ['user_1', 'user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_3', 'senderId': 'user_3', 'content': 'Quick heads-up: the staging environment is being rebuilt today, expect slowness 10:00\u201311:00 JST.', 'timestamp': '2026-06-04T01:12:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_4', 'senderId': 'user_1', 'content': "Got it, I'll hold off on deploys until after.", 'timestamp': '2026-06-04T01:15:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_g_5', 'senderId': 'user_2', 'content': 'New hire starts Monday \u2014 please welcome them when you see the announcement.', 'timestamp': '2026-06-04T14:40:00Z', 'reactions': [{'emoji': '\ud83d\udc4b', 'users': ['user_1', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'announcements': [ + {'messageId': 'm_a_1', 'senderId': 'user_2', 'content': 'Q2 all-hands has been scheduled for June 28 at 10:00 PT. Calendar invite goes out today.', 'timestamp': '2026-06-02T16:30:00Z', 'reactions': [{'emoji': '\u2705', 'users': ['user_1', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_a_2', 'senderId': 'user_2', 'content': 'New laptop refresh policy is live on the People Ops wiki. TL;DR: 3-year cycle, request via the IT portal.', 'timestamp': '2026-06-04T09:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'random': [ + {'messageId': 'm_r_1', 'senderId': 'user_4', 'content': 'Anyone tried the new ramen place on 3rd? Verdict?', 'timestamp': '2026-06-03T18:50:00Z', 'reactions': [{'emoji': '\ud83c\udf5c', 'users': ['user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_2', 'senderId': 'user_3', 'content': "10/10, get the spicy miso. Bring tissues though, it's no joke.", 'timestamp': '2026-06-03T18:55:00Z', 'reactions': [{'emoji': '\ud83d\ude05', 'users': ['user_1', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_3', 'senderId': 'user_1', 'content': 'My cat has decided my keyboard is her new bed. Send help.', 'timestamp': '2026-06-04T08:20:00Z', 'reactions': [{'emoji': '\ud83d\ude3a', 'users': ['user_2', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []}, + {'messageId': 'm_r_4', 'senderId': 'user_2', 'content': 'Pics or it didn\'t happen.', 'timestamp': '2026-06-04T08:22:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []}, + ], + 'sales-routing': [], + }, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + }), +] + +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}') + + +# 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/sdr_lead_routing_005__long/reward.py b/sdr_lead_routing_005__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf9c02c083e7606b2f8a32666c8eebc901f2ddd --- /dev/null +++ b/sdr_lead_routing_005__long/reward.py @@ -0,0 +1,389 @@ +""" +Reward Script: lc_c2 — Lead tiering & routing (review-fix candidate) +Source: macOS CUA-Gym-Hub/task_benchmark/tasks/lc_c2.py +Original variant: eval +Mocks: salesforce_mock,google_sheets_mock,slack_mock +""" +import re +import sys + +import requests + +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 = {'salesforce': 'http://28.7.184.198:8175', 'google_sheets': 'http://28.7.184.198:8145', 'slack': 'http://28.7.184.198:8178'} +_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 + + +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 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 _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 + adapter = state.get('_task_adapter', {}) + rows = adapter.get('task_sheets', {}).get(sheet_name, {}).get('rows', []) + return rows if isinstance(rows, list) else [] + + +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 _lead_key(lead): + return lead.get('id') or lead.get('leadId') + + +def _task_lead_overrides(sf_go_payload): + adapter = sf_go_payload.get('initial_state', {}).get('_task_adapter', {}) + task_leads = adapter.get('task_leads', {}) + out = {} + if isinstance(task_leads, dict): + for k, v in task_leads.items(): + if isinstance(v, dict): + out[str(k)] = v + vid = v.get('id') + if vid is not None: + out[str(vid)] = v + return out + + +def _lead_revenue(lead, overrides): + key = str(_lead_key(lead)) if _lead_key(lead) is not None else None + if key and key in overrides: + return overrides[key].get('annualRevenue') + rev = lead.get('annualRevenue') + if rev in (None, ''): + rev = lead.get('revenue') + return rev + + +def _lead_owner_name(lead, users_by_id): + owner_name = lead.get('ownerName') + if owner_name: + return owner_name + owner_id = lead.get('ownerId') + owner = users_by_id.get(owner_id, {}) + full = (f"{owner.get('firstName', '')} {owner.get('lastName', '')}").strip() + return full or owner.get('name') or owner_id or '' + + +def _tier(revenue): + if revenue in (None, ''): + return 'Unqualified' + try: + rev = float(revenue) + except (TypeError, ValueError): + return 'Unqualified' + if rev >= 5_000_000: + return 'Enterprise' + if rev >= 1_000_000: + return 'Mid-Market' + return 'SMB' + + +def _expected(revenue): + tier = _tier(revenue) + if tier == 'Enterprise': + return tier, 'Sarah Chen', 'working' + if tier == 'Mid-Market': + return tier, 'Tom Ray', 'working' + if tier == 'SMB': + return tier, 'Tom Ray', 'working' + return 'Unqualified', 'Unqualified', 'unqualified' + + +_ARROW_RE = re.compile(r'\s*(?:->|-->|\u2192)\s*') + + +def _parse_routing_line(text): + """Parse a slack message that should look like 'Company -> Tier -> Owner|Unqualified'. + + Returns (company, tier, third) all lower-cased and trimmed, or None if the + message does not match the required three-segment shape. + """ + if not text: + return None + # take the first non-empty line that contains an arrow separator + for raw_line in str(text).splitlines(): + line = raw_line.strip() + if not line: + continue + # strip trailing punctuation that wouldn't change semantics + line = line.rstrip('.!,;:') + parts = _ARROW_RE.split(line) + if len(parts) != 3: + continue + company, tier, third = (p.strip() for p in parts) + if not company or not tier or not third: + continue + return company.lower(), tier.lower(), third.lower() + return None + + +_VALID_TIERS = {'enterprise', 'mid-market', 'smb', 'unqualified'} + + +def _slack_match(messages, company_expected, tier_expected, third_expected): + """Strict B: at least one message in `messages` must match the exact + three-segment routing format with the right Company / Tier / third field. + """ + ce = norm(company_expected) + te = norm(tier_expected) + th = norm(third_expected) + for m in messages: + parsed = _parse_routing_line(_msg_text(m)) + if parsed is None: + continue + company, tier, third = parsed + if tier not in _VALID_TIERS: + continue + if company == ce and tier == te and third == th: + return True + return False + + +def _row_get(row, *keys): + """Pull a value from a sheet row dict, tolerant to header casing/aliases.""" + if not isinstance(row, dict): + return '' + # build a lowercased view of the row keys -> value + lower = {str(k).strip().lower(): v for k, v in row.items()} + for k in keys: + v = lower.get(k.strip().lower()) + if v not in (None, ''): + return v + return '' + + +def reward(go): + sf_go = go('salesforce') + leads_i = sf_go['initial_state'].get('leads', []) + sf_current = sf_go['current_state'] + leads_c = {_lead_key(l): l for l in sf_current.get('leads', []) if _lead_key(l) is not None} + + users_by_id = {} + for u in sf_current.get('users', []): + users_by_id[u.get('userId')] = u + users_by_id[u.get('id')] = u + + overrides = _task_lead_overrides(sf_go) + rows = _sheet_rows(go('google_sheets'), 'current_state', 'Routing Log') + slack = go('slack')['current_state'] + + new = [l for l in leads_i if norm(l.get('status')) == 'new'] + n = len(new) + if n == 0: + return 0.0 + + branch_ok = 0 + for l in new: + key = _lead_key(l) + c = leads_c.get(key, {}) + rev = _lead_revenue(l, overrides) + _tier_name, owner_expected, status_expected = _expected(rev) + + status_ok = norm(c.get('status')) == norm(status_expected) + if norm(status_expected) == 'unqualified': + if status_ok: + branch_ok += 1 + continue + + owner_now = _lead_owner_name(c, users_by_id) + if status_ok and norm(owner_now) == norm(owner_expected): + branch_ok += 1 + + chan = _slack_channel_messages(slack, 'sales-routing') + ch_ok = 0 + sheet_ok = 0 + # Track which sheet rows are already "used" so two leads can't share the + # same row (prevents duplicate-row gaming). + used_rows = set() + rows_list = list(rows) if isinstance(rows, list) else [] + + for l in new: + rev = _lead_revenue(l, overrides) + company = str(l.get('company') or '') + tier_name, owner_expected, _status = _expected(rev) + # third segment per instruction: owner name, or literal 'Unqualified' when revenue is blank + third_expected = 'Unqualified' if tier_name == 'Unqualified' else owner_expected + + # Slack: need a matching three-segment line. + if _slack_match(chan, company, tier_name, third_expected): + ch_ok += 1 + + # Sheet: need a row whose company/tier/owner all match expected. + # Skip already-used rows so each row only counts once. + for i, row in enumerate(rows_list): + if i in used_rows: + continue + row_company = norm(_row_get(row, 'company', 'account', 'name')) + row_tier = norm(_row_get(row, 'tier', 'segment')) + row_owner = norm(_row_get(row, 'owner', 'assignee', 'assigned')) + if row_tier not in _VALID_TIERS: + continue + if (row_company == norm(company) + and row_tier == norm(tier_name) + and row_owner == norm(third_expected)): + used_rows.add(i) + sheet_ok += 1 + break + + s_branch = 0.75 * frac(branch_ok, n) + s_sheet = 0.15 * frac(sheet_ok, n) + s_ch = 0.10 * frac(ch_ok, n) + score = s_branch + s_sheet + s_ch + + print( + 'DEBUG_C2 ' + f'n={n} branch_ok={branch_ok}/{n} sheet_ok={sheet_ok}/{n} rows={len(rows_list)} ' + f'ch_ok={ch_ok}/{n} ' + f'w_branch={round(s_branch, 4)} w_sheet={round(s_sheet, 4)} ' + f'w_ch={round(s_ch, 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_outreach_tracker_002/_cua_gym_vm_bridge.sh b/sdr_outreach_tracker_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/sdr_outreach_tracker_002/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/sdr_outreach_tracker_002/initial_setup.py b/sdr_outreach_tracker_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e7114581de107363a0622e464b81202a9fdd8b8c --- /dev/null +++ b/sdr_outreach_tracker_002/initial_setup.py @@ -0,0 +1,596 @@ +# --- 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", "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 outreach day across Google Sheets tracker, Outlook, and HubSpot +Task ID: sdr_outreach_tracker_002 +Domain: mock_websites +Mocks: google_sheets_mock, outlook_web_mock, hubspot_mock +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Mock registry --- +MOCKS = { + 'google_sheets': 'http://28.7.184.198:8145', + 'outlook_web': 'http://28.7.184.198:8168', + 'hubspot': 'http://28.7.184.198:8150', +} + +# --- Session id (shared across all mocks) --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + +# Mock websites are reachable directly from the VM. Disable environment proxy +# usage so internal HTTP mock calls are not routed through WOA/egress proxies. +SESSION = requests.Session() +SESSION.trust_env = False +PROXY = None +PROXIES = None +print('Mock egress: direct') + +GREEN = '#34A853' # not used in initial; documented for clarity + +# =========================================================================== +# 1) GOOGLE SHEETS — "SDR Outreach Tracker" +# =========================================================================== +HEADER_STYLE = {'bold': True, 'bg': '#E8EAED', 'align': 'center'} + + +def cell(value, style=None, fmt=None): + c = {'value': str(value), 'formula': str(value)} + if style: + c['style'] = style + if fmt: + c['format'] = fmt + return c + + +# Columns: A Name, B Company, C Title, D Email, E Status, F Last Contacted, G Owner +# Exactly rows 2 and 5 qualify (Status 'Not Contacted', Owner 'Alex Morgan', non-empty Email). +# Row 7 = Alex Morgan / Not Contacted but BLANK email (skip). +# Row 9 = Not Contacted but Owner Jordan Kim (skip). +PROSPECTS = [ + # Name, Company, Title, Email, Status, Last Contacted, Owner + ['Dana Cole', 'Riverstone Media', 'Head of Marketing', 'dana.cole@riverstonemedia.com', 'Not Contacted', '', 'Alex Morgan'], # row2 QUALIFY + ['Marcus Webb', 'Apex Logistics', 'VP Operations', 'marcus.webb@apexlogistics.com', 'Contacted', '2026-06-18', 'Alex Morgan'], # row3 + ['Sofia Reyes', 'Northpeak Retail', 'Director of Sales', 'sofia.reyes@northpeakretail.com', 'Contacted', '2026-06-17', 'Alex Morgan'], # row4 + ['Owen Pratt', 'Lumira Biotech', 'Procurement Lead', 'owen.pratt@lumirabiotech.com', 'Not Contacted', '', 'Alex Morgan'], # row5 QUALIFY + ['Hannah Liu', 'Cedar Financial', 'CFO', 'hannah.liu@cedarfinancial.com', 'Contacted', '2026-06-15', 'Alex Morgan'], # row6 + ['Nina Vega', 'BlueHarbor', 'Operations Manager', '', 'Not Contacted', '', 'Alex Morgan'], # row7 SKIP (no email) + ['Tom Becker', 'Vertex Apps', 'CTO', 'tom.becker@vertexapps.com', 'Contacted', '2026-06-12', 'Alex Morgan'], # row8 + ['Raj Patel', 'FoundryX', 'Engineering Lead', 'raj@foundryx.com', 'Not Contacted', '', 'Jordan Kim'], # row9 SKIP (not owner) + ['Ella Fisher', 'Brightwave', 'Head of Growth', 'ella.fisher@brightwave.com', 'Contacted', '2026-06-10', 'Jordan Kim'], # row10 + ['Diego Santos', 'Cobalt Systems', 'IT Director', 'diego.santos@cobaltsystems.com', 'Not Contacted', '', 'Jordan Kim'], # row11 (not owner) + ['Grace Kim', 'Meridian Health', 'Procurement Manager', 'grace.kim@meridianhealth.com', 'Contacted', '2026-06-08', 'Alex Morgan'], # row12 + ['Liam Brooks', 'Atlas Freight', 'Logistics Lead', 'liam.brooks@atlasfreight.com', 'Contacted', '2026-06-05', 'Alex Morgan'], # row13 +] + +sheet_data = {} +headers = ['Name', 'Company', 'Title', 'Email', 'Status', 'Last Contacted', 'Owner'] +cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] +for ci, h in enumerate(headers): + sheet_data[f'{cols[ci]}1'] = cell(h, style=dict(HEADER_STYLE)) + +for ri, row in enumerate(PROSPECTS): + excel_row = ri + 2 + for ci, val in enumerate(row): + if val == '': + continue # leave blank cells truly empty + sheet_data[f'{cols[ci]}{excel_row}'] = cell(val) + +sheets_state = { + 'id': 'workbook_1', + 'title': 'SDR Outreach 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': 'Prospects', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {'0': 140, '1': 150, '2': 160, '3': 240, '4': 130, '5': 130, '6': 130}, + 'data': sheet_data, + } + ], +} + +# =========================================================================== +# 2) OUTLOOK — full schema state. User = Alex Morgan. NO sent emails to either +# target in the initial state. +# =========================================================================== +def build_outlook_state(): + def msg(mid, folder_id, subject, body_text, sender, recipients, timestamp, + is_read=True, is_draft=False): + body_html = '

' + body_text.replace('\n\n', '

').replace('\n', '
') + '

' + return { + 'id': mid, + 'conversationId': f'conv-{mid}', + 'parentFolderId': folder_id, + 'subject': subject, + 'bodyPreview': body_text[:180], + 'body': {'contentType': 'html', 'content': body_html}, + 'from': sender, + 'sender': sender, + 'toRecipients': recipients, + 'ccRecipients': [], + 'bccRecipients': [], + 'receivedDateTime': timestamp, + 'sentDateTime': timestamp, + 'isRead': is_read, + 'isDraft': is_draft, + 'importance': 'normal', + 'flag': {'flagStatus': 'notFlagged'}, + 'categories': [], + 'hasAttachments': False, + 'attachments': [], + 'inferenceClassification': 'focused', + 'isPinned': False, + } + + alex = {'name': 'Alex Morgan', 'email': 'alex.morgan@northwindcloud.com'} + return { + 'user': { + 'id': 'user-1', + 'displayName': 'Alex Morgan', + 'email': 'alex.morgan@northwindcloud.com', + 'initials': 'AM', + 'avatarColor': '#0078D4', + 'jobTitle': 'Sales Development Representative', + 'company': 'Northwind Cloud', + 'timezone': 'America/New_York', + 'signature': '

Best regards,
Alex Morgan
Northwind Cloud

', + }, + 'folders': [ + {'id': 'folder-inbox', 'displayName': 'Inbox', 'parentFolderId': None, 'wellKnownName': 'inbox', 'totalItemCount': 3, 'unreadItemCount': 1, 'isSystem': True, 'icon': 'inbox', 'childFolders': [], 'isFavorite': True}, + {'id': 'folder-drafts', 'displayName': 'Drafts', 'parentFolderId': None, 'wellKnownName': 'drafts', 'totalItemCount': 0, 'unreadItemCount': 0, 'isSystem': True, 'icon': 'drafts', 'childFolders': [], 'isFavorite': False}, + {'id': 'folder-sentitems', 'displayName': 'Sent Items', 'parentFolderId': None, 'wellKnownName': 'sentitems', 'totalItemCount': 2, 'unreadItemCount': 0, 'isSystem': True, 'icon': 'send', 'childFolders': [], 'isFavorite': False}, + {'id': 'folder-archive', 'displayName': 'Archive', 'parentFolderId': None, 'wellKnownName': 'archive', 'totalItemCount': 0, 'unreadItemCount': 0, 'isSystem': True, 'icon': 'archive', 'childFolders': [], 'isFavorite': False}, + {'id': 'folder-deleteditems', 'displayName': 'Deleted Items', 'parentFolderId': None, 'wellKnownName': 'deleteditems', 'totalItemCount': 0, 'unreadItemCount': 0, 'isSystem': True, 'icon': 'trash', 'childFolders': [], 'isFavorite': False}, + {'id': 'folder-junkemail', 'displayName': 'Junk Email', 'parentFolderId': None, 'wellKnownName': 'junkemail', 'totalItemCount': 0, 'unreadItemCount': 0, 'isSystem': True, 'icon': 'warning', 'childFolders': [], 'isFavorite': False}, + ], + 'messages': [ + msg('msg-001', 'folder-inbox', 'Outreach targets for this week', + 'Hi Alex,\n\nHere are the prospects to prioritize this week. Focus on the uncontacted ones assigned to you.\n\nThanks,\nPriya', + {'name': 'Priya Nair', 'email': 'priya.nair@northwindcloud.com'}, + [alex], '2026-06-23T09:00:00.000Z'), + msg('msg-002', 'folder-inbox', 'Re: Intro from Northwind Cloud', + 'Thanks for reaching out, Alex. Happy to chat next week.\n\nMarcus', + {'name': 'Marcus Webb', 'email': 'marcus.webb@apexlogistics.com'}, + [alex], '2026-06-19T14:30:00.000Z'), + msg('msg-003', 'folder-inbox', 'Q3 campaign assets are ready', + 'The new one-pager and deck are in the shared drive.\n\nMarketing Team', + {'name': 'Northwind Marketing', 'email': 'marketing@northwindcloud.com'}, + [alex], '2026-06-18T11:15:00.000Z', is_read=False), + # Sent items: only unrelated prior outreach, none to Dana Cole or Owen Pratt. + msg('msg-011', 'folder-sentitems', 'Quick intro from Northwind Cloud', + 'Hi Marcus,\n\nWanted to introduce myself and Northwind Cloud.\n\nBest,\nAlex', + alex, [{'name': 'Marcus Webb', 'email': 'marcus.webb@apexlogistics.com'}], + '2026-06-18T10:05:00.000Z'), + msg('msg-012', 'folder-sentitems', 'Following up on our call', + 'Hi Hannah,\n\nGreat speaking with you earlier.\n\nBest,\nAlex', + alex, [{'name': 'Hannah Liu', 'email': 'hannah.liu@cedarfinancial.com'}], + '2026-06-15T16:20:00.000Z'), + ], + 'calendars': [ + {'id': 'cal-default', 'name': 'Calendar', 'color': '#0078D4', 'isDefault': True, 'isVisible': True, 'canEdit': True}, + ], + 'events': [], + 'contacts': [ + {'id': 'contact-dana', 'displayName': 'Dana Cole', 'givenName': 'Dana', 'surname': 'Cole', 'emailAddresses': [{'address': 'dana.cole@riverstonemedia.com', 'name': 'Dana Cole'}], 'businessPhones': ['555-2401'], 'mobilePhone': None, 'homePhones': [], 'jobTitle': 'Head of Marketing', 'companyName': 'Riverstone Media', 'department': None, 'officeLocation': None, 'businessAddress': None, 'homeAddress': None, 'birthday': None, 'personalNotes': '', 'initials': 'DC', 'avatarColor': '#0078D4', 'isFavorite': False, 'categories': []}, + {'id': 'contact-owen', 'displayName': 'Owen Pratt', 'givenName': 'Owen', 'surname': 'Pratt', 'emailAddresses': [{'address': 'owen.pratt@lumirabiotech.com', 'name': 'Owen Pratt'}], 'businessPhones': ['555-3117'], 'mobilePhone': None, 'homePhones': [], 'jobTitle': 'Procurement Lead', 'companyName': 'Lumira Biotech', 'department': None, 'officeLocation': None, 'businessAddress': None, 'homeAddress': None, 'birthday': None, 'personalNotes': '', 'initials': 'OP', 'avatarColor': '#107C10', 'isFavorite': False, 'categories': []}, + {'id': 'contact-priya', 'displayName': 'Priya Nair', 'givenName': 'Priya', 'surname': 'Nair', 'emailAddresses': [{'address': 'priya.nair@northwindcloud.com', 'name': 'Priya Nair'}], 'businessPhones': ['555-0100'], 'mobilePhone': None, 'homePhones': [], 'jobTitle': 'Sales Manager', 'companyName': 'Northwind Cloud', 'department': None, 'officeLocation': None, 'businessAddress': None, 'homeAddress': None, 'birthday': None, 'personalNotes': '', 'initials': 'PN', 'avatarColor': '#8764B8', 'isFavorite': True, 'categories': []}, + ], + 'categories': [ + {'id': 'cat-blue', 'displayName': 'Blue category', 'color': '#0078D4', 'presetIndex': 0}, + {'id': 'cat-green', 'displayName': 'Green category', 'color': '#107C10', 'presetIndex': 1}, + {'id': 'cat-orange', 'displayName': 'Orange category', 'color': '#FF8C00', 'presetIndex': 2}, + {'id': 'cat-red', 'displayName': 'Red category', 'color': '#D13438', 'presetIndex': 3}, + ], + 'settings': { + 'readingPanePosition': 'right', + 'density': 'medium', + 'conversationView': True, + 'focusedInbox': True, + 'autoReply': {'enabled': False, 'internalMessage': '', 'externalMessage': ''}, + 'signature': {'name': 'Default Signature', 'html': '

Best regards,
Alex Morgan
Northwind Cloud

', 'useForNew': True, 'useForReply': False}, + 'theme': 'light', + 'previewText': True, + 'weekStart': 'Sunday', + 'workingHours': {'start': '08:00', 'end': '17:00', 'days': [1, 2, 3, 4, 5]}, + }, + 'tasks': [ + {'id': 'task-outreach', 'title': 'Work through outreach list', 'dueDate': '2026-06-24T17:00:00.000Z', 'completed': False, 'importance': 'high', 'categories': []}, + {'id': 'task-hubspot', 'title': 'Update HubSpot lead statuses', 'dueDate': '2026-06-24T17:00:00.000Z', 'completed': False, 'importance': 'normal', 'categories': []}, + ], + 'selectedFolderId': 'folder-inbox', + 'selectedMessageId': None, + 'selectedModule': 'mail', + 'calendarView': 'month', + 'calendarDate': '2026-06-24T00:00:00.000Z', + 'searchQuery': '', + 'composeState': None, + 'settingsOpen': False, + 'settingsSection': 'accounts', + 'folderPaneCollapsed': False, + } + + +outlook_state = build_outlook_state() + +# =========================================================================== +# 3) HUBSPOT — full state (all top-level keys required, else the app +# reinitializes to defaults on browser load). Dana Cole (c1) & Owen Pratt +# (c2) leadStatus 'new' + distractor contacts. +# =========================================================================== +hubspot_contacts = [ + { + 'id': 'c1', 'firstName': 'Dana', 'lastName': 'Cole', + 'email': 'dana.cole@riverstonemedia.com', 'phone': '+1 (555) 240-1180', + 'jobTitle': 'Head of Marketing', 'companyId': 'comp1', + 'lifecycleStage': 'lead', 'leadStatus': 'new', 'owner': 'Alex Morgan', + 'city': 'Austin', 'state': 'TX', 'country': 'United States', + 'createDate': '2026-06-01T10:00:00Z', 'lastActivityDate': '2026-06-01T10:00:00Z', + 'timeline': [], + }, + { + 'id': 'c2', 'firstName': 'Owen', 'lastName': 'Pratt', + 'email': 'owen.pratt@lumirabiotech.com', 'phone': '+1 (555) 311-7742', + 'jobTitle': 'Procurement Lead', 'companyId': 'comp2', + 'lifecycleStage': 'lead', 'leadStatus': 'new', 'owner': 'Alex Morgan', + 'city': 'Boston', 'state': 'MA', 'country': 'United States', + 'createDate': '2026-06-02T11:00:00Z', 'lastActivityDate': '2026-06-02T11:00:00Z', + 'timeline': [], + }, + # --- distractor contacts (must remain unmodified) --- + { + 'id': 'c3', 'firstName': 'Marcus', 'lastName': 'Webb', + 'email': 'marcus.webb@apexlogistics.com', 'phone': '+1 (555) 412-9920', + 'jobTitle': 'VP Operations', 'companyId': 'comp3', + 'lifecycleStage': 'sql', 'leadStatus': 'connected', 'owner': 'Alex Morgan', + 'city': 'Denver', 'state': 'CO', 'country': 'United States', + 'createDate': '2026-05-20T09:00:00Z', 'lastActivityDate': '2026-06-18T14:00:00Z', + 'timeline': [], + }, + { + 'id': 'c4', 'firstName': 'Raj', 'lastName': 'Patel', + 'email': 'raj@foundryx.com', 'phone': '+1 (555) 778-3301', + 'jobTitle': 'Engineering Lead', 'companyId': 'comp4', + 'lifecycleStage': 'lead', 'leadStatus': 'new', 'owner': 'Jordan Kim', + 'city': 'Seattle', 'state': 'WA', 'country': 'United States', + 'createDate': '2026-06-03T08:30:00Z', 'lastActivityDate': '2026-06-03T08:30:00Z', + 'timeline': [], + }, + { + 'id': 'c5', 'firstName': 'Hannah', 'lastName': 'Liu', + 'email': 'hannah.liu@cedarfinancial.com', 'phone': '+1 (555) 660-1234', + 'jobTitle': 'CFO', 'companyId': 'comp5', + 'lifecycleStage': 'opportunity', 'leadStatus': 'open_deal', 'owner': 'Alex Morgan', + 'city': 'Chicago', 'state': 'IL', 'country': 'United States', + 'createDate': '2026-05-10T10:00:00Z', 'lastActivityDate': '2026-06-15T16:00:00Z', + 'timeline': [], + }, + { + 'id': 'c6', 'firstName': 'Sofia', 'lastName': 'Reyes', + 'email': 'sofia.reyes@northpeakretail.com', 'phone': '+1 (555) 902-4456', + 'jobTitle': 'Director of Sales', 'companyId': 'comp6', + 'lifecycleStage': 'mql', 'leadStatus': 'open', 'owner': 'Alex Morgan', + 'city': 'Portland', 'state': 'OR', 'country': 'United States', + 'createDate': '2026-05-28T13:00:00Z', 'lastActivityDate': '2026-06-17T12:00:00Z', + 'timeline': [], + }, +] + +HUBSPOT_COMPANIES = [ + {'id': 'comp1', 'name': 'Riverstone Media', 'domain': 'riverstonemedia.com', 'industry': 'Marketing', 'phone': '+1 (555) 240-1000', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'numberOfEmployees': 120, 'annualRevenue': 8000000, 'lifecycleStage': 'lead', 'owner': 'Alex Morgan', 'description': 'Boutique media and advertising agency', 'createDate': '2026-05-01T09:00:00Z'}, + {'id': 'comp2', 'name': 'Lumira Biotech', 'domain': 'lumirabiotech.com', 'industry': 'Healthcare', 'phone': '+1 (555) 311-7000', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'numberOfEmployees': 340, 'annualRevenue': 42000000, 'lifecycleStage': 'lead', 'owner': 'Alex Morgan', 'description': 'Clinical-stage biotechnology company', 'createDate': '2026-05-02T09:00:00Z'}, + {'id': 'comp3', 'name': 'Apex Logistics', 'domain': 'apexlogistics.com', 'industry': 'Other', 'phone': '+1 (555) 412-9000', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'numberOfEmployees': 600, 'annualRevenue': 75000000, 'lifecycleStage': 'sql', 'owner': 'Alex Morgan', 'description': 'Freight and supply-chain logistics', 'createDate': '2026-04-20T09:00:00Z'}, + {'id': 'comp4', 'name': 'FoundryX', 'domain': 'foundryx.com', 'industry': 'Technology', 'phone': '+1 (555) 778-3000', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'numberOfEmployees': 80, 'annualRevenue': 6000000, 'lifecycleStage': 'lead', 'owner': 'Jordan Kim', 'description': 'Developer tooling startup', 'createDate': '2026-05-03T09:00:00Z'}, + {'id': 'comp5', 'name': 'Cedar Financial', 'domain': 'cedarfinancial.com', 'industry': 'Finance', 'phone': '+1 (555) 660-1000', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'numberOfEmployees': 450, 'annualRevenue': 90000000, 'lifecycleStage': 'opportunity', 'owner': 'Alex Morgan', 'description': 'Mid-market financial advisory firm', 'createDate': '2026-04-10T09:00:00Z'}, + {'id': 'comp6', 'name': 'Northpeak Retail', 'domain': 'northpeakretail.com', 'industry': 'Other', 'phone': '+1 (555) 902-4000', 'city': 'Portland', 'state': 'OR', 'country': 'United States', 'numberOfEmployees': 210, 'annualRevenue': 30000000, 'lifecycleStage': 'mql', 'owner': 'Alex Morgan', 'description': 'Regional retail chain', 'createDate': '2026-04-28T09:00:00Z'}, +] + +HUBSPOT_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}, +} + +HUBSPOT_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}, +} + +hubspot_state = { + 'contacts': hubspot_contacts, + 'companies': HUBSPOT_COMPANIES, + 'deals': [], + 'tickets': [], + 'tasks': [], + 'notes': [], + 'templates': [], + 'emails': [], + 'meetings': [], + 'forms': [], + 'dealStages': HUBSPOT_DEAL_STAGES, + 'ticketStatuses': HUBSPOT_TICKET_STATUSES, + 'appState': { + 'sidebarOpen': True, + 'currentUser': {'name': 'Alex Morgan', 'email': 'alex.morgan@northwindcloud.com', 'avatar': None}, + }, +} + +# =========================================================================== +# Inject all three mocks with the SAME sid (action:"set") +# =========================================================================== +INJECT = { + 'google_sheets': sheets_state, + 'outlook_web': outlook_state, + 'hubspot': hubspot_state, +} + +for name, state in INJECT.items(): + url = MOCKS[name] + resp = SESSION.post( + f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + assert resp.status_code == 200, f'[{name}] State injection failed: {resp.status_code} {resp.text}' + go = SESSION.get(f'{url}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state') is not None, f'[{name}] initial_state is None after injection' + print(f'[{name}] state injected and verified (sid={sid})') + + +# =========================================================================== +# Launch browser (GUI-ready): open all three apps as tabs +# =========================================================================== +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 +chrome_proxy = f'--proxy-server={PROXY}' if PROXY else '' +urls = ' '.join(f'"{MOCKS[m]}/?sid={sid}"' for m in ['google_sheets', 'outlook_web', 'hubspot']) +launch_gui(f'google-chrome {urls}', delay_sec=3.0) +wait_mocks_loaded() +print(f'GUI_READY: launched Chrome with google_sheets, outlook_web, hubspot (sid={sid})') diff --git a/sdr_outreach_tracker_002/reward.py b/sdr_outreach_tracker_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..5010506900f5072d90156c36add48f1f25fff681 --- /dev/null +++ b/sdr_outreach_tracker_002/reward.py @@ -0,0 +1,503 @@ +# --- 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", "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 Outreach Tracker — cross-app outreach workflow +Task ID: sdr_outreach_tracker_002 +Domain: mock_websites (google_sheets_mock + outlook_web_mock + hubspot_mock) + +Scoring (task-introduced changes only; every component FAILS on initial_env): + - Outlook: two sent intro emails to the two qualifying prospects ...... 0.30 + (0.15 each: sent folder/status, non-draft, correct recipient, equivalent + intro subject, non-empty intro body) + - Google Sheets: rows for Dana Cole & Owen Pratt marked Contacted ..... 0.40 + (0.20 each: Status equivalent to 'Contacted' AND Last Contacted is + the fixed instruction date 2026-06-24 AND green bg on status cell) + Gated by negative constraint: skipped rows (Nina Vega row, Raj Patel row) + must remain 'Not Contacted' with no green fill — violating this zeroes the + Sheets score (prevents crediting indiscriminate edits). + - HubSpot: Dana Cole & Owen Pratt leadStatus='attempted' ............... 0.30 + (0.15 each) + Total: 1.0 +""" +import os +import sys +import json +import re +from datetime import datetime + +import requests + +# --------------------------------------------------------------------------- +# Read sid +# --------------------------------------------------------------------------- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +MOCKS = { + 'google_sheets': 'http://28.7.184.198:8145', + 'outlook': 'http://28.7.184.198:8168', + 'hubspot': 'http://28.7.184.198:8150', +} + +# --------------------------------------------------------------------------- +# HTTP client +# --------------------------------------------------------------------------- +SESSION = requests.Session() +SESSION.trust_env = False + +# --------------------------------------------------------------------------- +# Fetch state from all three mocks +# --------------------------------------------------------------------------- +states = {} +for name, url in MOCKS.items(): + try: + resp = SESSION.get(f'{url}/go?sid={sid}', timeout=15) + resp.raise_for_status() + states[name] = resp.json() + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {name} ({url}): {e}') + print('REWARD: 0.0') + sys.exit(0) + +# --------------------------------------------------------------------------- +# Constants derived from task description (ground truth) +# --------------------------------------------------------------------------- +DANA_EMAIL = 'dana.cole@riverstonemedia.com' +OWEN_EMAIL = 'owen.pratt@lumirabiotech.com' +TARGET_EMAILS = [DANA_EMAIL, OWEN_EMAIL] +TODAY = '2026-06-24' +EXPECTED_OUTLOOK_SUBJECT = 'Intro from Northwind Cloud' + +# Skipped rows (negative constraint) — must NOT be modified +SKIP_NINA_NAME = 'Nina Vega' # owner Alex Morgan, but email blank +SKIP_RAJ_EMAIL = 'raj@foundryx.com' # Not Contacted, but owner Jordan Kim + + +def normalize_text(value): + """Normalize human-entered text for case/spacing/punctuation tolerant checks.""" + if value is None: + return '' + if isinstance(value, (dict, list)): + value = json.dumps(value, ensure_ascii=False) + text = str(value) + text = re.sub(r'<[^>]+>', ' ', text) + text = re.sub(r'&(?:nbsp|amp|lt|gt|quot);', ' ', text, flags=re.IGNORECASE) + text = re.sub(r'[^a-z0-9@._+-]+', ' ', text.lower()) + return ' '.join(text.split()) + + +def compact_text(value): + return re.sub(r'[^a-z0-9]+', '', normalize_text(value)) + + +def normalize_email(value): + return str(value or '').strip().lower() + + +def cell_value(cell_obj): + if isinstance(cell_obj, dict): + for key in ('value', 'computed', 'formattedValue', 'formula', 'text'): + if key in cell_obj and cell_obj.get(key) not in (None, ''): + return cell_obj.get(key) + return '' + return '' if cell_obj is None else cell_obj + + +def cell_bg(cell_obj): + if not isinstance(cell_obj, dict): + return None + style = cell_obj.get('style') or {} + if not isinstance(style, dict): + return None + for key in ('bg', 'backgroundColor', 'background', 'fill', 'fillColor'): + if style.get(key): + return style.get(key) + return None + + +def status_is_contacted(value): + compact = compact_text(value) + return compact in { + 'contacted', + 'contact', + 'emailed', + 'emailsent', + 'sent', + 'reachedout', + 'outreachsent', + 'attempted', + 'attemptedcontact', + 'attemptedtocontact', + } + + +def status_is_not_contacted(value): + compact = compact_text(value) + return compact in { + 'notcontacted', + 'uncontacted', + 'notyetcontacted', + 'none', + 'new', + 'nocontact', + } + + +def lead_status_is_attempted(value): + compact = compact_text(value) + return compact in { + 'attempted', + 'attemptedcontact', + 'attemptedtocontact', + 'triedtocontact', + } + + +def get_nested_field(obj, field_names): + if not isinstance(obj, dict): + return '' + for field in field_names: + if obj.get(field) not in (None, ''): + return obj.get(field) + props = obj.get('properties') or {} + if isinstance(props, dict): + for field in field_names: + value = props.get(field) + if isinstance(value, dict): + value = value.get('value') or value.get('label') + if value not in (None, ''): + return value + return '' + + +def date_matches_expected(value): + raw = str(value or '').strip() + if not raw: + return False + if raw[:10] == TODAY: + return True + expected = datetime.strptime(TODAY, '%Y-%m-%d').date() + cleaned = re.sub(r'(\d+)(st|nd|rd|th)\b', r'\1', raw.strip(), flags=re.IGNORECASE) + cleaned = cleaned.replace(',', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned) + for fmt in ( + '%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', + '%m/%d/%Y', '%m/%d/%y', '%m-%d-%Y', '%m-%d-%y', + '%B %d %Y', '%b %d %Y', '%d %B %Y', '%d %b %Y', + ): + try: + return datetime.strptime(cleaned, fmt).date() == expected + except ValueError: + pass + try: + return datetime.fromisoformat(raw.replace('Z', '+00:00')).date() == expected + except ValueError: + return False + + +def is_green(hex_str): + """Return True if the hex color is a 'green' fill (green channel dominant).""" + if not hex_str or not isinstance(hex_str, str): + return False + normalized = normalize_text(hex_str) + if normalized in {'green', 'lightgreen', 'lime', 'darkgreen'}: + return True + rgb_match = re.search(r'rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)', hex_str, re.IGNORECASE) + if rgb_match: + r, g, b = (int(x) for x in rgb_match.groups()) + return g >= 100 and g > r and g > b + s = hex_str.strip().lstrip('#') + if len(s) != 6: + return False + try: + r = int(s[0:2], 16) + g = int(s[2:4], 16) + b = int(s[4:6], 16) + except ValueError: + return False + # Green dominant: reasonably strong green, clearly greater than red and blue. + return g >= 100 and g > r and g > b + + +def verify_task(): + total_score = 0.0 + + # ===================================================================== + # Locate the Prospects sheet (Google Sheets) + # ===================================================================== + gs_cur = states['google_sheets'].get('current_state') or {} + sheet_data = {} + try: + for sh in gs_cur.get('sheets', []): + if sh.get('name') == 'Prospects': + sheet_data = sh.get('data', {}) or {} + break + if not sheet_data and gs_cur.get('sheets'): + sheet_data = gs_cur['sheets'][0].get('data', {}) or {} + except Exception as e: + print(f'ERROR: Could not load Prospects sheet: {e}') + + def column_letters(): + for code in range(ord('A'), ord('Z') + 1): + yield chr(code) + + def find_col(header_names, default_col): + targets = {compact_text(name) for name in header_names} + for col in column_letters(): + if compact_text(cell_value(sheet_data.get(f'{col}1'))) in targets: + return col + return default_col + + name_col = find_col(('Name', 'Prospect', 'Contact Name'), 'A') + email_col = find_col(('Email', 'Email Address', 'Contact Email'), 'D') + status_col = find_col(('Status', 'Outreach Status'), 'E') + last_contacted_col = find_col(('Last Contacted', 'Last Contact Date', 'Contacted Date'), 'F') + + def find_row_by_email(email): + for r in range(2, 60): + candidates = [sheet_data.get(f'{email_col}{r}')] + candidates.extend(sheet_data.get(f'{col}{r}') for col in column_letters()) + for cell in candidates: + if normalize_email(cell_value(cell)) == email.lower(): + return r + return None + + def find_row_by_name(name): + target = compact_text(name) + for r in range(2, 60): + candidates = [sheet_data.get(f'{name_col}{r}')] + candidates.extend(sheet_data.get(f'{col}{r}') for col in column_letters()) + for cell in candidates: + if compact_text(cell_value(cell)) == target: + return r + return None + + # --------------------------------------------------------------------- + # NEGATIVE-CONSTRAINT GATE: skipped rows must remain untouched. + # (Passes on BOTH initial and golden, so it is a gate, not a scored item.) + # If a skipped row was wrongly marked Contacted / given a green fill, the + # Sheets work is considered incorrect and earns no Sheets credit. + # --------------------------------------------------------------------- + gate_violations = [] + try: + for label, finder in [ + ('Nina Vega', find_row_by_name(SKIP_NINA_NAME)), + ('Raj Patel', find_row_by_email(SKIP_RAJ_EMAIL)), + ]: + r = finder + if r is None: + print(f'WARN: skipped row {label} not found (cannot verify negative constraint)') + continue + e_cell = sheet_data.get(f'{status_col}{r}') or {} + status = str(cell_value(e_cell)).strip() + bg = cell_bg(e_cell) + if not status_is_not_contacted(status) or is_green(bg): + print(f'GATE FAIL: skipped row {label} (row {r}) was modified ' + f'(status={status!r}, bg={bg!r}) — should stay Not Contacted, no green') + gate_violations.append(label) + else: + print(f'GATE OK: skipped row {label} (row {r}) unchanged ' + f'(status={status!r}, bg={bg!r})') + except Exception as e: + print(f'ERROR: negative-constraint gate — {e}') + sheets_gate_ok = (len(gate_violations) == 0) + + # --------------------------------------------------------------------- + # Component A (0.40): Google Sheets — Dana & Owen rows marked Contacted + # 0.20 each: Status='Contacted' AND Last Contacted=TODAY AND green bg. + # --------------------------------------------------------------------- + for who, email in [('Dana Cole', DANA_EMAIL), ('Owen Pratt', OWEN_EMAIL)]: + try: + r = find_row_by_email(email) + if r is None: + print(f'FAIL: Sheets — row for {who} ({email}) not found') + continue + e_cell = sheet_data.get(f'{status_col}{r}') or {} + f_cell = sheet_data.get(f'{last_contacted_col}{r}') or {} + status = str(cell_value(e_cell)).strip() + bg = cell_bg(e_cell) + last_contacted = str(cell_value(f_cell)).strip() + + status_ok = status_is_contacted(status) + date_ok = date_matches_expected(last_contacted) + green_ok = is_green(bg) + + if not sheets_gate_ok: + print(f'FAIL: Sheets — {who} row {r}: negative-constraint gate failed, ' + f'Sheets credit withheld') + elif status_ok and date_ok and green_ok: + print(f'PASS: Sheets — {who} row {r}: Status=Contacted, ' + f'Last Contacted={last_contacted}, green bg={bg} (0.20 pts)') + total_score += 0.20 + else: + print(f'FAIL: Sheets — {who} row {r}: status_ok={status_ok}({status!r}), ' + f'date_ok={date_ok}({last_contacted!r}), green_ok={green_ok}({bg!r})') + except Exception as e: + print(f'ERROR: Sheets component for {who} — {e}') + + # --------------------------------------------------------------------- + # Component B (0.30): Outlook — two sent intro emails to the targets + # 0.15 each: sent folder/status, non-draft, correct recipient, equivalent + # intro subject, non-empty body. + # --------------------------------------------------------------------- + ol_cur = states['outlook'].get('current_state') or {} + emails = ol_cur.get('messages') or ol_cur.get('emails') or ol_cur.get('mail') or [] + + sent_folder_ids = {'folder-sentitems', 'sent', 'sentitems', 'sent items'} + for folder in ol_cur.get('folders', []) or []: + folder_tokens = { + normalize_text(folder.get('id')), + normalize_text(folder.get('wellKnownName')), + normalize_text(folder.get('displayName')), + normalize_text(folder.get('name')), + } + if {'sent', 'sentitems', 'sent items'} & folder_tokens: + sent_folder_ids.add(normalize_text(folder.get('id'))) + + def sent_folder_id(message): + folder = message.get('parentFolderId') or message.get('folderId') or message.get('folder') + if isinstance(folder, dict): + return ( + folder.get('id') or folder.get('wellKnownName') or + folder.get('displayName') or folder.get('name') + ) + return folder + + def is_sent_message(message): + folder_id = normalize_text(sent_folder_id(message)) + if folder_id in sent_folder_ids: + return True + if str(message.get('isSent', '')).strip().lower() == 'true': + return True + return bool(message.get('sentDateTime') or message.get('sentAt')) and message.get('isDraft') is not True + + def recipient_addresses(message): + recipients = message.get('toRecipients') + if recipients is None: + recipients = message.get('to') + if recipients is None: + recipients = message.get('recipients', []) + if isinstance(recipients, str): + recipients = re.split(r'[,;]\s*', recipients) + if isinstance(recipients, dict): + recipients = [recipients] + + addresses = [] + for recipient in (recipients or []): + if isinstance(recipient, str): + addresses.append(normalize_email(recipient)) + continue + if not isinstance(recipient, dict): + continue + email_obj = recipient.get('emailAddress') + if isinstance(email_obj, dict): + addresses.append(normalize_email(email_obj.get('address') or email_obj.get('email'))) + addresses.append(normalize_email( + recipient.get('email') or recipient.get('address') or recipient.get('value') + )) + return [addr for addr in addresses if addr] + + def body_text(message): + body = message.get('body') + if isinstance(body, dict): + body = body.get('content') or body.get('text') or body.get('html') or '' + if not body: + body = message.get('bodyPreview') or message.get('preview') or '' + return str(body or '') + + def subject_matches_intro(subject): + compact = compact_text(subject) + accepted = { + compact_text(EXPECTED_OUTLOOK_SUBJECT), + 'introductionfromnorthwindcloud', + 'introtonorthwindcloud', + } + if compact in accepted: + return True + normalized = normalize_text(subject) + return ( + 'northwind' in normalized and + 'cloud' in normalized and + any(token in normalized for token in ('intro', 'introduction', 'introducing')) + ) + + for who, email in [('Dana Cole', DANA_EMAIL), ('Owen Pratt', OWEN_EMAIL)]: + try: + matches = [] + for m in emails: + if not is_sent_message(m): + continue + if m.get('isDraft') is True: + continue + if email.lower() in recipient_addresses(m): + matches.append(m) + good = None + for m in matches: + subject_ok = subject_matches_intro(m.get('subject', '')) + body_ok = len(normalize_text(body_text(m))) >= 5 + if subject_ok and body_ok: + good = m + break + if good is not None: + print(f'PASS: Outlook — sent intro email to {who} ({email}), ' + f'subject={good.get("subject")!r} (0.15 pts)') + total_score += 0.15 + elif matches: + print(f'FAIL: Outlook — email to {who} exists but subject/body check failed; ' + f'expected subject={EXPECTED_OUTLOOK_SUBJECT!r}') + else: + print(f'FAIL: Outlook — no sent non-draft email to {who} ({email})') + except Exception as e: + print(f'ERROR: Outlook component for {who} — {e}') + + # --------------------------------------------------------------------- + # Component C (0.30): HubSpot — Dana & Owen leadStatus='attempted' + # 0.15 each. + # --------------------------------------------------------------------- + hs_cur = states['hubspot'].get('current_state') or {} + contacts = hs_cur.get('contacts', []) or [] + for who, email in [('Dana Cole', DANA_EMAIL), ('Owen Pratt', OWEN_EMAIL)]: + try: + found = None + for c in contacts: + c_email = normalize_email(get_nested_field(c, ('email', 'emailAddress', 'contactEmail'))) + first = get_nested_field(c, ('firstName', 'first_name', 'firstname')) + last = get_nested_field(c, ('lastName', 'last_name', 'lastname')) + full_name = get_nested_field(c, ('name', 'fullName', 'displayName')) or f'{first} {last}' + if c_email == email.lower() or compact_text(full_name) == compact_text(who): + found = c + break + if found is None: + print(f'FAIL: HubSpot — contact {who} ({email}) not found') + continue + ls = get_nested_field(found, ('leadStatus', 'lead_status', 'leadstatus', 'status')) + if lead_status_is_attempted(ls): + print(f'PASS: HubSpot — {who} leadStatus=attempted (0.15 pts)') + total_score += 0.15 + else: + print(f'FAIL: HubSpot — {who} leadStatus={ls!r}, expected "attempted"') + except Exception as e: + print(f'ERROR: HubSpot component for {who} — {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_outreach_tracker_002/reward_label.json b/sdr_outreach_tracker_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..7e3be858b1f363d43876e3ef2e0fc57632131eaa --- /dev/null +++ b/sdr_outreach_tracker_002/reward_label.json @@ -0,0 +1,56 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/sdr_outreach_tracker_004/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:11", + "label": { + "task_id": "sdr_outreach_tracker_002", + "domain": "mock_websites", + "summary": "验证跨应用SDR外联工作流:在Outlook向两名目标潜在客户发送介绍邮件、在Google Sheets将对应行标记为已联系并填充绿色背景及更新最后联系日期、在HubSpot将线索状态设为attempted,同时确保未要求联系的行不被修改。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_sheets_mock (http://28.7.186.212:8165)", + "outlook_web_mock (http://28.7.186.212:8188)", + "hubspot_mock (http://28.7.186.212:8170)" + ], + "scoring_components": [ + { + "name": "Component A - Google Sheets", + "weight": 0.4, + "description": "检查Dana Cole和Owen Pratt在Prospects表格中的行是否被正确标记为已联系", + "check_logic": "通过邮箱定位行,检查status_col单元格的值是否被识别为'Contacted'(compact_text匹配多种等价写法如contacted/emailed/sent等),last_contacted_col是否为2026-06-24(支持多种日期格式解析),以及status单元格背景是否为绿色(green channel dominant,hex或rgb中g≥100且g>r,b)。设有negative-constraint gate:Nina Vega(按姓名)和Raj Patel(按邮箱raj@foundryx.com)对应的行必须保持Not Contacted(compact_text匹配notcontacted/new/none等)且不能有绿色背景,否则sheets_gate_ok为False,整个Sheets组件得0分。", + "pass_condition": "gate通过,且Dana和Owen各自满足:status为Contacted、Last Contacted为2026-06-24、status单元格绿色背景" + }, + { + "name": "Component B - Outlook", + "weight": 0.3, + "description": "检查是否向两名目标潜在客户发送了介绍邮件", + "check_logic": "遍历Outlook邮件列表,筛选位于sent文件夹(通过parentFolderId/folderId/wellKnownName/displayName等匹配sent/sentitems,或isSent为true,或存在sentDateTime且isDraft不为True)且非草稿的邮件。检查收件人地址(toRecipients/to/recipients中解析emailAddress.address等)是否包含目标邮箱。主题需匹配'Intro from Northwind Cloud'(compact_text完全匹配或包含northwind+cloud+intro/introduction/introducing语义)。邮件正文(body.content/bodyPreview等)normalize_text后长度≥5。", + "pass_condition": "每封邮件满足:已发送、非草稿、收件人地址正确、主题匹配介绍语义、正文非空" + }, + { + "name": "Component C - HubSpot", + "weight": 0.3, + "description": "检查HubSpot中两名目标联系人的leadStatus是否为attempted", + "check_logic": "在contacts列表中通过邮箱(email/emailAddress/contactEmail)或姓名(firstName+lastName/name/fullName)匹配Dana Cole和Owen Pratt。读取leadStatus字段(支持leadStatus/lead_status/leadstatus/status,优先从对象属性或properties嵌套字典中获取),检查compact_text后是否为attempted及其等价写法(attemptedcontact/attemptedtocontact/triedtocontact)。", + "pass_condition": "两名联系人的leadStatus均被设置为attempted" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各子项分数累加(Dana/Owen在三个组件中分别计0.20、0.15、0.15分),最终通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数", + "failure_modes": [ + "读取/tmp/task_web_sid失败或为空:打印CRITICAL并返回0.0后sys.exit(0)", + "从任一mock服务(google_sheets/outlook/hubspot)拉取状态失败:打印CRITICAL并返回0.0后sys.exit(0)", + "Negative-constraint gate失败(Nina Vega或Raj Patel的行被改为Contacted或添加了绿色背景):Sheets组件总分为0,但其他组件仍可能得分", + "在Google Sheets中找不到目标邮箱对应的行:该0.20子项不得分", + "在Outlook中找不到符合条件的已发送邮件:该0.15子项不得分", + "在HubSpot中找不到目标联系人:该0.15子项不得分", + "主题、正文、日期、状态、背景色任一检查不通过:对应子项不得分" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向三个mock服务(google_sheets、outlook、hubspot)拉取当前状态。接着在Google Sheets的Prospects工作表中动态定位Name、Email、Status、Last Contacted列(通过第一行表头匹配)。先执行negative-constraint gate:检查Nina Vega和Raj Patel对应的行是否保持Not Contacted且无绿色背景,若任一被修改则gate失败,sheets_gate_ok设为False。随后对Dana Cole和Owen Pratt分别检查:若gate通过且status为Contacted、Last Contacted为2026-06-24、status单元格为绿色,则各加0.20分;若gate失败则两人均不得分。之后检查Outlook:在已发送邮件中查找发给两名目标邮箱、主题为Intro from Northwind Cloud(或语义等价)、正文非空的邮件,每封通过加0.15分。最后检查HubSpot:查找两名联系人并确认leadStatus为attempted,每人通过加0.15分。最终总分累加后通过min函数钳制在1.0以内,四舍五入到4位小数后输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取关键信息:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: sdr_outreach_tracker_004`\n2. **Domain**: `Domain: mock_websites (google_sheets_mock + outlook_web_mock + hubspot_mock)`,所以 domain 是 `mock_websites`\n3. **Summary**: 这是一个跨应用的外联工作流评分脚本,验证在 Outlook 发送邮件、Google Sheets 更新状态、HubSpot 更新线索状态\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `google_sheets` mock (http://28.7.186.212:8165)\n - `outlook` mock (http://28.7.186.212:8188)\n - `hubspot` mock (http://28.7.186.212:8170)\n\n6. **Scoring components**:\n - Component A (Google Sheets): 0.40 total, 0.20 each for Dana Cole & Owen Pratt. 检查 Status='Contacted' (或等价), Last Contacted='2026-06-24', green background. 但有 negative constraint gate: Nina Vega 和 Raj Patel 必须保持 'Not Contacted' 且没有绿色背景,否则整个 Sheets 分数为 0。\n - Component B (Outlook): 0.30 total, 0.15 each. 检查 sent folder, non-draft, correct recipient, intro subject (包含 Northwind Cloud intro), non-empty body.\n - Component C (HubSpot): 0.30 total, 0.15 each. 检查 leadStatus='attempted' for Dana & Owen.\n\n7. **Score aggregation**: 各组件分数相加,最后 `min(total_score, 1.0)` 并四舍五入到4位小数。\n\n8. **Failure modes**:\n - 读取 /tmp/task_web_sid 失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 从任何一个 mock 获取状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - Negative constraint gate 失败 -> Sheets 部分得 0 分(但其他组件仍可能得分)\n - 找不到对应行/联系人/邮件 -> 该子项失败\n - 各种检查条件不满足 -> 该子项不得分\n\n9. **Scoring logic explanation**: 需要按执行顺序详细说明。\n\n10. **Confidence**: 1.0,因为代码非常清晰。\n\n让我构建 JSON:\n\n- task_id: \"sdr_outreach_tracker_004\"\n- domain: \"mock_websites\"\n- summary: \"验证跨应用SDR外联工作流:在Outlook向两名目标潜在客户发送介绍邮件、在Google Sheets将对应行标记为已联系并填充绿色背景及更新最后联系日期、在HubSpot将线索状态设为attempted,同时确保未要求联系的行不被修改。\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"google_sheets_mock\", \"outlook_web_mock\", \"hubspot_mock\"]\n- scoring_components:\n 1. name: \"Component A - Google Sheets\", weight: 0.4, description: \"检查Dana Cole和Owen Pratt在Prospects表格中的行是否被正确标记为已联系\", check_logic: \"通过邮箱定位行,检查status_col单元格的值是否被识别为'Contacted'(使用compact_text匹配多种等价写法),last_contacted_col是否为2026-06-24(支持多种日期格式),以及status单元格背景是否为绿色(green channel dominant)。同时设有negative-constraint gate:Nina Vega和Raj Patel对应的行必须保持Not Contacted状态且不能有绿色背景,否则整个Sheets组件得0分。\", pass_condition: \"gate通过,且Dana和Owen各自满足status为Contacted、Last Contacted为2026-06-24、status单元格绿色背景\"\n 2. name: \"Component B - Outlook\", weight: 0.3, description: \"检查是否向两名目标潜在客户发送了介绍邮件\", check_logic: \"遍历Outlook邮件,筛选位于sent文件夹(通过parentFolderId/wellKnownName等判断)或非草稿且包含sentDateTime的邮件,检查收件人地址是否包含目标邮箱,主题是否匹配'Intro from Northwind Cloud'(或包含northwind+cloud+intro/introduction等价语义),且邮件正文非空(normalize_text后长度≥5)。\", pass_condition: \"每封邮件需满足:已发送、非草稿、收件人正确、主题匹配介绍、正文非空\"\n 3. name: \"Component C - HubSpot\", weight: 0.3, description: \"检查HubSpot中两名目标联系人的leadStatus是否为attempted\", check_logic: \"在contacts列表中通过邮箱或姓名匹配Dana Cole和Owen Pratt,读取leadStatus字段(支持leadStatus/lead_status/leadstatus/status等嵌套路径),检查compact_text后是否为attempted及其等价写法。\", pass_condition: \"两名联系人的leadStatus均被设置为attempted\"\n\n- total_max_score: 1.0\n- score_aggregation: \"各子项分数累加(Dana/Owen各自0.15/0.20/0.15),最终通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数\"\n- failure_modes: [\n \"读取/tmp/task_web_sid失败或为空:打印CRITICAL并返回0.0后退出\",\n \"从任一mock服务(google_sheets/outlook/hubspot)拉取状态失败:打印CRITICAL并返回0.0后退出\",\n \"Negative-constraint gate失败(Nina Vega或Raj Patel的行被改为Contacted或添加了绿色背景):Sheets组件总分为0\",\n \"找不到目标行、邮件或联系人:对应子项不得分\",\n \"主题、正文、日期、状态、背景色任一检查不通过:对应子项不得分\"\n ]\n- scoring_logic_explanation: \"脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向三个mock服务(google_sheets、outlook、hubspot)拉取当前状态。接着在Google Sheets的Prospects工作表中定位Name、Email、Status、Last Contacted列。先执行negative-constraint gate:检查Nina Vega和Raj Patel对应的行是否保持Not Contacted且无绿色背景,若失败则sheets_gate_ok为False。随后对Dana Cole和Owen Pratt分别检查:若gate通过且status为Contacted、Last Contacted为2026-06-24、status单元格为绿色,则各加0.20分。之后检查Outlook:在已发送邮件中查找发给两名目标邮箱、主题为Intro from Northwind Cloud(或语义等价)、正文非空的邮件,每封通过加0.15分。最后检查HubSpot:查找两名联系人并确认leadStatus为attempted,每人通过加0.15分。最终总分累加后钳制在1.0以内并输出。\"\n- confidence: 1.0\n\n我需要确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 },所有字符串 value 使用中文(但代码标识符保留原样)。\n\n让我再检查一下 weight 的分配:\n- Component A: 0.40 (0.20 each)\n- Component B: 0.30 (0.15 each)\n- Component C: 0.30 (0.15 each)\n\n在 JSON 中,weight 应该填组件的总权重。\n\n检查 check_logic 和 pass_condition 的细节:\n- Google Sheets: 0.20 each, total 0.40. gate失败则整个0.40拿不到。\n- Outlook: 0.15 each, total 0.30.\n- HubSpot: 0.15 each, total 0.30.\n\n所有要求都满足了。 {\"task_id\":\"sdr_outreach_tracker_004\",\"domain\":\"mock_websites\",\"summary\":\"验证跨应用SDR外联工作流:在Outlook向两名目标潜在客户发送介绍邮件、在Google Sheets将对应行标记为已联系并填充绿色背景及更新最后联系日期、在HubSpot将线索状态设为attempted,同时确保未要求联系的行不被修改。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock (http://28.7.186.212:8165)\",\"outlook_web_mock (http://28.7.186.212:8188)\",\"hubspot_mock (http://28.7.186.212:8170)\"],\"scoring_components\":[{\"name\":\"Component A - Google Sheets\",\"weight\":0.4,\"description\":\"检查Dana Cole和Owen Pratt在Prospects表格中的行是否被正确标记为已联系\",\"check_logic\":\"通过邮箱定位行,检查status_col单元格的值是否被识别为'Contacted'(compact_text匹配多种等价写法如contacted/emailed/sent等),last_contacted_col是否为2026-06-24(支持多种日期格式解析),以及status单元格背景是否为绿色(green channel dominant,hex或rgb中g≥100且g>r,b)。设有negative-constraint gate:Nina Vega(按姓名)和Raj Patel(按邮箱raj@foundryx.com)对应的行必须保持Not Contacted(compact_text匹配notcontacted/new/none等)且不能有绿色背景,否则sheets_gate_ok为False,整个Sheets组件得0分。\",\"pass_condition\":\"gate通过,且Dana和Owen各自满足:status为Contacted、Last Contacted为2026-06-24、status单元格绿色背景\"},{\"name\":\"Component B - Outlook\",\"weight\":0.3,\"description\":\"检查是否向两名目标潜在客户发送了介绍邮件\",\"check_logic\":\"遍历Outlook邮件列表,筛选位于sent文件夹(通过parentFolderId/folderId/wellKnownName/displayName等匹配sent/sentitems,或isSent为true,或存在sentDateTime且isDraft不为True)且非草稿的邮件。检查收件人地址(toRecipients/to/recipients中解析emailAddress.address等)是否包含目标邮箱。主题需匹配'Intro from Northwind Cloud'(compact_text完全匹配或包含northwind+cloud+intro/introduction/introducing语义)。邮件正文(body.content/bodyPreview等)normalize_text后长度≥5。\",\"pass_condition\":\"每封邮件满足:已发送、非草稿、收件人地址正确、主题匹配介绍语义、正文非空\"},{\"name\":\"Component C - HubSpot\",\"weight\":0.3,\"description\":\"检查HubSpot中两名目标联系人的leadStatus是否为attempted\",\"check_logic\":\"在contacts列表中通过邮箱(email/emailAddress/contactEmail)或姓名(firstName+lastName/name/fullName)匹配Dana Cole和Owen Pratt。读取leadStatus字段(支持leadStatus/lead_status/leadstatus/status,优先从对象属性或properties嵌套字典中获取),检查compact_text后是否为attempted及其等价写法(attemptedcontact/attemptedtocontact/triedtocontact)。\",\"pass_condition\":\"两名联系人的leadStatus均被设置为attempted\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各子项分数累加(Dana/Owen在三个组件中分别计0.20、0.15、0.15分),最终通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或为空:打印CRITICAL并返回0.0后sys.exit(0)\",\"从任一mock服务(google_sheets/outlook/hubspot)拉取状态失败:打印CRITICAL并返回0.0后sys.exit(0)\",\"Negative-constraint gate失败(Nina Vega或Raj Patel的行被改为Contacted或添加了绿色背景):Sheets组件总分为0,但其他组件仍可能得分\",\"在Google Sheets中找不到目标邮箱对应的行:该0.20子项不得分\",\"在Outlook中找不到符合条件的已发送邮件:该0.15子项不得分\",\"在HubSpot中找不到目标联系人:该0.15子项不得分\",\"主题、正文、日期、状态、背景色任一检查不通过:对应子项不得分\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向三个mock服务(google_sheets、outlook、hubspot)拉取当前状态。接着在Google Sheets的Prospects工作表中动态定位Name、Email、Status、Last Contacted列(通过第一行表头匹配)。先执行negative-constraint gate:检查Nina Vega和Raj Patel对应的行是否保持Not Contacted且无绿色背景,若任一被修改则gate失败,sheets_gate_ok设为False。随后对Dana Cole和Owen Pratt分别检查:若gate通过且status为Contacted、Last Contacted为2026-06-24、status单元格为绿色,则各加0.20分;若gate失败则两人均不得分。之后检查Outlook:在已发送邮件中查找发给两名目标邮箱、主题为Intro from Northwind Cloud(或语义等价)、正文非空的邮件,每封通过加0.15分。最后检查HubSpot:查找两名联系人并确认leadStatus为attempted,每人通过加0.15分。最终总分累加后通过min函数钳制在1.0以内,四舍五入到4位小数后输出。\",\"confidence\":1.0}" +}