diff --git a/ar_aging_001/_cua_gym_vm_bridge.sh b/ar_aging_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_aging_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/ar_aging_001/initial_setup.py b/ar_aging_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4571532d75265d5fbf1ab4726a574dceeaabce42 --- /dev/null +++ b/ar_aging_001/initial_setup.py @@ -0,0 +1,200 @@ +""" +Initial Setup: AR aging snapshot — build aging summary in Google Sheets + post to Slack #finance +Task ID: ar_aging_001 +Domain: mock_websites (google_sheets_mock + slack_mock) + +Pre-task state: + - Google Sheet 'AR Invoice Ledger' with 8 unpaid invoices (rows 2-9) plus a few + paid rows, fixed columns A..H. NO summary block below the data. + - Slack workspace with a #finance channel. NO AR aging message posted yet. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +SHEETS_URL = 'http://28.7.184.198:8145' +SLACK_URL = 'http://28.7.184.198:8178' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +# --------------------------------------------------------------------------- +# Google Sheets initial state — AR Invoice Ledger +# --------------------------------------------------------------------------- +def build_sheets_state(): + headers = ['Invoice #', 'Customer', 'Deal/Contract', 'Amount', + 'Issue Date', 'Due Date', 'Status', 'AE/Owner'] + # Invoice rows: (inv, customer, deal, amount, issue, due, status, owner) + rows = [ + ['INV-2998', 'Stark Industries', 'Renewal FY25', 52000, '2026-02-01', '2026-03-03', 'Paid', 'Diane Wu'], + ['INV-2999', 'Cyberdyne Systems', 'New Logo', 31000, '2026-02-10', '2026-03-12', 'Paid', 'Raj Patel'], + ['INV-3000', 'Pied Piper', 'Expansion', 18500, '2026-03-01', '2026-03-31', 'Paid', 'Diane Wu'], + ['INV-3001', 'Acme Corp', 'Platform Annual', 48000, '2026-06-10', '2026-07-10', 'Sent', 'Diane Wu'], + ['INV-3002', 'Globex Inc', 'Support Tier 2', 24000, '2026-05-16', '2026-06-15', 'Overdue', 'Raj Patel'], + ['INV-3003', 'Initech', 'Implementation', 72000, '2026-05-02', '2026-06-01', 'Overdue', 'Diane Wu'], + ['INV-3004', 'Umbrella Health', 'Enterprise Suite', 115000, '2026-04-20', '2026-05-20', 'Overdue', 'Maria Lopez'], + ['INV-3005', 'Soylent Foods', 'Data Add-on', 36500, '2026-04-10', '2026-05-10', 'Overdue', 'Raj Patel'], + ['INV-3006', 'Vandelay Industries', 'Pilot', 15000, '2026-03-16', '2026-04-15', 'Overdue', 'Maria Lopez'], + ['INV-3007', 'Wayne Enterprises', 'Security Bundle', 90000, '2026-06-01', '2026-07-01', 'Sent', 'Diane Wu'], + ['INV-3008', 'Hooli', 'Cloud Migration', 63000, '2026-03-02', '2026-04-01', 'Overdue', 'Maria Lopez'], + ] + + def col_letter(idx): # 0 -> A + return chr(ord('A') + idx) + + data = {} + # Header row (row 1), bold + light grey background + for c, h in enumerate(headers): + cell = f'{col_letter(c)}1' + data[cell] = { + 'value': h, 'formula': h, + 'style': {'bold': True, 'bg': '#E8EAED', 'align': 'center'}, + } + # Data rows (rows 2..) + for r, row in enumerate(rows, start=2): + for c, val in enumerate(row): + cell = f'{col_letter(c)}{r}' + entry = {'value': str(val), 'formula': str(val)} + if c == 3: # Amount column -> currency + entry['format'] = 'currency' + elif c in (4, 5): # Issue / Due Date + entry['format'] = 'date' + data[cell] = entry + + sheet = { + 'id': 'sheet_1', + 'name': 'AR Invoice Ledger', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {'0': 90, '1': 150, '2': 140, '3': 100, '4': 100, '5': 100, '6': 80, '7': 110}, + 'data': data, + } + + 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': [sheet], + } + + +# --------------------------------------------------------------------------- +# Slack initial state — workspace with #finance channel, no AR message yet +# --------------------------------------------------------------------------- +def build_slack_state(): + users = [ + {'userId': 'user_1', 'fullName': 'Diane Wu', 'displayName': 'Diane', + 'email': 'diane.wu@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': 'Maria Lopez', 'displayName': 'Maria', + 'email': 'maria.lopez@company.com', 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': 'Controller', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Raj Patel', 'displayName': 'Raj', + 'email': 'raj.patel@company.com', 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': 'CFO', 'status': 'away', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/Los_Angeles'}, + ] + current_user = dict(users[0]) + + channels = [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', + 'topic': '', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3'], + 'createdBy': 'user_3', 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'finance', 'name': 'finance', 'description': 'Finance team — AR, AP, reporting', + 'topic': 'Month-end close & receivables', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_3', + 'createdAt': '2026-01-02T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'random', 'name': 'random', 'description': 'Watercooler', + 'topic': '', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3'], + 'createdBy': 'user_1', 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ] + + messages = { + 'general': [ + {'messageId': 'msg_g1', 'senderId': 'user_3', + 'content': 'Reminder: finance review meeting Thursday at 2pm.', + 'timestamp': '2026-06-22T15:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + 'finance': [ + {'messageId': 'msg_f1', 'senderId': 'user_2', + 'content': 'Can someone pull the AR aging snapshot before the review?', + 'timestamp': '2026-06-23T16:20:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_f2', 'senderId': 'user_1', + 'content': 'On it — will post bucket totals and the worst offenders shortly.', + 'timestamp': '2026-06-23T16:25:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ], + 'random': [], + } + + return { + 'currentUser': current_user, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind Finance', '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): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'Inject failed for {url}: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=15).json() + assert go.get('initial_state') is not None, f'initial_state is None for {url}' + + +inject(SHEETS_URL, build_sheets_state()) +print(f'Google Sheets state injected: sid={sid}') +inject(SLACK_URL, build_slack_state()) +print(f'Slack state injected: sid={sid}') + + +# --------------------------------------------------------------------------- +# Launch browser (GUI-ready) — primary app is the Google Sheet +# --------------------------------------------------------------------------- +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 "{SLACK_URL}/?sid={sid}"', delay_sec=1.0) +print(f'GUI_READY: launched Chrome for Sheets and Slack with sid={sid}') diff --git a/ar_aging_001/reward.py b/ar_aging_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1080648b37602d608afc086dfc4ce8affd0ddd7b --- /dev/null +++ b/ar_aging_001/reward.py @@ -0,0 +1,226 @@ +""" +Reward Script: AR aging snapshot — Google Sheets summary block + Slack #finance post +Task ID: ar_aging_001 +Domain: mock_websites (google_sheets_mock + slack_mock) + +Task: classify unpaid invoices into aging buckets, write a labeled summary block +below the ledger data totaling each bucket, then post the top three overdue +customers and total outstanding in Slack #finance. + +Scoring (only task-introduced changes are scored; everything is derived from the +diff between initial_state and current_state of the SAME /go response, so the +initial_env — where current == initial — scores exactly 0.0): + + Google Sheets (0.50): + - 4 aging-bucket totals appear in cells added below the ledger ......... 0.30 (0.075 each) + Current=138000, 1-30=96000, 31-60=151500, 60+=78000 + - Total Outstanding (463500) appears in added cells .................... 0.20 + + Slack #finance (0.50): + - A new message was posted in #finance by user_1 ...................... 0.10 + - Message lists the top three overdue customers + their balances ..... 0.25 + Umbrella Health $115,000, Initech $72,000, Hooli $63,000 + - Message states the total outstanding of $463,500 ................... 0.15 + + Total = 1.0 +""" +import json +import re +import sys + +import requests + +GS_URL = 'http://28.7.184.198:8145' +SLACK_URL = 'http://28.7.184.198:8178' + +# Ground-truth values from task context +BUCKETS = { + 'Current': 138000.0, + '1-30': 96000.0, + '31-60': 151500.0, + '60+': 78000.0, +} +TOTAL_OUTSTANDING = 463500.0 +TOP3 = { + 'Umbrella Health': 115000.0, + 'Initech': 72000.0, + 'Hooli': 63000.0, +} + + +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): + """Fetch /go state for a mock. Returns (initial, current) or (None, None).""" + try: + resp = requests.get(f'{url}/go?sid={sid}', timeout=30) + resp.raise_for_status() + data = resp.json() + return data.get('initial_state'), data.get('current_state') + except Exception as e: + print(f'CRITICAL: cannot fetch {url}: {e}') + return None, None + + +def to_number(v): + """Parse a cell/text token into a float, stripping $ , and spaces. None if not numeric.""" + if v is None: + return None + s = str(v).strip().replace('$', '').replace(',', '').replace(' ', '') + if s == '': + return None + try: + return float(s) + except ValueError: + return None + + +def num_matches(value_set, target, tol=0.5): + return any(abs(n - target) <= tol for n in value_set) + + +def added_cell_numbers(initial, current): + """ + Collect numeric values from cells that were ADDED or CHANGED between + initial and current across all sheets. This guarantees pre-existing ledger + values are never counted, so the initial_env (current == initial) yields an + empty set. + """ + nums = [] + + def index_sheets(state): + idx = {} + for sh in (state or {}).get('sheets', []) or []: + idx[sh.get('id')] = sh.get('data', {}) or {} + return idx + + init_idx = index_sheets(initial) + cur_idx = index_sheets(current) + + for sid_, cur_data in cur_idx.items(): + init_data = init_idx.get(sid_, {}) + for cell_id, cell in cur_data.items(): + init_cell = init_data.get(cell_id) + # Only consider cells that are new or whose value/computed changed + if init_cell is not None and init_cell == cell: + continue + # Prefer computed result of a formula, else raw value + n = to_number(cell.get('computed')) + if n is None: + n = to_number(cell.get('value')) + if n is None: + n = to_number(cell.get('formula')) + if n is not None: + nums.append(n) + return nums + + +def new_finance_messages(initial, current): + """Return list of message dicts present in current #finance but not in initial.""" + def fin_msgs(state): + return ((state or {}).get('messages', {}) or {}).get('finance', []) or [] + + init_ids = {m.get('messageId') for m in fin_msgs(initial)} + return [m for m in fin_msgs(current) if m.get('messageId') not in init_ids] + + +def verify_task(): + total_score = 0.0 + + sid = read_sid() + if not sid: + print('REWARD: 0.0') + return 0.0 + + gs_init, gs_cur = fetch(GS_URL, sid) + sl_init, sl_cur = fetch(SLACK_URL, sid) + if gs_cur is None or sl_cur is None: + print('REWARD: 0.0') + return 0.0 + + # ---------- Google Sheets: added cells only ---------- + added_nums = added_cell_numbers(gs_init, gs_cur) + + # Component 1: 4 aging-bucket totals present in added cells (0.30, 0.075 each) + try: + for label, target in BUCKETS.items(): + if num_matches(added_nums, target): + print(f'PASS: bucket {label} total {target:.0f} found in added cells (0.075 pts)') + total_score += 0.075 + else: + print(f'FAIL: bucket {label} total {target:.0f} not found in added cells') + except Exception as e: + print(f'ERROR: Component 1 (bucket totals) — {e}') + + # Component 2: Total Outstanding 463500 present in added cells (0.20) + try: + if num_matches(added_nums, TOTAL_OUTSTANDING): + print(f'PASS: Total Outstanding {TOTAL_OUTSTANDING:.0f} found in added cells (0.20 pts)') + total_score += 0.20 + else: + print(f'FAIL: Total Outstanding {TOTAL_OUTSTANDING:.0f} not found in added cells') + except Exception as e: + print(f'ERROR: Component 2 (total outstanding) — {e}') + + # ---------- Slack #finance: new message only ---------- + new_msgs = new_finance_messages(sl_init, sl_cur) + + # Component 3: a new message was posted in #finance by user_1 (0.10) + user_1_msgs = [m for m in new_msgs if m.get('senderId') == 'user_1'] + try: + if user_1_msgs: + print(f'PASS: {len(user_1_msgs)} new #finance message(s) by user_1 (0.10 pts)') + total_score += 0.10 + else: + print(f'FAIL: no new #finance message by user_1 (new msgs: {len(new_msgs)})') + except Exception as e: + print(f'ERROR: Component 3 (new message) — {e}') + + # Combine all new user_1 message text (the snapshot post) for content checks. + combined = '\n'.join(m.get('content', '') or '' for m in user_1_msgs) + combined_lower = combined.lower() + # Normalized digits-only version for amount matching ($115,000 -> 115000) + combined_norm = combined.replace('$', '').replace(',', '').replace(' ', '') + + # Component 4: top three overdue customers + balances present (0.25) + try: + hits = 0 + for name, amount in TOP3.items(): + name_ok = name.lower() in combined_lower + amt_ok = str(int(amount)) in combined_norm + if name_ok and amt_ok: + print(f'PASS: top-3 customer {name} (${int(amount)}) present (0.0833 pts)') + hits += 1 + else: + print(f'FAIL: top-3 customer {name} (${int(amount)}) — name={name_ok} amount={amt_ok}') + total_score += 0.25 * (hits / 3.0) + except Exception as e: + print(f'ERROR: Component 4 (top 3 customers) — {e}') + + # Component 5: total outstanding 463500 stated in the message (0.15) + try: + if str(int(TOTAL_OUTSTANDING)) in combined_norm: + print(f'PASS: total outstanding {int(TOTAL_OUTSTANDING)} stated in message (0.15 pts)') + total_score += 0.15 + else: + print(f'FAIL: total outstanding {int(TOTAL_OUTSTANDING)} not stated in message') + except Exception as e: + print(f'ERROR: Component 5 (message total) — {e}') + + final_score = round(min(total_score, 1.0), 4) + print(f'\nScore: {total_score:.4f}/1.0') + print(f'REWARD: {final_score}') + return final_score + + +verify_task() diff --git a/ar_aging_001/reward_label.json b/ar_aging_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..17991ebb6bc3ccf6bd0b12ac24607db84ab207fd --- /dev/null +++ b/ar_aging_001/reward_label.json @@ -0,0 +1,67 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_aging_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:21:59", + "label": { + "task_id": "ar_aging_001", + "domain": "mock_websites", + "summary": "验证用户在 Google Sheets 应收账款账龄表下方新增四个账龄区间合计与总欠款金额,并在 Slack #finance 频道以 user_1 身份发布包含前三位逾期客户及其余额和总欠款的新消息。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_sheets_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.3, + "description": "Google Sheets 中新增或修改的单元格内包含四个账龄区间(Current、1-30、31-60、60+)的正确合计金额", + "check_logic": "调用 added_cell_numbers 提取所有新增/修改单元格中的数值集合 added_nums,使用 num_matches 逐一检查 BUCKETS 中的四个目标值(138000.0、96000.0、151500.0、78000.0,容差 0.5)是否存在于该集合中。每匹配一个加 0.075 分。", + "pass_condition": "added_nums 中同时包含 138000、96000、151500、78000(容差 0.5)" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "Google Sheets 中新增或修改的单元格内包含总欠款金额 463500", + "check_logic": "使用 num_matches 检查 added_nums 中是否存在 TOTAL_OUTSTANDING(463500.0,容差 0.5)。存在则加 0.20 分。", + "pass_condition": "added_nums 中包含 463500(容差 0.5)" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "Slack #finance 频道中有 user_1 发布的新消息", + "check_logic": "调用 new_finance_messages 获取 current 相对 initial 的新消息列表,筛选 senderId 为 'user_1' 的消息。若列表非空则加 0.10 分。", + "pass_condition": "new_msgs 中存在至少一条 senderId 为 'user_1' 的新消息" + }, + { + "name": "Component 4", + "weight": 0.25, + "description": "Slack 新消息内容中列出前三位逾期客户及其余额(Umbrella Health $115,000、Initech $72,000、Hooli $63,000)", + "check_logic": "合并所有 user_1 新消息的 content 文本,生成 combined_lower(小写)和 combined_norm(去除 $、逗号、空格)。对 TOP3 中每个客户,检查 name.lower() 是否在 combined_lower 中,且 str(int(amount)) 是否在 combined_norm 中。每完全匹配一个客户计 1 hit,最终得分 = 0.25 × (hits / 3.0)。", + "pass_condition": "消息文本中同时出现三位客户名称(不区分大小写)及其对应金额数字(115000、72000、63000)" + }, + { + "name": "Component 5", + "weight": 0.15, + "description": "Slack 新消息内容中声明总欠款 463500", + "check_logic": "检查 str(int(TOTAL_OUTSTANDING)) 即 '463500' 是否存在于 combined_norm 中。存在则加 0.15 分。", + "pass_condition": "规范化后的消息文本中包含 463500" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加求和,最终通过 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数。", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空,直接返回 0.0", + "从 google_sheets_mock 或 slack_mock 拉取 /go 状态失败,直接返回 0.0", + "initial_env 下 current 与 initial 完全相同,导致 added_cell_numbers 返回空集,所有 Sheets 相关组件无法得分", + "Slack #finance 中无 user_1 发送的新消息,导致 Component 3 得 0 分且后续内容检查基于空文本进行", + "各组件内部异常被 try/except 捕获,打印 ERROR 但不中断流程,该组件得 0 分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,随后并行(逻辑上顺序)向 google_sheets_mock 和 slack_mock 请求 /go 接口,获取 initial_state 与 current_state。若任一环节失败则直接返回 0.0。对于 Google Sheets,脚本通过 added_cell_numbers 函数对比 initial 与 current,仅收集新增或修改单元格中的数值,避免计入原有账簿数据;然后逐项匹配四个账龄区间合计(各 0.075 分)与总欠款(0.20 分)。对于 Slack,脚本通过 new_finance_messages 提取 #finance 频道中 messageId 为新增的消息,并筛选 senderId 为 user_1 的消息;若存在则得 0.10 分,随后将所有 user_1 消息内容合并,进行文本检查:验证前三位逾期客户名称与金额是否同时出现(按命中比例 0.25 × hits/3 计分),以及总欠款 463500 是否出现(0.15 分)。所有组件得分累加后钳制到 1.0 并输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **任务信息**:\n - Task ID: ar_aging_001\n - Domain: mock_websites (google_sheets_mock + slack_mock)\n - 这是一个关于 AR aging snapshot 的任务,需要在 Google Sheets 中分类未付发票到 aging buckets,写一个标记的摘要块,然后在 Slack #finance 中发布前三位逾期客户和总欠款。\n\n2. **数据源**:\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\n3. **评分组件**:\n - **Component 1**: Google Sheets 中 4 个 aging-bucket 总计出现在新增/修改的单元格中 (0.30, 每个 0.075)\n - Current=138000, 1-30=96000, 31-60=151500, 60+=78000\n - 检查逻辑:`added_cell_numbers` 函数收集所有新增或修改的单元格中的数字,然后 `num_matches` 检查这些数字中是否包含目标值(容差 0.5)\n \n - **Component 2**: Google Sheets 中 Total Outstanding (463500) 出现在新增/修改的单元格中 (0.20)\n - 检查逻辑:同上,检查 added_nums 中是否有 463500.0\n\n - **Component 3**: Slack #finance 中有 user_1 发布的新消息 (0.10)\n - 检查逻辑:`new_finance_messages` 获取 current 中但不在 initial 中的 finance 频道消息,筛选 senderId 为 'user_1' 的消息\n\n - **Component 4**: 消息中列出前三位逾期客户及其余额 (0.25)\n - Umbrella Health $115,000, Initech $72,000, Hooli $63,000\n - 检查逻辑:合并所有 user_1 消息文本,检查每个客户名称(不区分大小写)和金额(去除 $, , 空格后匹配数字字符串)是否都出现\n - 得分:0.25 * (hits / 3.0),即每个客户约 0.0833 分\n\n - **Component 5**: 消息中说明总欠款 $463,500 (0.15)\n - 检查逻辑:在规范化后的消息文本中查找 \"463500\"\n\n4. **分数汇总**:\n - 各组件分数相加\n - 最后 `round(min(total_score, 1.0), 4)`,即上限为 1.0\n\n5. **失败模式**:\n - 读取 sid 失败:返回 0.0\n - 获取 Google Sheets 或 Slack 状态失败:返回 0.0\n - 各组件检查中的异常会被捕获并打印 ERROR,但不会导致提前退出(除了上面的 CRITICAL)\n - 如果 initial_env (current == initial),added_cell_numbers 返回空集,所有依赖 added cells 的组件都会失败\n\n6. **is_placeholder**:\n - false,因为脚本确实进行了详细的状态检查和评分\n\n7. **confidence**:\n - 1.0,因为代码逻辑清晰完整\n\n现在构建 JSON:\n\n- task_id: \"ar_aging_001\"\n- domain: \"mock_websites\"\n- summary: \"验证用户在 Google Sheets 的应收账款账龄表中新增四个账龄区间合计与总欠款金额,并在 Slack #finance 频道发布包含前三位逾期客户及其余额和总欠款的新消息。\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"google_sheets_mock\", \"slack_mock\"]\n- scoring_components:\n 1. Component 1: 4个账龄区间合计, weight 0.30, 每个0.075\n 2. Component 2: 总欠款金额, weight 0.20\n 3. Component 3: user_1在#finance发新消息, weight 0.10\n 4. Component 4: 前三位逾期客户及余额, weight 0.25\n 5. Component 5: 消息中声明总欠款, weight 0.15\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 失败返回 0.0\",\n \"从 google_sheets_mock 或 slack_mock 获取 /go 状态失败返回 0.0\",\n \"initial_env 下 current == initial 导致 added_cell_numbers 为空集,所有 Sheets 相关组件得 0 分\",\n \"Slack #finance 无 user_1 发送的新消息导致 Component 3 得 0 分并影响后续内容检查\"\n ]\n\n- scoring_logic_explanation: 详细说明执行顺序...\n\n让我确保所有字符串 value 使用中文,但代码标识符保留原样。\n\n检查 weight 字段:\n- Component 1: 0.30 (代码中显式 0.075 each, 共4个)\n- Component 2: 0.20\n- Component 3: 0.10\n- Component 4: 0.25\n- Component 5: 0.15\n\n这些在 docstring 和代码中都明确给出了。\n\npass_condition 需要具体:\n- Component 1: added_nums 中包含 138000.0、96000.0、151500.0、78000.0 中的对应值(容差 0.5)\n- Component 2: added_nums 中包含 463500.0(容差 0.5)\n- Component 3: new_msgs 中存在 senderId 为 'user_1' 的消息\n- Component 4: combined_lower 中包含客户名称(不区分大小写)且 combined_norm 中包含对应金额数字(如 115000)\n- Component 5: combined_norm 中包含 463500\n\n注意 Component 4 是部分得分:0.25 * (hits/3.0)\n\nJSON 格式要求:\n- 不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 不要额外解释\n\n让我再仔细检查一下代码细节:\n\n`added_cell_numbers` 函数:\n- 遍历 current 的所有 sheet\n- 对比 initial 中相同 cell_id 的值\n- 如果 init_cell == cell,跳过(完全相同的不算)\n- 否则提取 computed, value, formula 中的数字\n- 这意味着修改现有单元格也算 \"added\"(函数名是 added_cell_numbers,但注释说 ADDED or CHANGED)\n\n`num_matches`:容差 0.5\n\n`new_finance_messages`:通过 messageId 判断是否是新消息\n\n`combined_norm`:去掉了 $, , 空格\n\n好的,开始写 JSON。 {\"task_id\":\"ar_aging_001\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Google Sheets 应收账款账龄表下方新增四个账龄区间合计与总欠款金额,并在 Slack #finance 频道以 user_1 身份发布包含前三位逾期客户及其余额和总欠款的新消息。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.3,\"description\":\"Google Sheets 中新增或修改的单元格内包含四个账龄区间(Current、1-30、31-60、60+)的正确合计金额\",\"check_logic\":\"调用 added_cell_numbers 提取所有新增/修改单元格中的数值集合 added_nums,使用 num_matches 逐一检查 BUCKETS 中的四个目标值(138000.0、96000.0、151500.0、78000.0,容差 0.5)是否存在于该集合中。每匹配一个加 0.075 分。\",\"pass_condition\":\"added_nums 中同时包含 138000、96000、151500、78000(容差 0.5)\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"Google Sheets 中新增或修改的单元格内包含总欠款金额 463500\",\"check_logic\":\"使用 num_matches 检查 added_nums 中是否存在 TOTAL_OUTSTANDING(463500.0,容差 0.5)。存在则加 0.20 分。\",\"pass_condition\":\"added_nums 中包含 463500(容差 0.5)\"},{\"name\":\"Component 3\",\"weight\":0.1,\"description\":\"Slack #finance 频道中有 user_1 发布的新消息\",\"check_logic\":\"调用 new_finance_messages 获取 current 相对 initial 的新消息列表,筛选 senderId 为 'user_1' 的消息。若列表非空则加 0.10 分。\",\"pass_condition\":\"new_msgs 中存在至少一条 senderId 为 'user_1' 的新消息\"},{\"name\":\"Component 4\",\"weight\":0.25,\"description\":\"Slack 新消息内容中列出前三位逾期客户及其余额(Umbrella Health $115,000、Initech $72,000、Hooli $63,000)\",\"check_logic\":\"合并所有 user_1 新消息的 content 文本,生成 combined_lower(小写)和 combined_norm(去除 $、逗号、空格)。对 TOP3 中每个客户,检查 name.lower() 是否在 combined_lower 中,且 str(int(amount)) 是否在 combined_norm 中。每完全匹配一个客户计 1 hit,最终得分 = 0.25 × (hits / 3.0)。\",\"pass_condition\":\"消息文本中同时出现三位客户名称(不区分大小写)及其对应金额数字(115000、72000、63000)\"},{\"name\":\"Component 5\",\"weight\":0.15,\"description\":\"Slack 新消息内容中声明总欠款 463500\",\"check_logic\":\"检查 str(int(TOTAL_OUTSTANDING)) 即 '463500' 是否存在于 combined_norm 中。存在则加 0.15 分。\",\"pass_condition\":\"规范化后的消息文本中包含 463500\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终通过 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数。\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空,直接返回 0.0\",\"从 google_sheets_mock 或 slack_mock 拉取 /go 状态失败,直接返回 0.0\",\"initial_env 下 current 与 initial 完全相同,导致 added_cell_numbers 返回空集,所有 Sheets 相关组件无法得分\",\"Slack #finance 中无 user_1 发送的新消息,导致 Component 3 得 0 分且后续内容检查基于空文本进行\",\"各组件内部异常被 try/except 捕获,打印 ERROR 但不中断流程,该组件得 0 分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,随后并行(逻辑上顺序)向 google_sheets_mock 和 slack_mock 请求 /go 接口,获取 initial_state 与 current_state。若任一环节失败则直接返回 0.0。对于 Google Sheets,脚本通过 added_cell_numbers 函数对比 initial 与 current,仅收集新增或修改单元格中的数值,避免计入原有账簿数据;然后逐项匹配四个账龄区间合计(各 0.075 分)与总欠款(0.20 分)。对于 Slack,脚本通过 new_finance_messages 提取 #finance 频道中 messageId 为新增的消息,并筛选 senderId 为 user_1 的消息;若存在则得 0.10 分,随后将所有 user_1 消息内容合并,进行文本检查:验证前三位逾期客户名称与金额是否同时出现(按命中比例 0.25 × hits/3 计分),以及总欠款 463500 是否出现(0.15 分)。所有组件得分累加后钳制到 1.0 并输出。\",\"confidence\":1.0}" +} diff --git a/ar_invoice_003/_cua_gym_vm_bridge.sh b/ar_invoice_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/ar_invoice_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/ar_invoice_003/reward_label.json b/ar_invoice_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..d62811f164c26fecd618ec9099bb5cd7ec0b71ea --- /dev/null +++ b/ar_invoice_003/reward_label.json @@ -0,0 +1,49 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_invoice_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:38", + "label": { + "task_id": "ar_invoice_003", + "domain": "mock_websites", + "summary": "验证在Google Sheets中新增INV-1043发票台账行且未改动原有数据,并在Slack的#finance频道向Sarah Chen发送关于该发票的新消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google-sheets mock 服务 (/go?sid=...)", + "slack mock 服务 (/go?sid=...)" + ], + "scoring_components": [ + { + "name": "Sheet", + "weight": 0.5, + "description": "检查Google Sheets中是否新增了INV-1043发票行,且原有行未被修改", + "check_logic": "先通过fetch_state获取google-sheets的initial_state和current_state;构建发票号到行数据的映射;检查所有initial中的发票行在current中是否完全一致(norm后比较),若不一致则返回0.0;检查INV-1043是否已存在于initial中,若存在则返回0.0;在current中查找INV-1043新行,若不存在则返回0.0;对A..H共8个单元格逐格比对,text类型用norm比较,amount类型用norm_amount比较,date类型用digits比较", + "pass_condition": "现有发票行完全未被修改;INV-1043为新增行;8个单元格分别匹配预期值(A=INV-1043, B=Acme Corp, C=Acme Corp - Platform License, D=48000, E=20260624, F=20260724, G=Sent, H=Sarah Chen)" + }, + { + "name": "Slack", + "weight": 0.5, + "description": "检查Slack的#finance频道是否新增了发给Sarah Chen的关于INV-1043发票的消息", + "check_logic": "获取slack的initial_state和current_state;比较#finance频道消息数,若current消息数不大于initial则返回0.0;取新增消息(cur_msgs[len(init_msgs):]);对每条新增消息归一化后检查5个关键词条件,取命中数最多的消息;5个条件各值0.1分", + "pass_condition": "#finance频道至少有一条新增消息;该消息同时满足5个关键词条件:包含sarah chen或@sarah、包含inv-1043、包含acme、包含金额48000、包含日期2026-07-24(经过去分隔符处理后匹配20260724)" + } + ], + "total_max_score": 1.0, + "score_aggregation": "两个组件分数相加,最终用min(total, 1.0)钳制到上限1.0,再四舍五入到4位小数", + "failure_modes": [ + "读取/tmp/task_web_sid失败或为空时打印CRITICAL并直接退出,REWARD为0.0", + "fetch_state拉取google-sheets或slack状态失败时该组件返回0.0", + "current_state为空时该组件返回0.0", + "Sheet组件中任何现有初始行被修改或删除,该组件直接返回0.0", + "Sheet组件中INV-1043在initial_state已存在,直接返回0.0", + "Sheet组件中未找到INV-1043新行,直接返回0.0", + "Slack组件中#finance频道无新增消息(消息数未增加),直接返回0.0", + "任一组件内部抛出异常时该组件得0.0,不影响另一组件评分" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID。然后分别调用verify_sheet()和verify_slack()两个组件。verify_sheet通过mock API获取Google Sheets的initial_state和current_state,先进行两个硬性门控:1)所有原有发票行必须完全不变;2)目标行INV-1043必须是新增且存在于current_state中。门控通过后,对A到H共8个单元格逐格匹配预期值,按匹配单元格比例乘以0.5计分。verify_slack通过mock API获取Slack状态,检查#finance频道消息数是否增加,若无增加则得0分;若有新增消息,则在新增消息中寻找命中5个关键词条件最多的一条,按命中比例乘以0.5计分。两个组件得分相加后,最终分数被钳制在1.0以内并四舍五入到4位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。我需要仔细阅读源码,提取关键信息。\n\n首先,从 docstring 中提取信息:\n- Task ID: ar_invoice_001\n- Domain: mock_websites (google_sheets + slack)\n- 这是一个链式任务:Salesforce -> Google Sheets -> Slack\n- Salesforce 是只读的,只评分 Google Sheet 和 Slack\n\n数据源:\n- /tmp/task_web_sid:读取 sid\n- google-sheets mock:通过 _cua_gym_base('google-sheets')/go?sid={SID} 获取状态\n- slack mock:通过 _cua_gym_base('slack')/go?sid={SID} 获取状态\n\n评分组件:\n\n1. Sheet (0.5分):\n - 检查是否新增了 INV-1043 行\n - 检查现有行是否未被修改\n - 8个单元格 (A..H) 逐单元格评分,每个单元格匹配得 0.5/8\n - 期望值:\n - A: INV-1043 (text)\n - B: Acme Corp (text)\n - C: Acme Corp - Platform License (text)\n - D: 48000 (amount)\n - E: 20260624 (date)\n - F: 20260724 (date)\n - G: Sent (text)\n - H: Sarah Chen (text)\n - 如果现有行被修改或删除,得 0.0\n - 如果 INV-1043 在 initial_state 中已存在,得 0.0\n - 如果没有找到 INV-1043 新行,得 0.0\n\n2. Slack (0.5分):\n - 检查 #finance 频道是否有新消息\n - 新消息数量必须大于初始消息数量\n - 在新增消息中找最佳匹配\n - 5个关键词标准,每个 0.1分 (0.5/5):\n 1. addressed to Sarah Chen ('sarah chen' in t or '@sarah' in t)\n 2. invoice INV-1043 ('inv-1043' in t)\n 3. customer Acme ('acme' in t)\n 4. amount 48000 ('48000' in re.sub(r'[$,\\s]', '', t))\n 5. due date 2026-07-24 ('20260724' in re.sub(r'[^0-9]', '', t))\n\n分数汇总:\n- total = verify_sheet() + verify_slack()\n- final = round(min(total, 1.0), 4)\n- 两个组件相加,钳制到 1.0\n\n失败路径:\n- 读取 /tmp/task_web_sid 失败会打印 CRITICAL 并退出,返回 0.0\n- fetch_state('google-sheets') 失败返回 None,verify_sheet 返回 0.0\n- fetch_state('slack') 失败返回 None,verify_slack 返回 0.0\n- current_state 为空返回 0.0\n- Sheet:现有行被修改或删除返回 0.0\n- Sheet:INV-1043 已存在于 initial_state 返回 0.0\n- Sheet:未找到 INV-1043 新行返回 0.0\n- Slack:#finance 无新消息返回 0.0\n- 各组件异常被捕获,打印 ERROR,该组件得 0.0\n\nis_placeholder: false,因为脚本有详细的检查逻辑。\n\nconfidence: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON。 {\"task_id\":\"ar_invoice_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在Google Sheets中新增INV-1043发票台账行且未改动原有数据,并在Slack的#finance频道向Sarah Chen发送关于该发票的新消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google-sheets mock 服务 (/go?sid=...)\",\"slack mock 服务 (/go?sid=...)\"],\"scoring_components\":[{\"name\":\"Sheet\",\"weight\":0.5,\"description\":\"检查Google Sheets中是否新增了INV-1043发票行,且原有行未被修改\",\"check_logic\":\"先通过fetch_state获取google-sheets的initial_state和current_state;构建发票号到行数据的映射;检查所有initial中的发票行在current中是否完全一致(norm后比较),若不一致则返回0.0;检查INV-1043是否已存在于initial中,若存在则返回0.0;在current中查找INV-1043新行,若不存在则返回0.0;对A..H共8个单元格逐格比对,text类型用norm比较,amount类型用norm_amount比较,date类型用digits比较\",\"pass_condition\":\"现有发票行完全未被修改;INV-1043为新增行;8个单元格分别匹配预期值(A=INV-1043, B=Acme Corp, C=Acme Corp - Platform License, D=48000, E=20260624, F=20260724, G=Sent, H=Sarah Chen)\"},{\"name\":\"Slack\",\"weight\":0.5,\"description\":\"检查Slack的#finance频道是否新增了发给Sarah Chen的关于INV-1043发票的消息\",\"check_logic\":\"获取slack的initial_state和current_state;比较#finance频道消息数,若current消息数不大于initial则返回0.0;取新增消息(cur_msgs[len(init_msgs):]);对每条新增消息归一化后检查5个关键词条件,取命中数最多的消息;5个条件各值0.1分\",\"pass_condition\":\"#finance频道至少有一条新增消息;该消息同时满足5个关键词条件:包含sarah chen或@sarah、包含inv-1043、包含acme、包含金额48000、包含日期2026-07-24(经过去分隔符处理后匹配20260724)\"}],\"total_max_score\":1.0,\"score_aggregation\":\"两个组件分数相加,最终用min(total, 1.0)钳制到上限1.0,再四舍五入到4位小数\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或为空时打印CRITICAL并直接退出,REWARD为0.0\",\"fetch_state拉取google-sheets或slack状态失败时该组件返回0.0\",\"current_state为空时该组件返回0.0\",\"Sheet组件中任何现有初始行被修改或删除,该组件直接返回0.0\",\"Sheet组件中INV-1043在initial_state已存在,直接返回0.0\",\"Sheet组件中未找到INV-1043新行,直接返回0.0\",\"Slack组件中#finance频道无新增消息(消息数未增加),直接返回0.0\",\"任一组件内部抛出异常时该组件得0.0,不影响另一组件评分\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID。然后分别调用verify_sheet()和verify_slack()两个组件。verify_sheet通过mock API获取Google Sheets的initial_state和current_state,先进行两个硬性门控:1)所有原有发票行必须完全不变;2)目标行INV-1043必须是新增且存在于current_state中。门控通过后,对A到H共8个单元格逐格匹配预期值,按匹配单元格比例乘以0.5计分。verify_slack通过mock API获取Slack状态,检查#finance频道消息数是否增加,若无增加则得0分;若有新增消息,则在新增消息中寻找命中5个关键词条件最多的一条,按命中比例乘以0.5计分。两个组件得分相加后,最终分数被钳制在1.0以内并四舍五入到4位小数输出。\",\"confidence\":1.0}" +} diff --git a/fin_expense_claim_002__long__cond/.PLACEHOLDER b/fin_expense_claim_002__long__cond/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/fin_expense_claim_002__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/fin_expense_claim_002__long__cond/0a7fc64f-9ca0-54e1-90d0-9bdb1fea4b10_oa_server.py b/fin_expense_claim_002__long__cond/0a7fc64f-9ca0-54e1-90d0-9bdb1fea4b10_oa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6d428ad688e6b53c68f28bf5d3fa29d9675c5c --- /dev/null +++ b/fin_expense_claim_002__long__cond/0a7fc64f-9ca0-54e1-90d0-9bdb1fea4b10_oa_server.py @@ -0,0 +1,779 @@ +#!/usr/bin/env python3 +""" +TechCorp Expense Reimbursement System - Fake OA Server +====================================================== +A single-file, zero-dependency web server for OSWorld condition-branch tasks. + +Usage: + python3 oa_server.py --user zhang_wei --role employee --port 8765 + python3 oa_server.py --user li_ming --role intern --port 8765 + +All submitted data is persisted to DATA_DIR (default: /home/user/oa_data/). +""" + +import argparse +import json +import os +import re +import sys +import time +from http.server import HTTPServer, BaseHTTPRequestHandler +from urllib.parse import urlparse, parse_qs + + +# --- Multipart Form Data Parser (replaces deprecated cgi module) --- + +class UploadedFile: + """Represents an uploaded file from multipart form data.""" + def __init__(self, filename, data): + self.filename = filename + self.data = data + + def read(self): + return self.data + + +def parse_multipart(body, boundary): + """ + Parse multipart/form-data body into a dict. + Returns: {field_name: value_or_UploadedFile_or_list} + For file fields: value is UploadedFile (or list of UploadedFile) + For text fields: value is string (or list of strings) + """ + result = {} + # Boundary comes as string, body is bytes + if isinstance(boundary, str): + boundary = boundary.encode() + + # Split by boundary + delimiter = b"--" + boundary + parts = body.split(delimiter) + + for part in parts: + # Skip preamble and epilogue + if part in (b"", b"--", b"--\r\n", b"\r\n"): + continue + if part.startswith(b"--"): + continue + + # Strip leading \r\n + if part.startswith(b"\r\n"): + part = part[2:] + + # Split headers from body + header_end = part.find(b"\r\n\r\n") + if header_end == -1: + continue + + header_data = part[:header_end].decode("utf-8", errors="replace") + file_data = part[header_end + 4:] + + # Remove trailing \r\n from file_data + if file_data.endswith(b"\r\n"): + file_data = file_data[:-2] + + # Parse Content-Disposition header + name = None + filename = None + for line in header_data.split("\r\n"): + if line.lower().startswith("content-disposition"): + # Extract name + name_match = re.search(r'name="([^"]*)"', line) + if name_match: + name = name_match.group(1) + # Extract filename + filename_match = re.search(r'filename="([^"]*)"', line) + if filename_match: + filename = filename_match.group(1) + + if name is None: + continue + + # Determine if this is a file upload or text field + if filename is not None: + # File field (could be empty filename for no file selected) + if filename: + value = UploadedFile(filename, file_data) + else: + continue # Skip empty file fields + else: + # Text field + value = file_data.decode("utf-8", errors="replace") + + # Append to result (support multiple values for same name) + if name in result: + existing = result[name] + if isinstance(existing, list): + existing.append(value) + else: + result[name] = [existing, value] + else: + result[name] = value + + return result + +# --- Configuration --- +DEFAULT_PORT = 8765 +DATA_DIR = os.environ.get("OA_DATA_DIR", "/home/user/oa_data") + +# --- HTML Templates --- + +HOMEPAGE_HTML = """ + + + + +TechCorp Expense Reimbursement System + + + +
+

🏢 TechCorp Expense Reimbursement System

+
Internal Finance Portal
+
+
+
+

Welcome, {display_name}

+{role_label} +
+
+ + +
+
+

📋 How to Submit a Reimbursement

+
    +
  1. Choose the portal that matches your role
  2. +
  3. Upload your invoice files (PDF or image format)
  4. +
  5. Fill in the details: total amount, expense category, and a brief description
  6. +
  7. If your total amount exceeds ¥1,000: +
      +
    • • You must provide a written justification (at least 20 characters)
    • +
    • • You must upload a manager-approved report (PDF)
    • +
    +
  8. +
  9. (Interns only) Provide your mentor's ID and department approval code
  10. +
  11. Click "Submit Reimbursement"
  12. +
+
💡 Tip: Have all your documents ready before starting. You can find invoice files and any required documents in your designated folder.
+
+
+ + + + + +""" + +FORM_HTML = """ + + + + +Reimbursement Form - TechCorp + + + +
+

🏢 TechCorp Expense Reimbursement System

+ +
+
+
+

📝 Expense Reimbursement Form

+

Logged in as: {display_name} ({role_label})

+ +
+

⚠️ Please fix the errors below before submitting.

+
+ +
+ + +
+ + +
Upload your invoice files (PDF or image). You can select multiple files.
+
Please upload at least one invoice file.
+
+ +
+ + +
Enter the combined total of all invoices.
+
Please enter a valid amount greater than 0.
+
+ +
+ + +
Please select a category.
+
+ +
+ + +
Please enter a description.
+
+ + {intern_section} + +
+

⚠️ High-Value Expense (Amount exceeds ¥1,000)

+

Additional documentation is required for expenses over ¥1,000.

+ +
+ + +
Minimum 20 characters. Explain the business necessity of this expense.
+
Justification must be at least 20 characters.
+
+ +
+ + +
Upload the manager-signed approval document (PDF only).
+
Please upload the approval report.
+
+
+ + +
+
+
+ + + +""" + +INTERN_SECTION_HTML = """ +
+
+

📚 Intern Additional Information

+

As an intern, you need to provide the following additional details.

+ +
+ + +
Enter your mentor's employee ID as shown in your internship agreement.
+
Please enter your mentor's ID.
+
+ +
+ + +
Your department approval code (format: DEPT-XXXX). Check your approval documents.
+
Please enter the department approval code.
+
+
+""" + +SUCCESS_HTML = """ + + + + +Submission Successful - TechCorp + + + +
+

🏢 TechCorp Expense Reimbursement System

+
+
+
+
✅
+

Reimbursement Submitted Successfully!

+
{reference_number}
+ + + + + + +
Amount:¥{amount}
Category:{category}
Description:{description}
Invoice Files:{invoice_count} file(s) uploaded
Status:Pending Review
+

Your submission has been recorded and is awaiting review.

+ ← Back to Home +
+
+ +""" + + +class OARequestHandler(BaseHTTPRequestHandler): + """HTTP request handler for the OA reimbursement system.""" + + def log_message(self, format, *args): + """Override to log to stderr with timestamp.""" + sys.stderr.write("[%s] %s\n" % ( + time.strftime("%Y-%m-%d %H:%M:%S"), format % args)) + + def do_GET(self): + parsed = urlparse(self.path) + path = parsed.path + + if path == "/" or path == "": + self._serve_homepage() + elif path == "/form": + params = parse_qs(parsed.query) + portal = params.get("portal", [""])[0] + self._serve_form(portal) + else: + self._send_404() + + def do_POST(self): + parsed = urlparse(self.path) + if parsed.path == "/submit": + self._handle_submit() + else: + self._send_404() + + def _serve_homepage(self): + """Serve the homepage with guide and portal buttons.""" + user_config = self.server.user_config + role = user_config["role"] + display_name = user_config["display_name"] + + if role == "employee": + role_label = "Full-time Employee" + else: + role_label = "Intern" + + html = HOMEPAGE_HTML.replace( + "{display_name}", display_name + ).replace( + "{role_label}", role_label + ).replace( + "{role}", role + ) + self._send_html(html) + + def _serve_form(self, portal): + """Serve the reimbursement form.""" + user_config = self.server.user_config + role = user_config["role"] + display_name = user_config["display_name"] + + if role == "employee": + role_label = "Full-time Employee" + else: + role_label = "Intern" + + if portal == "employee": + portal_label = "Employee Portal" + else: + portal_label = "Intern Portal" + + # Determine if intern section should be shown + intern_section = "" + if portal == "intern": + intern_section = INTERN_SECTION_HTML + + html = FORM_HTML.replace( + "{display_name}", display_name + ).replace( + "{role_label}", role_label + ).replace( + "{portal_label}", portal_label + ).replace( + "{portal}", portal + ).replace( + "{intern_section}", intern_section + ) + self._send_html(html) + + def _handle_submit(self): + """Handle form submission: save data + files to DATA_DIR.""" + content_type = self.headers.get("Content-Type", "") + if "multipart/form-data" not in content_type: + self._send_error(400, "Invalid content type") + return + + # Extract boundary from content-type header + boundary = None + for part in content_type.split(";"): + part = part.strip() + if part.startswith("boundary="): + boundary = part[len("boundary="):].strip('"') + break + + if not boundary: + self._send_error(400, "Missing boundary in content type") + return + + # Read request body + content_length = int(self.headers.get("Content-Length", 0)) + body = self.rfile.read(content_length) + + # Parse multipart form data + form = parse_multipart(body, boundary) + + # Ensure data directory exists + os.makedirs(DATA_DIR, exist_ok=True) + + # Extract form fields + portal_used = self._get_field(form, "portal_used", "") + amount_str = self._get_field(form, "amount", "0") + category = self._get_field(form, "category", "") + description = self._get_field(form, "description", "") + justification = self._get_field(form, "justification", "") + mentor_id = self._get_field(form, "mentor_id", "") + dept_approval_code = self._get_field(form, "dept_approval_code", "") + + try: + amount = float(amount_str) + except (ValueError, TypeError): + amount = 0.0 + + # Save uploaded invoice files + invoice_files = [] + if "invoices" in form: + invoices_field = form["invoices"] + if not isinstance(invoices_field, list): + invoices_field = [invoices_field] + for item in invoices_field: + if isinstance(item, UploadedFile) and item.filename: + filename = os.path.basename(item.filename) + filepath = os.path.join(DATA_DIR, filename) + with open(filepath, "wb") as f: + f.write(item.read()) + invoice_files.append(filename) + + # Save approval report if present + approval_report_filename = None + if "approval_report" in form: + ar_field = form["approval_report"] + if isinstance(ar_field, list): + ar_field = ar_field[0] + if isinstance(ar_field, UploadedFile) and ar_field.filename: + filename = os.path.basename(ar_field.filename) + filepath = os.path.join(DATA_DIR, filename) + with open(filepath, "wb") as f: + f.write(ar_field.read()) + approval_report_filename = filename + + # Build submission record + user_config = self.server.user_config + ref_number = "EXP-%s-%03d" % ( + time.strftime("%Y%m%d"), int(time.time()) % 1000) + + submission = { + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), + "user": user_config["user"], + "role": user_config["role"], + "portal_used": portal_used, + "amount": amount, + "category": category, + "description": description, + "justification": justification if justification else None, + "mentor_id": mentor_id if mentor_id else None, + "dept_approval_code": dept_approval_code if dept_approval_code else None, + "invoice_files": invoice_files, + "approval_report_filename": approval_report_filename, + "reference_number": ref_number, + "status": "submitted" + } + + # Write submission.json + submission_path = os.path.join(DATA_DIR, "submission.json") + with open(submission_path, "w", encoding="utf-8") as f: + json.dump(submission, f, indent=2, ensure_ascii=False) + + # Serve success page + html = SUCCESS_HTML.replace( + "{reference_number}", ref_number + ).replace( + "{amount}", "%.2f" % amount + ).replace( + "{category}", category + ).replace( + "{description}", description + ).replace( + "{invoice_count}", str(len(invoice_files)) + ) + self._send_html(html) + + self.log_message("Submission saved: %s (amount=%.2f, invoices=%d)", + ref_number, amount, len(invoice_files)) + + def _get_field(self, form, name, default=""): + """Safely get a form field value from parsed multipart data.""" + if name in form: + field = form[name] + if isinstance(field, list): + field = field[0] + if isinstance(field, UploadedFile): + return field.filename # For file fields, return filename + return str(field) + return default + + def _send_html(self, html, status=200): + """Send an HTML response.""" + encoded = html.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def _send_error(self, code, message): + """Send a simple error response.""" + self._send_html("

Error %d

%s

" % (code, message), code) + + def _send_404(self): + """Send 404 response.""" + self._send_html("

404 Not Found

The requested page does not exist.

", 404) + + +def format_display_name(user_id): + """Convert user_id like 'zhang_wei' to 'Zhang Wei'.""" + return " ".join(part.capitalize() for part in user_id.split("_")) + + +def main(): + global DATA_DIR + + parser = argparse.ArgumentParser( + description="TechCorp Expense Reimbursement System (Fake OA Server)") + parser.add_argument("--user", required=True, + help="User ID (e.g. zhang_wei)") + parser.add_argument("--role", required=True, choices=["employee", "intern"], + help="User role: employee or intern") + parser.add_argument("--port", type=int, default=DEFAULT_PORT, + help="Port to listen on (default: %d)" % DEFAULT_PORT) + parser.add_argument("--data-dir", default=DATA_DIR, + help="Directory to save submission data (default: %s)" % DATA_DIR) + args = parser.parse_args() + + DATA_DIR = args.data_dir + os.makedirs(DATA_DIR, exist_ok=True) + + # Configure server + server = HTTPServer(("0.0.0.0", args.port), OARequestHandler) + server.user_config = { + "user": args.user, + "role": args.role, + "display_name": format_display_name(args.user), + } + + url = "http://localhost:%d/" % args.port + + print("=" * 60) + print(" TechCorp Expense Reimbursement System") + print(" " + "-" * 56) + print(" User: %s (%s)" % (server.user_config["display_name"], args.role)) + print(" Port: %d" % args.port) + print(" Data: %s" % DATA_DIR) + print(" URL: %s" % url) + print("=" * 60) + print("\nServer is running. Press Ctrl+C to stop.\n") + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nShutting down server...") + server.shutdown() + + +if __name__ == "__main__": + main() diff --git a/fin_expense_claim_002__long__cond/5cb11caa-90fb-53cc-9f6b-1489523366db_manager_approval.pdf b/fin_expense_claim_002__long__cond/5cb11caa-90fb-53cc-9f6b-1489523366db_manager_approval.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d8001fffb9b2bff77cb622d115d1e7c2d9c20392 --- /dev/null +++ b/fin_expense_claim_002__long__cond/5cb11caa-90fb-53cc-9f6b-1489523366db_manager_approval.pdf @@ -0,0 +1,74 @@ +%PDF-1.3 +%“Œ‹ž ReportLab Generated PDF document (opensource) +1 0 obj +<< +/F1 2 0 R /F2 3 0 R +>> +endobj +2 0 obj +<< +/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font +>> +endobj +3 0 obj +<< +/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font +>> +endobj +4 0 obj +<< +/Contents 8 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 7 0 R /Resources << +/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] +>> /Rotate 0 /Trans << + +>> + /Type /Page +>> +endobj +5 0 obj +<< +/PageMode /UseNone /Pages 7 0 R /Type /Catalog +>> +endobj +6 0 obj +<< +/Author (anonymous) /CreationDate (D:20260517182107+08'00') /Creator (anonymous) /Keywords () /ModDate (D:20260517182107+08'00') /Producer (ReportLab PDF Library - \(opensource\)) + /Subject (unspecified) /Title (untitled) /Trapped /False +>> +endobj +7 0 obj +<< +/Count 1 /Kids [ 4 0 R ] /Type /Pages +>> +endobj +8 0 obj +<< +/Filter [ /ASCII85Decode /FlateDecode ] /Length 816 +>> +stream +GatUr;/ao;&BE]*.IN=lc1megG'IM6i<@0L7=``1'X_6dPWHWU43FJaP-eLM%>9ZY[FWn-kBHXqmLV@+YkqaE!Nn5'obIQ3AG:U/M]mEXo5)k."e]c#!a5)-a.icP`=bHmPY@I1SI?+XjDQ`r/djdHRu^-hV"Q!a[iBCTkkn1_+4l]Y;D#V$T@;+eV>A>GXC69X$p\=K./Z,;PlA;pDErIh42dn,-G%6-_SA;<7IQFj9(%:k7J]H0oKj\7*kJV)!C5>dsNXGuo8]E(ecs,f(aS42('0$M"K`\)lELLTj.2ckThjGM,2c7p"di@J$(5P&%7KVK!1:0bk-Yp.I-f;eRe>F3mVKVK!q^2@u'LXZ[nYd`.8*-ENP-Xqq!a@&UAm@%f:i*]t[_5V+n9>2r=@#8^3AM>+BE1[ok`u]skC]0mRQ!0`O.YR@5e^>FdlQ#h^AlLiF,NlVTl3'b#.i(r*]d'XYR\[*Etrct4VCR/Z!18kYDQmQNs-T?a7eZ!`@fT^"$\B5T1]IXSt2V'kAdhUqe72(Xc>;bKkO'P&Cj\Tk*^7>YG=BgXlB@q_G-GKRL(aTL~>endstream +endobj +xref +0 9 +0000000000 65535 f +0000000061 00000 n +0000000102 00000 n +0000000209 00000 n +0000000321 00000 n +0000000524 00000 n +0000000592 00000 n +0000000853 00000 n +0000000912 00000 n +trailer +<< +/ID +[<0612e7b4c5688218dcc1822c23642fe4><0612e7b4c5688218dcc1822c23642fe4>] +% ReportLab generated PDF document -- digest (opensource) + +/Info 6 0 R +/Root 5 0 R +/Size 9 +>> +startxref +1818 +%%EOF diff --git a/fin_expense_claim_002__long__cond/999fca2d-ceec-581b-9623-500d62780607_invoice_1.pdf b/fin_expense_claim_002__long__cond/999fca2d-ceec-581b-9623-500d62780607_invoice_1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..937235dff9c89a195032def739972dd30391b564 --- /dev/null +++ b/fin_expense_claim_002__long__cond/999fca2d-ceec-581b-9623-500d62780607_invoice_1.pdf @@ -0,0 +1,80 @@ +%PDF-1.3 +%“Œ‹ž ReportLab Generated PDF document (opensource) +1 0 obj +<< +/F1 2 0 R /F2 3 0 R /F3 4 0 R +>> +endobj +2 0 obj +<< +/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font +>> +endobj +3 0 obj +<< +/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font +>> +endobj +4 0 obj +<< +/BaseFont /Symbol /Name /F3 /Subtype /Type1 /Type /Font +>> +endobj +5 0 obj +<< +/Contents 9 0 R /MediaBox [ 0 0 419.5276 595.2756 ] /Parent 8 0 R /Resources << +/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] +>> /Rotate 0 /Trans << + +>> + /Type /Page +>> +endobj +6 0 obj +<< +/PageMode /UseNone /Pages 8 0 R /Type /Catalog +>> +endobj +7 0 obj +<< +/Author (anonymous) /CreationDate (D:20260517182107+08'00') /Creator (anonymous) /Keywords () /ModDate (D:20260517182107+08'00') /Producer (ReportLab PDF Library - \(opensource\)) + /Subject (unspecified) /Title (untitled) /Trapped /False +>> +endobj +8 0 obj +<< +/Count 1 /Kids [ 5 0 R ] /Type /Pages +>> +endobj +9 0 obj +<< +/Filter [ /ASCII85Decode /FlateDecode ] /Length 611 +>> +stream +Gat=h9lJc/(kD)S(%3lJ'Zu3IVRJ*^GM,KOqQN=?Q;&!h(cl-(lb=O]DMO^)ROf\9?AjU%"nNABrZU6+2#n^+\@`tM-kol..8$q`$l60iY'YREAA^DV2.[6"/gShQ@t'A6Y47["L(V`%Ce?4,/1IH*M)k,)CYo*Eq%:g@J@dF<2:F%LN(-Gq;htau)';WI::ZRk'\k`rd^=*Om:,.aXu35KarUEr_:k?A1>sFYIBVG-,af>pkBPXbg[_?6./9gr]rgI/3ruLdo@MOmD6U#igR7aEa#C$9\YYrIB;l0`\3^5k50;_b3;~>endstream +endobj +xref +0 10 +0000000000 65535 f +0000000061 00000 n +0000000112 00000 n +0000000219 00000 n +0000000331 00000 n +0000000408 00000 n +0000000611 00000 n +0000000679 00000 n +0000000940 00000 n +0000000999 00000 n +trailer +<< +/ID +[<0863e61a1dac3fff929198004d0745a8><0863e61a1dac3fff929198004d0745a8>] +% ReportLab generated PDF document -- digest (opensource) + +/Info 7 0 R +/Root 6 0 R +/Size 10 +>> +startxref +1700 +%%EOF diff --git a/fin_expense_claim_002__long__cond/c97f91fe-8f04-5f0f-a397-971c012d254d_invoice_2.pdf b/fin_expense_claim_002__long__cond/c97f91fe-8f04-5f0f-a397-971c012d254d_invoice_2.pdf new file mode 100644 index 0000000000000000000000000000000000000000..57ed1d19bb0c30a1ae6d8e75b053d7d371152f1f --- /dev/null +++ b/fin_expense_claim_002__long__cond/c97f91fe-8f04-5f0f-a397-971c012d254d_invoice_2.pdf @@ -0,0 +1,80 @@ +%PDF-1.3 +%“Œ‹ž ReportLab Generated PDF document (opensource) +1 0 obj +<< +/F1 2 0 R /F2 3 0 R /F3 4 0 R +>> +endobj +2 0 obj +<< +/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font +>> +endobj +3 0 obj +<< +/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font +>> +endobj +4 0 obj +<< +/BaseFont /Symbol /Name /F3 /Subtype /Type1 /Type /Font +>> +endobj +5 0 obj +<< +/Contents 9 0 R /MediaBox [ 0 0 419.5276 595.2756 ] /Parent 8 0 R /Resources << +/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] +>> /Rotate 0 /Trans << + +>> + /Type /Page +>> +endobj +6 0 obj +<< +/PageMode /UseNone /Pages 8 0 R /Type /Catalog +>> +endobj +7 0 obj +<< +/Author (anonymous) /CreationDate (D:20260517182107+08'00') /Creator (anonymous) /Keywords () /ModDate (D:20260517182107+08'00') /Producer (ReportLab PDF Library - \(opensource\)) + /Subject (unspecified) /Title (untitled) /Trapped /False +>> +endobj +8 0 obj +<< +/Count 1 /Kids [ 5 0 R ] /Type /Pages +>> +endobj +9 0 obj +<< +/Filter [ /ASCII85Decode /FlateDecode ] /Length 612 +>> +stream +Gat=h:N)^V(l.R-MYEK4MX*LZ`k,gH\kCdX/Vb?m6/X#[K&&GK[blPRcjlLfRLg6#DresbC[dAb%MsurZ3L)m_q>1o66Y4d8Poij-%*n"=JnDPX=H^=f#`FbPTliH#+UEn=G<_3/95+M_h7PTd26NTAJ/Iq=p3VBN4=1hAME"I"!@J^]-7IBZUdQ'C;/Hhfabqd3>4dg@8bGN;$R?Ed"B$Z[V3jd'_%!OfqD&]]E/iJh,t;!KE_=N)/h*Z,M)f"3^?,8I^Or%5J(;:ki/1S1&Nh5D?2s[Rr6\qpD@MGAi7\p5T.W@QJE8$F\mW>h<\B(YM0A&mVEU5Yom6:WNRnm`2$1lAMNgb.~>endstream +endobj +xref +0 10 +0000000000 65535 f +0000000061 00000 n +0000000112 00000 n +0000000219 00000 n +0000000331 00000 n +0000000408 00000 n +0000000611 00000 n +0000000679 00000 n +0000000940 00000 n +0000000999 00000 n +trailer +<< +/ID +[<430513405f7b86d2996780ca2a987f36><430513405f7b86d2996780ca2a987f36>] +% ReportLab generated PDF document -- digest (opensource) + +/Info 7 0 R +/Root 6 0 R +/Size 10 +>> +startxref +1701 +%%EOF diff --git a/fin_expense_claim_002__long__cond/ce9481c5-7ab8-50e7-a97b-0f4f833ad690_justification.txt b/fin_expense_claim_002__long__cond/ce9481c5-7ab8-50e7-a97b-0f4f833ad690_justification.txt new file mode 100644 index 0000000000000000000000000000000000000000..17b0f2b2353bdf712953421a7ea28c19767f1e9e --- /dev/null +++ b/fin_expense_claim_002__long__cond/ce9481c5-7ab8-50e7-a97b-0f4f833ad690_justification.txt @@ -0,0 +1,12 @@ +Justification for high-value expense: + +This transportation expense of ¥1,105 was incurred for client visits +to the Riverside Convention Center on May 12-13, 2026. The visits were +essential for the Q3 project delivery milestone meeting with our key +client, Greenland Holdings. + +The higher-than-usual cost is due to the remote location of the +convention center (45 km from office) and the need for round-trip +transportation on both days during peak hours. + +Approved by: Manager Chen Wei, 2026-05-10. diff --git a/hr_onboarding_checklist_004/_cua_gym_vm_bridge.sh b/hr_onboarding_checklist_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/hr_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/hr_onboarding_checklist_004/initial_setup.py b/hr_onboarding_checklist_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef0ed6c9b8ae6a402595e9ec2056b06b4844473 --- /dev/null +++ b/hr_onboarding_checklist_004/initial_setup.py @@ -0,0 +1,220 @@ +""" +Initial Setup: HR onboarding checklist (Workday) + Day-1 orientation event (Google Calendar) +Task ID: hr_onboarding_checklist_004 +Domain: libreoffice_calc (actual task is a mock_websites task against Workday + Google Calendar) +Mocks: + - Workday: http://28.7.184.198:8192 + - Calendar: http://28.7.184.198:8141 + +This script runs on the INITIAL VM only. It establishes the PRE-TASK state: + - Workday: full default org state + an EMPTY onboardingChecklists array (no Ava Thompson checklist) + - Calendar: a realistic baseline calendar with a few existing events, but NO + "Day-1 Orientation — Ava Thompson" event. + +The sid is deterministic per-environment and written to /tmp/task_web_sid so the +reward-gen agent can locate this session's state on the (shared) mock server. +""" + +import json +import os +import shlex +import subprocess +import time + +import requests + +# --------------------------------------------------------------------------- +# Config +# --------------------------------------------------------------------------- +WORKDAY_URL = "http://28.7.184.198:8192" +CALENDAR_URL = "http://28.7.184.198:8141" + +# Deterministic, per-environment sid. The initial VM uses the "_init" variant. +SID = "prof13_onboarding_checklist_001_init" + +# Persist sid for reward-gen (it reads /tmp/task_web_sid on the VM it tests). +with open("/tmp/task_web_sid", "w") as f: + f.write(SID) + + +# --------------------------------------------------------------------------- +# Baseline calendar state (the mock has no default state, so we build one). +# This is realistic content: a few existing events, no orientation event. +# --------------------------------------------------------------------------- +def build_baseline_calendar_state(): + return { + "user": { + "id": "u1", + "username": "HR Generalist", + "email": "hr@northwindcloud.com", + "avatar": "https://ui-avatars.com/api/?name=HR+Generalist&background=0875E1&color=fff&size=128", + }, + "calendars": [ + {"id": "c1", "name": "Personal", "color": "#039BE5", "visible": True, "userId": "u1", "isDefault": True}, + {"id": "c2", "name": "Work", "color": "#33B679", "visible": True, "userId": "u1", "isDefault": False}, + {"id": "c3", "name": "Family", "color": "#8E24AA", "visible": True, "userId": "u1", "isDefault": False}, + ], + "events": [ + { + "id": "evt_daily_standup", + "calendarId": "c2", + "title": "Daily Standup", + "start": "2026-07-02T09:00:00", + "end": "2026-07-02T09:15:00", + "allDay": False, + "location": "Zoom", + "description": "Team sync", + "guests": ["daniel.okafor@northwindcloud.com"], + "color": "#33B679", + "recurring": "daily", + "reminders": [{"type": "popup", "minutes": 5}], + "meetLink": "", + "status": "confirmed", + }, + { + "id": "evt_benefits_review", + "calendarId": "c2", + "title": "Benefits Enrollment Review", + "start": "2026-07-10T14:00:00", + "end": "2026-07-10T15:00:00", + "allDay": False, + "location": "Conference Room B", + "description": "Quarterly benefits review with HR.", + "guests": [], + "color": "#33B679", + "recurring": "none", + "reminders": [{"type": "popup", "minutes": 15}], + "meetLink": "", + "status": "confirmed", + }, + ], + "view": "week", + "currentDate": "2026-07-02T00:00:00", + "sidebarOpen": True, + "settings": { + "weekStart": 0, + "defaultDuration": 60, + "defaultView": "week", + "defaultReminder": {"type": "popup", "minutes": 10}, + "timeFormat": "12h", + "showWeekNumbers": False, + "showDeclinedEvents": False, + }, + } + + +def inject_state(base_url, state, action="set"): + resp = requests.post( + f"{base_url}/post?sid={SID}", + json={"action": action, "state": state}, + timeout=30, + ) + resp.raise_for_status() + return resp.json() + + +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, timeout=60.0, render_timeout=15.0): + """Block until every mock serves the injected state AND the page 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)}") + return + + # Browser-side render check (best effort). + try: + from playwright.sync_api import sync_playwright + except ImportError: + print("WARN: playwright not installed; skipping render check") + return + try: + 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)) + print(f"[{name}] rendered OK") + except Exception as e: + print(f"WARN: [{name}] render check failed: {e}") + finally: + page.close() + finally: + browser.close() + except Exception as e: + print(f"WARN: render check skipped: {e}") + + +def main(): + # --- Workday: fetch the server's default state and inject it with an + # EMPTY onboardingChecklists array (pre-task state). --- + try: + default_wd = requests.get(f"{WORKDAY_URL}/go?sid=nonexistent", timeout=15).json()["initial_state"] + except Exception as e: + print(f"WARN: could not fetch Workday default state: {e}") + default_wd = {} + wd_state = dict(default_wd) + wd_state["onboardingChecklists"] = [] # no checklist yet (pre-task) + inject_state(WORKDAY_URL, wd_state, action="set") + print("Workday initial state injected (onboardingChecklists=[]).") + + # --- Calendar: inject a realistic baseline calendar with NO orientation event. --- + cal_state = build_baseline_calendar_state() + inject_state(CALENDAR_URL, cal_state, action="set") + print("Calendar initial state injected (no orientation event).") + + # --- Verify --- + go_wd = requests.get(f"{WORKDAY_URL}/go?sid={SID}", timeout=10).json() + go_cal = requests.get(f"{CALENDAR_URL}/go?sid={SID}", timeout=10).json() + assert go_wd["initial_state"] is not None, "Workday initial_state is None" + assert go_cal["initial_state"] is not None, "Calendar initial_state is None" + print("Verified: initial_state set for both mocks.") + + # --- Launch Chrome for BOTH mocks (agent needs both open). --- + launch_gui(f'google-chrome "{WORKDAY_URL}/?sid={SID}"', delay_sec=1.0) + launch_gui(f'google-chrome "{CALENDAR_URL}/?sid={SID}"', delay_sec=1.0) + + # --- Wait until both mocks serve state and render. --- + wait_for_mocks_loaded({ + "workday": WORKDAY_URL, + "calendar": CALENDAR_URL, + }) + + print(f"GUI_READY: launched and verified Chrome for both mocks (sid={SID})") + + +if __name__ == "__main__": + main() diff --git a/hr_onboarding_checklist_004/reward.py b/hr_onboarding_checklist_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea4f8818a4e85c2e9b9a29cb8aeff1cc91d4a60 --- /dev/null +++ b/hr_onboarding_checklist_004/reward.py @@ -0,0 +1,192 @@ +""" +Reward Script: Create Workday onboarding checklist for Ava Thompson + Google Calendar Day-1 orientation event +Task ID: hr_onboarding_checklist_004 +Domain: mock_websites (Workday @ http://28.7.184.198:8192, Google Calendar @ http://28.7.184.198:8141) +Scoring: + Component 1 (0.5): Workday onboardingChecklists has exactly one checklist for 'Ava Thompson' + with assignee 'Ava Thompson', dueDate '2026-07-13', and the 5 checkbox items + in the exact required order/labels. + Component 2 (0.5): Google Calendar has exactly one event titled 'Day-1 Orientation — Ava Thompson' + on 2026-07-13 09:30-11:00 with both required guests and the exact description. +Each component is verified against the LIVE mock state via /go?sid=, so it fails on the +initial VM (empty checklist list, no orientation event) and passes on the golden VM. +""" +import json +import sys + +import requests + +# --- Mock URLs (from task_config.json; state lives on the remote mock server) --- +WORKDAY_URL = 'http://28.7.184.198:8192' +CALENDAR_URL = 'http://28.7.184.198:8141' + +# --- Ground-truth values from task_config.json context --- +EXPECTED_EMPLOYEE = 'Ava Thompson' +EXPECTED_ASSIGNEE = 'Ava Thompson' +EXPECTED_DUE_DATE = '2026-07-13' +EXPECTED_ITEMS = [ + 'Submit I-9 and W-4', + 'Order laptop (MacBook Pro 14")', + 'Assign Platform team Slack channel', + 'Schedule Day-1 orientation', + 'Grant GitHub access', +] +EXPECTED_EVENT_TITLE = 'Day-1 Orientation — Ava Thompson' +EXPECTED_EVENT_START = '2026-07-13T09:30:00' +EXPECTED_EVENT_END = '2026-07-13T11:00:00' +EXPECTED_GUESTS = ['ava.thompson@northwindcloud.com', 'daniel.okafor@northwindcloud.com'] +EXPECTED_DESC = ('New-hire orientation for Ava Thompson (Backend Engineer, Platform team, ' + 'manager Daniel Okafor). Onboarding checklist owner: HR.') + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +# --- State fetch helper --- +def _fetch_current(base_url): + """Read sid from /tmp/task_web_sid and fetch current_state from the mock server. + + Returns the current_state dict, or {} on any failure (caller handles scoring). + """ + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + return {} + except Exception: + return {} + try: + resp = requests.get(f'{base_url}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + return data.get('current_state') or {} + except Exception: + return {} + + +# --- Per-component checks (one function per sub-objective) --- + +def check_component_1(workday_state): + """Workday has exactly one onboarding checklist for 'Ava Thompson' with assignee + 'Ava Thompson', dueDate '2026-07-13', and the 5 checkbox items in the exact required + order/labels. Pass condition: onboardingChecklists is a list of length 1, the single + entry's employeeName == 'Ava Thompson', assignee == 'Ava Thompson', dueDate == + '2026-07-13', and items (label sequence) == the 5 expected labels. + """ + lists = workday_state.get('onboardingChecklists') + if not isinstance(lists, list): + return False, 0.0, 'onboardingChecklists missing or not a list' + if len(lists) != 1: + return False, 0.0, f'expected exactly 1 checklist, found {len(lists)}' + + cl = lists[0] + if not isinstance(cl, dict): + return False, 0.0, 'checklist entry is not an object' + + name = cl.get('employeeName') + if name != EXPECTED_EMPLOYEE: + return False, 0.0, f'employeeName={name!r}, expected {EXPECTED_EMPLOYEE!r}' + + assignee = cl.get('assignee') + if assignee != EXPECTED_ASSIGNEE: + return False, 0.0, f'assignee={assignee!r}, expected {EXPECTED_ASSIGNEE!r}' + + due = cl.get('dueDate') + if due != EXPECTED_DUE_DATE: + return False, 0.0, f'dueDate={due!r}, expected {EXPECTED_DUE_DATE!r}' + + items = cl.get('items') + if not isinstance(items, list): + return False, 0.0, 'items missing or not a list' + labels = [it.get('label') for it in items if isinstance(it, dict)] + if labels != EXPECTED_ITEMS: + return False, 0.0, f'item labels={labels!r} != expected {EXPECTED_ITEMS!r}' + + return True, 0.5, ('one Ava Thompson checklist, assignee=Ava Thompson, ' + f'dueDate={EXPECTED_DUE_DATE}, 5 items in order') + + +def check_component_2(calendar_state): + """Calendar has exactly one event titled 'Day-1 Orientation — Ava Thompson' on + 2026-07-13 09:30-11:00 with both required guests and the exact description. + Pass condition: among current events there is exactly one event whose title matches + the expected title, start == '2026-07-13T09:30:00', end == '2026-07-13T11:00:00', + the guest set contains both required emails, and description matches exactly. + """ + events = calendar_state.get('events') + if not isinstance(events, list): + return False, 0.0, 'events missing or not a list' + + matches = [e for e in events if isinstance(e, dict) + and e.get('title') == EXPECTED_EVENT_TITLE] + if len(matches) != 1: + return False, 0.0, (f'expected exactly 1 event titled {EXPECTED_EVENT_TITLE!r}, ' + f'found {len(matches)}') + + ev = matches[0] + start = ev.get('start') + if start != EXPECTED_EVENT_START: + return False, 0.0, f'start={start!r}, expected {EXPECTED_EVENT_START!r}' + + end = ev.get('end') + if end != EXPECTED_EVENT_END: + return False, 0.0, f'end={end!r}, expected {EXPECTED_EVENT_END!r}' + + guests = ev.get('guests') or [] + if not isinstance(guests, list): + return False, 0.0, 'guests not a list' + guest_set = set(guests) + missing = [g for g in EXPECTED_GUESTS if g not in guest_set] + if missing: + return False, 0.0, f'missing guests: {missing} (have {guests!r})' + + desc = ev.get('description') + if desc != EXPECTED_DESC: + return False, 0.0, f'description mismatch: got {desc!r}' + + return True, 0.5, ('one orientation event 2026-07-13 09:30-11:00, both guests invited, ' + 'exact description') + + +def verify_task(): + """Verify task completion against live mock state. Returns float 0.0-1.0.""" + workday_state = _fetch_current(WORKDAY_URL) + calendar_state = _fetch_current(CALENDAR_URL) + + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'Workday Ava Thompson onboarding checklist', 0.5, + check_component_1, (workday_state,)), + (2, 'Calendar Day-1 Orientation event', 0.5, + check_component_2, (calendar_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/hr_onboarding_checklist_004/reward_label.json b/hr_onboarding_checklist_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..50afba4df4c4102250ab1d702294025f1a539e8c --- /dev/null +++ b/hr_onboarding_checklist_004/reward_label.json @@ -0,0 +1,50 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof13_onboarding_checklist_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:34", + "label": { + "task_id": "hr_onboarding_checklist_004", + "domain": "mock_websites", + "summary": "验证在 Workday 中为 Ava Thompson 创建了包含5项检查内容的入职清单,并在 Google Calendar 中创建了指定时间、嘉宾和描述的 Day-1 Orientation 活动。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8212", + "http://28.7.186.212:8161" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.5, + "description": "Workday 中存在且仅存在一个针对 Ava Thompson 的入职清单,包含正确的负责人、截止日期和5个检查项。", + "check_logic": "从 Workday mock 状态获取 onboardingChecklists,验证其为长度为1的列表;检查唯一条目的 employeeName == 'Ava Thompson'、assignee == 'Ava Thompson'、dueDate == '2026-07-13';提取 items 中所有 label 并与 EXPECTED_ITEMS 列表进行精确顺序比较。", + "pass_condition": "onboardingChecklists 长度为1,且该清单的 employeeName、assignee、dueDate 均与预期值一致,items 的 label 序列与预期5项完全一致。" + }, + { + "name": "Component 2", + "weight": 0.5, + "description": "Google Calendar 中存在且仅存在一个标题为 'Day-1 Orientation — Ava Thompson' 的事件,时间、嘉宾和描述均正确。", + "check_logic": "从 Calendar mock 状态获取 events,筛选 title == 'Day-1 Orientation — Ava Thompson' 的事件,验证匹配数量为1;检查该事件的 start == '2026-07-13T09:30:00'、end == '2026-07-13T11:00:00';验证 guests 列表包含两个预期邮箱;验证 description 与预期字符串完全相等。", + "pass_condition": "events 中恰好有1个匹配标题的事件,start/end 时间正确,guests 包含两个指定邮箱,description 完全匹配。" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 round(min(total_score, 1.0), 4) 计算并钳制到上限 1.0。", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空,导致获取 mock 状态失败", + "向 Workday 或 Calendar mock 服务器请求失败,返回空状态", + "Workday 的 onboardingChecklists 缺失、非列表或长度不为1", + "Workday 清单的 employeeName、assignee、dueDate 任一字段不匹配", + "Workday 清单的 items 缺失、非列表或 label 顺序/内容不匹配", + "Calendar 的 events 缺失或非列表", + "Calendar 中匹配标题的事件数量不为1", + "Calendar 事件的起止时间、嘉宾列表(缺少任一预期邮箱)或描述不匹配", + "组件检查函数抛出异常时该组件得 0.0 分" + ], + "scoring_logic_explanation": "脚本首先通过 /tmp/task_web_sid 读取会话 ID,然后分别向 Workday (8212) 和 Calendar (8161) 的 mock 服务器请求当前状态。接着依次执行两个组件检查:Component 1 验证 Workday 中是否存在唯一且字段完全正确的 Ava Thompson 入职清单;Component 2 验证 Calendar 中是否存在唯一且字段完全正确的 Day-1 Orientation 事件。每个组件通过返回 (passed, score, detail) 元组,权重分别为 0.5。verify_task 将各组件 score 累加得到 total_score,最终返回 round(min(total_score, 1.0), 4)。任一组件失败仅扣除该组件权重分数,不会导致整体提前退出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: prof13_onboarding_checklist_001\n - Domain: mock_websites (Workday @ http://28.7.186.212:8212, Google Calendar @ http://28.7.186.212:8161)\n\n2. **数据源**:\n - 从 `/tmp/task_web_sid` 读取 sid\n - 通过 HTTP GET 请求获取 mock 服务器状态:\n - Workday: `http://28.7.186.212:8212/go?sid=`\n - Google Calendar: `http://28.7.186.212:8161/go?sid=`\n\n3. **评分组件**:\n - Component 1 (0.5): Workday onboarding checklist\n - 检查 onboardingChecklists 是否为长度为1的列表\n - 检查 employeeName == 'Ava Thompson'\n - 检查 assignee == 'Ava Thompson'\n - 检查 dueDate == '2026-07-13'\n - 检查 items 列表中的 label 顺序和内容完全匹配5个预期项目\n - Component 2 (0.5): Google Calendar event\n - 检查 events 列表中是否有且仅有1个标题为 'Day-1 Orientation — Ava Thompson' 的事件\n - 检查 start == '2026-07-13T09:30:00'\n - 检查 end == '2026-07-13T11:00:00'\n - 检查 guests 包含两个指定邮箱(ava.thompson@northwindcloud.com, daniel.okafor@northwindcloud.com)\n - 检查 description 完全匹配预期字符串\n\n4. **分数汇总**:\n - 两个组件分数相加,每个 0.5\n - 最终分数 = round(min(total_score, 1.0), 4)\n - 是相加逻辑\n\n5. **失败模式**:\n - 读取 /tmp/task_web_sid 失败或为空 → _fetch_current 返回 {},后续检查会失败\n - 请求 mock 服务器失败 → 返回 {},后续检查会失败\n - Workday: onboardingChecklists 缺失/非列表/长度不为1/字段不匹配/items不匹配\n - Calendar: events 缺失/非列表/无匹配事件/多个匹配事件/时间不匹配/客人缺失/描述不匹配\n - 任何异常会被捕获,返回 False, 0.0, error message\n\n6. **is_placeholder**:\n - 不是占位脚本,它真正检查 mock 状态。\n\n7. **confidence**:\n - 1.0,因为代码清晰完整。\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"prof13_onboarding_checklist_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Workday 中为 Ava Thompson 创建了正确的入职清单,并在 Google Calendar 中创建了正确的 Day-1 定向活动。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"http://28.7.186.212:8212\", \"http://28.7.186.212:8161\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.5,\n \"description\": \"Workday 中存在且仅存在一个针对 Ava Thompson 的入职清单,包含正确的负责人、截止日期和5个检查项。\",\n \"check_logic\": \"从 Workday mock 状态获取 onboardingChecklists,验证其为长度为1的列表;检查唯一条目的 employeeName == 'Ava Thompson'、assignee == 'Ava Thompson'、dueDate == '2026-07-13';提取 items 中所有 label 并与 EXPECTED_ITEMS 列表进行精确顺序比较。\",\n \"pass_condition\": \"onboardingChecklists 长度为1,且该清单的 employeeName、assignee、dueDate 均与预期值一致,items 的 label 序列与预期5项完全一致。\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.5,\n \"description\": \"Google Calendar 中存在且仅存在一个标题为 'Day-1 Orientation — Ava Thompson' 的事件,时间、嘉宾和描述均正确。\",\n \"check_logic\": \"从 Calendar mock 状态获取 events,筛选 title == 'Day-1 Orientation — Ava Thompson' 的事件,验证匹配数量为1;检查该事件的 start == '2026-07-13T09:30:00'、end == '2026-07-13T11:00:00';验证 guests 列表包含两个预期邮箱;验证 description 与预期字符串完全相等。\",\n \"pass_condition\": \"events 中恰好有1个匹配标题的事件,start/end 时间正确,guests 包含两个指定邮箱,description 完全匹配。\"\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 失败或为空,导致获取 mock 状态失败\",\n \"向 Workday 或 Calendar mock 服务器请求失败,返回空状态\",\n \"Workday 的 onboardingChecklists 缺失、非列表或长度不为1\",\n \"Workday 清单的 employeeName、assignee、dueDate 任一字段不匹配\",\n \"Workday 清单的 items 缺失、非列表或 label 顺序/内容不匹配\",\n \"Calendar 的 events 缺失或非列表\",\n \"Calendar 中匹配标题的事件数量不为1\",\n \"Calendar 事件的起止时间、嘉宾列表(缺少任一预期邮箱)或描述不匹配\",\n \"组件检查函数抛出异常时该组件得 0.0 分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先通过 /tmp/task_web_sid 读取会话 ID,然后分别向 Workday (8212) 和 Calendar (8161) 的 mock 服务器请求当前状态。接着依次执行两个组件检查:Component 1 验证 Workday 中是否存在唯一且字段完全正确的 Ava Thompson 入职清单;Component 2 验证 Calendar 中是否存在唯一且字段完全正确的 Day-1 Orientation 事件。每个组件通过返回 (passed, score, detail) 元组,权重分别为 0.5。verify_task 将各组件 score 累加得到 total_score,最终返回 round(min(total_score, 1.0), 4)。任一组件失败仅扣除该组件权重分数,不会导致整体提前退出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名、代码标识符保留原样\n- weight 显式给出:0.5\n- is_placeholder: false\n\n确认所有字段都已覆盖。 {\n \"task_id\": \"prof13_onboarding_checklist_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Workday 中为 Ava Thompson 创建了包含5项检查内容的入职清单,并在 Google Calendar 中创建了指定时间、嘉宾和描述的 Day-1 Orientation 活动。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"http://28.7.186.212:8212\", \"http://28.7.186.212:8161\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.5,\n \"description\": \"Workday 中存在且仅存在一个针对 Ava Thompson 的入职清单,包含正确的负责人、截止日期和5个检查项。\",\n \"check_logic\": \"从 Workday mock 状态获取 onboardingChecklists,验证其为长度为1的列表;检查唯一条目的 employeeName == 'Ava Thompson'、assignee == 'Ava Thompson'、dueDate == '2026-07-13';提取 items 中所有 label 并与 EXPECTED_ITEMS 列表进行精确顺序比较。\",\n \"pass_condition\": \"onboardingChecklists 长度为1,且该清单的 employeeName、assignee、dueDate 均与预期值一致,items 的 label 序列与预期5项完全一致。\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.5,\n \"description\": \"Google Calendar 中存在且仅存在一个标题为 'Day-1 Orientation — Ava Thompson' 的事件,时间、嘉宾和描述均正确。\",\n \"check_logic\": \"从 Calendar mock 状态获取 events,筛选 title == 'Day-1 Orientation — Ava Thompson' 的事件,验证匹配数量为1;检查该事件的 start == '2026-07-13T09:30:00'、end == '2026-07-13T11:00:00';验证 guests 列表包含两个预期邮箱;验证 description 与预期字符串完全相等。\",\n \"pass_condition\": \"events 中恰好有1个匹配标题的事件,start/end 时间正确,guests 包含两个指定邮箱,description 完全匹配。\"\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 失败或为空,导致获取 mock 状态失败\",\n \"向 Workday 或 Calendar mock 服务器请求失败,返回空状态\",\n \"Workday 的 onboardingChecklists 缺失、非列表或长度不为1\",\n \"Workday 清单的 employeeName、assignee、dueDate 任一字段不匹配\",\n \"Workday 清单的 items 缺失、非列表或 label 顺序/内容不匹配\",\n \"Calendar 的 events 缺失或非列表\",\n \"Calendar 中匹配标题的事件数量不为1\",\n \"Calendar 事件的起止时间、嘉宾列表(缺少任一预期邮箱)或描述不匹配\",\n \"组件检查函数抛出异常时该组件得 0.0 分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先通过 /tmp/task_web_sid 读取会话 ID,然后分别向 Workday (8212) 和 Calendar (8161) 的 mock 服务器请求当前状态。接着依次执行两个组件检查:Component 1 验证 Workday 中是否存在唯一且字段完全正确的 Ava Thompson 入职清单;Component 2 验证 Calendar 中是否存在唯一且字段完全正确的 Day-1 Orientation 事件。每个组件通过返回 (passed, score, detail) 元组,权重分别为 0.5。verify_task 将各组件 score 累加得到 total_score,最终返回 round(min(total_score, 1.0), 4)。任一组件失败仅扣除该组件权重分数,不会导致整体提前退出。\",\n \"confidence\": 1.0\n}" +} diff --git a/img_contrast_002__long/.PLACEHOLDER b/img_contrast_002__long/.PLACEHOLDER new file mode 100644 index 0000000000000000000000000000000000000000..197b2f7afaf921b78e1ee81802d36150418cd83a --- /dev/null +++ b/img_contrast_002__long/.PLACEHOLDER @@ -0,0 +1,5 @@ +This directory is intentionally empty. +It exists only to satisfy start_our_benchmark_test.sh's uniform +'cache_dir// must exist' precheck. Non-mock tasks do not use +cua_gym cache; their evaluators read a vm_file tarball instead. +See docs/0716_迁移执行日志.md § S15 for details. diff --git a/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/_cua_gym_vm_bridge.sh b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/initial_setup.py b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..229c28d926404cb965238c7e40891d828457a6e6 --- /dev/null +++ b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/initial_setup.py @@ -0,0 +1,365 @@ +""" +Initial Setup: cm_publish_sync_b98 +Task ID: 23a66d5f-baa6-5303-a1d6-6275229ebfa9 +Domain: mock_websites +Mocks: airtable_mock, slack_mock, gmail_mock (single shared sid) + +Persona: You are an office worker acting as an operations manager. Your tools for this task are: the Airtable base, team communications, the shared email inbox. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Airtable 'Project Tracker' base (Tasks + Team tables); Slack workspace with channels #general, #marketing, #random; Gmail inbox with 1 email(s): "Let me know when assets are live" from enablement@company.com. GROUND TRUTH — the agent earns partial credit for each checkpoint: Website Redesign Status = Done (+0.3); Approved checkbox ticked (+0.2); gmail_new_sent (+0.1); emailed enablement lead (+0.2); slack_new_msg (+0.1); heads-up in #marketing (+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 = { + "airtable_mock": "http://28.7.186.212:8129", + "slack_mock": "http://28.7.186.212:8198", + "gmail_mock": "http://28.7.186.212:8158" +} +PRIMARY_URL = 'http://28.7.186.212:8129' + +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 = { 'airtable_mock': { 'bases': { 'base_cyqj85ts3': { 'id': 'base_cyqj85ts3', + 'name': 'Project Tracker', + 'color': 'bg-orange-500', + 'tables': [ 'tbl_btxo7yi93', + 'tbl_qcxlmfd9q']}}, + 'tables': { 'tbl_btxo7yi93': { 'id': 'tbl_btxo7yi93', + 'name': 'Tasks', + 'baseId': 'base_cyqj85ts3', + 'fields': [ { 'id': 'fld_3z0pn979t', + 'name': 'Name', + 'type': 'text', + 'primary': True}, + { 'id': 'fld_9bpvpiybo', + 'name': 'Status', + 'type': 'single_select', + 'options': [ { 'id': 'opt1', + 'name': 'Todo', + 'color': 'bg-red-100 ' + 'text-red-800'}, + { 'id': 'opt2', + 'name': 'In ' + 'Progress', + 'color': 'bg-yellow-100 ' + 'text-yellow-800'}, + { 'id': 'opt3', + 'name': 'Done', + 'color': 'bg-green-100 ' + 'text-green-800'}]}, + { 'id': 'fld_6mdsjffxl', + 'name': 'Priority', + 'type': 'rating', + 'max': 5}, + { 'id': 'fld_mpojl6vv7', + 'name': 'Assignee', + 'type': 'user'}, + { 'id': 'fld_1lzg9gbnm', + 'name': 'Due Date', + 'type': 'date'}, + { 'id': 'fld_gwn2mrky2', + 'name': 'Budget', + 'type': 'currency'}, + { 'id': 'fld_lzn5jy370', + 'name': 'Attachments', + 'type': 'attachment'}, + { 'id': 'fld_vd5052ol2', + 'name': 'Tags', + 'type': 'multiple_select', + 'options': [ { 'id': 'tag1', + 'name': 'Design', + 'color': 'bg-purple-100 ' + 'text-purple-800'}, + { 'id': 'tag2', + 'name': 'Dev', + 'color': 'bg-blue-100 ' + 'text-blue-800'}, + { 'id': 'tag3', + 'name': 'Marketing', + 'color': 'bg-pink-100 ' + 'text-pink-800'}]}, + { 'id': 'fld_jli108tsf', + 'name': 'Notes', + 'type': 'long_text'}, + { 'id': 'fld_znxiw39md', + 'name': 'Approved', + 'type': 'checkbox'}], + 'records': [ { 'id': 'rec_mbony82h2', + 'createdTime': '2026-06-11T06:40:50.934Z', + 'fields': { 'fld_3z0pn979t': 'Website ' + 'Redesign', + 'fld_9bpvpiybo': 'In ' + 'Progress', + 'fld_6mdsjffxl': 4, + 'fld_mpojl6vv7': { 'name': 'Alice', + 'avatar': 'https://picsum.photos/100/100?random=1'}, + 'fld_1lzg9gbnm': '2023-12-25', + 'fld_gwn2mrky2': 5000, + 'fld_lzn5jy370': [ { 'url': 'https://picsum.photos/300/200?random=10', + 'name': 'mockup.png'}], + 'fld_vd5052ol2': [ 'Design', + 'Dev'], + 'fld_jli108tsf': 'Needs ' + 'to ' + 'be ' + 'responsive.', + 'fld_znxiw39md': False}}, + { 'id': 'rec_ggerrdipl', + 'createdTime': '2026-06-11T06:40:50.934Z', + 'fields': { 'fld_3z0pn979t': 'Q1 ' + 'Marketing ' + 'Campaign', + 'fld_9bpvpiybo': 'Todo', + 'fld_6mdsjffxl': 5, + 'fld_mpojl6vv7': { 'name': 'Bob', + 'avatar': 'https://picsum.photos/100/100?random=2'}, + 'fld_1lzg9gbnm': '2024-01-15', + 'fld_gwn2mrky2': 12000, + 'fld_lzn5jy370': [ ], + 'fld_vd5052ol2': [ 'Marketing'], + 'fld_jli108tsf': 'Focus ' + 'on ' + 'social ' + 'media.', + 'fld_znxiw39md': False}}, + { 'id': 'rec_0651cwkw3', + 'createdTime': '2026-06-11T06:40:50.934Z', + 'fields': { 'fld_3z0pn979t': 'Database ' + 'Migration', + 'fld_9bpvpiybo': 'Done', + 'fld_6mdsjffxl': 3, + 'fld_mpojl6vv7': { 'name': 'Charlie', + 'avatar': 'https://picsum.photos/100/100?random=3'}, + 'fld_1lzg9gbnm': '2023-11-01', + 'fld_gwn2mrky2': 2500, + 'fld_lzn5jy370': [ { 'url': 'https://picsum.photos/300/200?random=11', + 'name': 'schema.pdf'}], + 'fld_vd5052ol2': [ 'Dev'], + 'fld_jli108tsf': 'Completed ' + 'ahead ' + 'of ' + 'schedule.', + 'fld_znxiw39md': True}}], + 'views': [ { 'id': 'view_aa9x38mct', + 'name': 'Grid View', + 'type': 'grid'}, + { 'id': 'view_rykugfxaw', + 'name': 'Kanban Board', + 'type': 'kanban', + 'groupFieldId': 'fld_9bpvpiybo'}, + { 'id': 'view_zzdarkhpg', + 'name': 'Gallery', + 'type': 'gallery'}, + { 'id': 'view_63y3ptw7g', + 'name': 'Input Form', + 'type': 'form'}], + 'activeViewId': 'view_aa9x38mct'}, + 'tbl_qcxlmfd9q': { 'id': 'tbl_qcxlmfd9q', + 'name': 'Team', + 'baseId': 'base_cyqj85ts3', + 'fields': [ { 'id': 'fld_i5gvgkxrc', + 'name': 'Name', + 'type': 'text', + 'primary': True}, + { 'id': 'fld_yuilfoka7', + 'name': 'Role', + 'type': 'single_select', + 'options': [ { 'id': 'r1', + 'name': 'Manager'}, + { 'id': 'r2', + 'name': 'IC'}]}, + { 'id': 'fld_0c3we1tep', + 'name': 'Email', + 'type': 'email'}], + 'records': [ { 'id': 'rec_ohudorf8k', + 'createdTime': '2026-06-11T06:40:50.934Z', + 'fields': {}}], + 'views': [ { 'id': 'view_bngoc8vlm', + 'name': 'All Team', + 'type': 'grid'}], + 'activeViewId': None}}, + 'activeBaseId': 'base_cyqj85ts3', + 'activeTableId': 'tbl_btxo7yi93', + 'ui': {'searchQuery': ''}, + 'activityLog': []}, + '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': 'marketing', + 'name': 'marketing', + 'description': 'marketing 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': [], + 'marketing': [ { 'messageId': 'm1', + 'senderId': 'user_3', + 'content': 'did the website redesign ' + 'asset ship?', + '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': []}, + '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': 'Enablement Lead', + 'email': 'enablement@company.com', + 'avatar': ''}, + 'to': [ { 'name': 'John Smith', + 'email': 'john.smith@company.com'}], + 'cc': [], + 'bcc': [], + 'subject': 'Let me know when assets are live', + 'body': '

Ping me when the redesign content is published ' + 'so I can brief the sales team.

', + 'snippet': 'Ping when live.', + 'timestamp': '2026-06-08T08:15:00Z', + 'read': False, + 'starred': False, + 'important': False, + 'labels': [], + 'category': 'primary', + 'folder': 'inbox', + 'attachments': []}], + 'drafts': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward.py b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..f19caf25ae682de068747de69d2d29d18193c484 --- /dev/null +++ b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward.py @@ -0,0 +1,129 @@ +""" +Reward Script: cm_publish_sync_b98 +Task ID: 23a66d5f-baa6-5303-a1d6-6275229ebfa9 +Domain: mock_websites +Mocks: airtable_mock, slack_mock, gmail_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.3] Website Redesign Status = Done + - [0.2] Approved checkbox ticked + - [0.1] gmail_new_sent + - [0.2] emailed enablement lead + - [0.1] slack_new_msg + - [0.1] heads-up in #marketing +""" +import re +import sys + +import requests + +MOCK_URLS = { + "airtable_mock": "http://28.7.186.212:8129", + "slack_mock": "http://28.7.186.212:8198", + "gmail_mock": "http://28.7.186.212:8158" +} +SEED = { + "slack_mock:general": [], + "slack_mock:marketing": [ + "m1" + ], + "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: airtable record rec_mbony82h2 field fld_9bpvpiybo == 'Done' +c0_tbl = (cur('airtable_mock').get('tables') or {}).get('tbl_btxo7yi93') or {} +c0_rec = next((r for r in (c0_tbl.get('records') or []) if r.get('id') == 'rec_mbony82h2'), None) +if c0_rec and (c0_rec.get('fields') or {}).get('fld_9bpvpiybo') == 'Done': + print('PASS: Website Redesign Status = Done (0.3)') + total += 0.3 +else: + print('FAIL: Website Redesign Status = Done') + +# c1: airtable record rec_mbony82h2 field fld_znxiw39md == True +c1_tbl = (cur('airtable_mock').get('tables') or {}).get('tbl_btxo7yi93') or {} +c1_rec = next((r for r in (c1_tbl.get('records') or []) if r.get('id') == 'rec_mbony82h2'), None) +if c1_rec and (c1_rec.get('fields') or {}).get('fld_znxiw39md') == True: + print('PASS: Approved checkbox ticked (0.2)') + total += 0.2 +else: + print('FAIL: Approved checkbox ticked') + +# c2: a new email was sent (folder sent) or saved as draft +c2_init = (STATES['gmail_mock'].get('initial_state') or {}) +c2_cur = cur('gmail_mock') +c2_init_ids = {e.get('id') for e in (c2_init.get('emails') or [])} +c2_sent = [e for e in (c2_cur.get('emails') or []) if e.get('id') not in c2_init_ids and e.get('folder') in ('sent', 'drafts')] +c2_sent += [d for d in (c2_cur.get('drafts') or []) if d.get('id') not in {x.get('id') for x in (c2_init.get('drafts') or [])}] +if c2_sent: + print('PASS: new email sent/drafted (0.1)') + total += 0.1 +else: + print('FAIL: no new sent/draft email') + +# c3: sent/draft email addressed to (emailed enablement lead) +c3_init = (STATES['gmail_mock'].get('initial_state') or {}) +c3_cur = cur('gmail_mock') +c3_init_ids = {e.get('id') for e in (c3_init.get('emails') or [])} +c3_pool = [e for e in (c3_cur.get('emails') or []) if e.get('id') not in c3_init_ids and e.get('folder') in ('sent','drafts')] + (c3_cur.get('drafts') or []) +c3_tos = _lc(' '.join(t.get('email','') for e in c3_pool for t in (e.get('to') or []))) +if any(t in c3_tos for t in ['enablement@company.com']): + print('PASS: emailed enablement lead (0.2)') + total += 0.2 +else: + print('FAIL: emailed enablement lead') + +# c4: new message by user_1 in #marketing +c4_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or [] +c4_seed = set(SEED.get('slack_mock:marketing', [])) +c4_new = [m for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1'] +c4_blob = _lc(' '.join((m.get('content') or '') for m in c4_new)) +if c4_new: + print('PASS: new message by user_1 in #marketing (0.1)') + total += 0.1 +else: + print('FAIL: no new user_1 message in #marketing') + +# c5: slack #marketing contains (heads-up in #marketing) +c5_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or [] +c5_seed = set(SEED.get('slack_mock:marketing', [])) +c5_blob = _lc(' '.join((m.get('content') or '') for m in c5_msgs if m.get('messageId') not in c5_seed and m.get('senderId') == 'user_1')) +if any(t in c5_blob for t in ['publish', 'live', 'redesign', 'approved']): + print('PASS: heads-up in #marketing (0.1)') + total += 0.1 +else: + print('FAIL: heads-up in #marketing') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward_label.json b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..eeee3b4e462374f4d715f2fb273740b728b4f188 --- /dev/null +++ b/legacy/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward_label.json @@ -0,0 +1,77 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/23a66d5f-baa6-5303-a1d6-6275229ebfa9/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:18:50", + "label": { + "task_id": "23a66d5f-baa6-5303-a1d6-6275229ebfa9", + "domain": "mock_websites", + "summary": "验证用户在 Airtable 中将网站重设计状态更新为 Done 并勾选 Approved,通过 Gmail 向 enablement lead 发送邮件,并在 Slack #marketing 频道发送包含指定关键词的提醒消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "airtable_mock", + "slack_mock", + "gmail_mock" + ], + "scoring_components": [ + { + "name": "Component 0: Website Redesign Status = Done", + "weight": 0.3, + "description": "检查 Airtable 中指定记录的网站重设计状态是否标记为 Done", + "check_logic": "从 airtable_mock 的 current_state 中获取 tables.tbl_btxo7yi93.records,查找 id 为 rec_mbony82h2 的记录,检查其 fields.fld_9bpvpiybo 是否等于 'Done'", + "pass_condition": "rec_mbony82h2 的 fld_9bpvpiybo 字段值为 'Done'" + }, + { + "name": "Component 1: Approved checkbox ticked", + "weight": 0.2, + "description": "检查 Airtable 中指定记录的 Approved 复选框是否被勾选", + "check_logic": "从 airtable_mock 的 current_state 中获取 tables.tbl_btxo7yi93.records,查找 id 为 rec_mbony82h2 的记录,检查其 fields.fld_znxiw39md 是否等于 True", + "pass_condition": "rec_mbony82h2 的 fld_znxiw39md 字段值为 True" + }, + { + "name": "Component 2: gmail_new_sent", + "weight": 0.1, + "description": "检查是否通过 Gmail 发送了新邮件或保存了新草稿", + "check_logic": "对比 gmail_mock 的 initial_state 与 current_state,找出 emails 中 id 不在初始集合且 folder 为 sent 或 drafts 的新邮件,以及 drafts 中新增的草稿;若列表非空则通过", + "pass_condition": "存在至少一封新的 sent 或 draft 邮件" + }, + { + "name": "Component 3: emailed enablement lead", + "weight": 0.2, + "description": "检查新邮件是否发送给了 enablement lead", + "check_logic": "在新邮件/草稿池中,提取所有 to 字段中的 email 地址并转为小写拼接,检查是否包含 'enablement@company.com'", + "pass_condition": "新邮件的收件人包含 enablement@company.com" + }, + { + "name": "Component 4: slack_new_msg", + "weight": 0.1, + "description": "检查 user_1 是否在 Slack #marketing 频道发送了新消息", + "check_logic": "从 slack_mock 的 current_state.messages.marketing 中,排除 SEED 中预置的消息(messageId 不在 seed 中),筛选 senderId 为 'user_1' 的消息;若存在则通过", + "pass_condition": "#marketing 频道存在至少一条 user_1 发送的新消息" + }, + { + "name": "Component 5: heads-up in #marketing", + "weight": 0.1, + "description": "检查 Slack #marketing 频道的新消息内容是否包含相关提醒关键词", + "check_logic": "提取 #marketing 频道中 user_1 发送的新消息内容并转为小写,检查是否包含 'publish'、'live'、'redesign'、'approved' 中的任一关键词", + "pass_condition": "消息内容包含 'publish'、'live'、'redesign' 或 'approved' 至少一个关键词" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 0.0 退出", + "请求任何 mock 服务(airtable_mock、slack_mock、gmail_mock)失败:打印 CRITICAL 并返回 0.0 退出", + "Airtable 记录不存在或字段值不符合预期:对应组件不得分", + "Gmail 无新邮件/草稿:对应组件不得分", + "新邮件未发送给 enablement@company.com:对应组件不得分", + "Slack #marketing 无 user_1 新消息:对应组件不得分", + "Slack 消息内容不包含所需关键词:对应组件不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 airtable_mock、slack_mock、gmail_mock 发送 HTTP GET 请求获取 current_state。若任何步骤失败则直接返回 0.0。随后按顺序执行 6 项检查:1)Airtable 记录 rec_mbony82h2 的 Website Redesign Status 字段是否为 Done(0.3 分);2)同一记录的 Approved 复选框是否为 True(0.2 分);3)Gmail 是否存在新的 sent/drafts 邮件(0.1 分);4)新邮件是否发送给 enablement@company.com(0.2 分);5)Slack #marketing 是否有 user_1 的新消息(0.1 分);6)该消息内容是否包含 publish/live/redesign/approved 任一关键词(0.1 分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 限制后四舍五入输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Task ID: 23a66d5f-baa6-5303-a1d6-6275229ebfa9(从 docstring 中提取)\n - Domain: mock_websites(从 docstring 中提取)\n - Mocks: airtable_mock, slack_mock, gmail_mock\n\n2. 评分组件:\n - c0: [0.3] Website Redesign Status = Done - 检查 airtable_mock 中 tbl_btxo7yi93 表的 rec_mbony82h2 记录的 fld_9bpvpiybo 字段是否等于 'Done'\n - c1: [0.2] Approved checkbox ticked - 检查 airtable_mock 中 tbl_btxo7yi93 表的 rec_mbony82h2 记录的 fld_znxiw39md 字段是否等于 True\n - c2: [0.1] gmail_new_sent - 检查是否有新发送或保存为草稿的邮件(通过比较 initial_state 和 current_state 的 emails/drafts)\n - c3: [0.2] emailed enablement lead - 检查新发送/草稿邮件是否发送给 enablement@company.com\n - c4: [0.1] slack_new_msg - 检查 user_1 是否在 #marketing 频道发送了新消息(排除 seed 中的消息)\n - c5: [0.1] heads-up in #marketing - 检查 #marketing 频道中 user_1 的新消息内容是否包含 'publish', 'live', 'redesign', 'approved' 任一关键词\n\n3. 数据源:\n - /tmp/task_web_sid(读取 session id)\n - airtable_mock (http://28.7.186.212:8129)\n - slack_mock (http://28.7.186.212:8198)\n - gmail_mock (http://28.7.186.212:8158)\n\n4. 失败模式:\n - 读取 sid 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 获取任何 mock 状态失败:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出\n\n5. 分数汇总:\n - 各组件分数相加(0.3 + 0.2 + 0.1 + 0.2 + 0.1 + 0.1 = 1.0)\n - 最后 round(min(total, 1.0), 4)\n\n6. is_placeholder: false,因为这是一个真正的评分脚本,有具体的检查逻辑。\n\n7. confidence: 1.0,因为代码清晰完整。\n\n现在构建 JSON:\n\ntask_id: \"23a66d5f-baa6-5303-a1d6-6275229ebfa9\"\ndomain: \"mock_websites\"\nsummary: \"验证用户在 Airtable 中更新网站重设计状态为 Done 并勾选 Approved,通过 Gmail 向 enablement lead 发送邮件,并在 Slack #marketing 频道发送提醒消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"airtable_mock\", \"slack_mock\", \"gmail_mock\"]\n\nscoring_components:\n- name: \"Component 0\" 或 \"Website Redesign Status = Done\"\n weight: 0.3\n description: \"检查 Airtable 中指定记录的网站重设计状态是否标记为 Done\"\n check_logic: \"从 airtable_mock 的 current_state 中获取 tables.tbl_btxo7yi93.records,查找 id 为 rec_mbony82h2 的记录,检查其 fields.fld_9bpvpiybo 是否等于 'Done'\"\n pass_condition: \"rec_mbony82h2 的 fld_9bpvpiybo 字段值为 'Done'\"\n\n- name: \"Component 1\" 或 \"Approved checkbox ticked\"\n weight: 0.2\n description: \"检查 Airtable 中指定记录的 Approved 复选框是否被勾选\"\n check_logic: \"从 airtable_mock 的 current_state 中获取 tables.tbl_btxo7yi93.records,查找 id 为 rec_mbony82h2 的记录,检查其 fields.fld_znxiw39md 是否等于 True\"\n pass_condition: \"rec_mbony82h2 的 fld_znxiw39md 字段值为 True\"\n\n- name: \"Component 2\" 或 \"gmail_new_sent\"\n weight: 0.1\n description: \"检查是否通过 Gmail 发送了新邮件或保存了新草稿\"\n check_logic: \"对比 gmail_mock 的 initial_state 与 current_state,找出 emails 中 id 不在初始集合且 folder 为 sent 或 drafts 的新邮件,以及 drafts 中新增的草稿;若列表非空则通过\"\n pass_condition: \"存在至少一封新的 sent 或 draft 邮件\"\n\n- name: \"Component 3\" 或 \"emailed enablement lead\"\n weight: 0.2\n description: \"检查新邮件是否发送给了 enablement lead\"\n check_logic: \"在新邮件/草稿池中,提取所有 to 字段中的 email 地址并转为小写拼接,检查是否包含 'enablement@company.com'\"\n pass_condition: \"新邮件的收件人包含 enablement@company.com\"\n\n- name: \"Component 4\" 或 \"slack_new_msg\"\n weight: 0.1\n description: \"检查 user_1 是否在 Slack #marketing 频道发送了新消息\"\n check_logic: \"从 slack_mock 的 current_state.messages.marketing 中,排除 SEED 中预置的消息(messageId 不在 seed 中),筛选 senderId 为 'user_1' 的消息;若存在则通过\"\n pass_condition: \"#marketing 频道存在至少一条 user_1 发送的新消息\"\n\n- name: \"Component 5\" 或 \"heads-up in #marketing\"\n weight: 0.1\n description: \"检查 Slack #marketing 频道的新消息内容是否包含相关提醒关键词\"\n check_logic: \"提取 #marketing 频道中 user_1 发送的新消息内容并转为小写,检查是否包含 'publish'、'live'、'redesign'、'approved' 中的任一关键词\"\n pass_condition: \"消息内容包含 'publish'、'live'、'redesign' 或 'approved' 至少一个关键词\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 0.0 退出\",\n \"请求任何 mock 服务(airtable_mock、slack_mock、gmail_mock)失败:打印 CRITICAL 并返回 0.0 退出\",\n \"Airtable 记录不存在或字段值不符合预期:对应组件不得分\",\n \"Gmail 无新邮件/草稿:对应组件不得分\",\n \"新邮件未发送给 enablement@company.com:对应组件不得分\",\n \"Slack #marketing 无 user_1 新消息:对应组件不得分\",\n \"Slack 消息内容不包含所需关键词:对应组件不得分\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 airtable_mock、slack_mock、gmail_mock 发送 HTTP GET 请求获取 current_state。若任何步骤失败则直接返回 0.0。随后按顺序执行 6 项检查:1)Airtable 记录 rec_mbony82h2 的 Website Redesign Status 字段是否为 Done(0.3 分);2)同一记录的 Approved 复选框是否为 True(0.2 分);3)Gmail 是否存在新的 sent/drafts 邮件(0.1 分);4)新邮件是否发送给 enablement@company.com(0.2 分);5)Slack #marketing 是否有 user_1 的新消息(0.1 分);6)该消息内容是否包含 publish/live/redesign/approved 任一关键词(0.1 分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 限制后四舍五入输出。\"\n\nconfidence: 1.0\n\n确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。 {\"task_id\":\"23a66d5f-baa6-5303-a1d6-6275229ebfa9\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Airtable 中将网站重设计状态更新为 Done 并勾选 Approved,通过 Gmail 向 enablement lead 发送邮件,并在 Slack #marketing 频道发送包含指定关键词的提醒消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"airtable_mock\",\"slack_mock\",\"gmail_mock\"],\"scoring_components\":[{\"name\":\"Component 0: Website Redesign Status = Done\",\"weight\":0.3,\"description\":\"检查 Airtable 中指定记录的网站重设计状态是否标记为 Done\",\"check_logic\":\"从 airtable_mock 的 current_state 中获取 tables.tbl_btxo7yi93.records,查找 id 为 rec_mbony82h2 的记录,检查其 fields.fld_9bpvpiybo 是否等于 'Done'\",\"pass_condition\":\"rec_mbony82h2 的 fld_9bpvpiybo 字段值为 'Done'\"},{\"name\":\"Component 1: Approved checkbox ticked\",\"weight\":0.2,\"description\":\"检查 Airtable 中指定记录的 Approved 复选框是否被勾选\",\"check_logic\":\"从 airtable_mock 的 current_state 中获取 tables.tbl_btxo7yi93.records,查找 id 为 rec_mbony82h2 的记录,检查其 fields.fld_znxiw39md 是否等于 True\",\"pass_condition\":\"rec_mbony82h2 的 fld_znxiw39md 字段值为 True\"},{\"name\":\"Component 2: gmail_new_sent\",\"weight\":0.1,\"description\":\"检查是否通过 Gmail 发送了新邮件或保存了新草稿\",\"check_logic\":\"对比 gmail_mock 的 initial_state 与 current_state,找出 emails 中 id 不在初始集合且 folder 为 sent 或 drafts 的新邮件,以及 drafts 中新增的草稿;若列表非空则通过\",\"pass_condition\":\"存在至少一封新的 sent 或 draft 邮件\"},{\"name\":\"Component 3: emailed enablement lead\",\"weight\":0.2,\"description\":\"检查新邮件是否发送给了 enablement lead\",\"check_logic\":\"在新邮件/草稿池中,提取所有 to 字段中的 email 地址并转为小写拼接,检查是否包含 'enablement@company.com'\",\"pass_condition\":\"新邮件的收件人包含 enablement@company.com\"},{\"name\":\"Component 4: slack_new_msg\",\"weight\":0.1,\"description\":\"检查 user_1 是否在 Slack #marketing 频道发送了新消息\",\"check_logic\":\"从 slack_mock 的 current_state.messages.marketing 中,排除 SEED 中预置的消息(messageId 不在 seed 中),筛选 senderId 为 'user_1' 的消息;若存在则通过\",\"pass_condition\":\"#marketing 频道存在至少一条 user_1 发送的新消息\"},{\"name\":\"Component 5: heads-up in #marketing\",\"weight\":0.1,\"description\":\"检查 Slack #marketing 频道的新消息内容是否包含相关提醒关键词\",\"check_logic\":\"提取 #marketing 频道中 user_1 发送的新消息内容并转为小写,检查是否包含 'publish'、'live'、'redesign'、'approved' 中的任一关键词\",\"pass_condition\":\"消息内容包含 'publish'、'live'、'redesign' 或 'approved' 至少一个关键词\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 0.0 退出\",\"请求任何 mock 服务(airtable_mock、slack_mock、gmail_mock)失败:打印 CRITICAL 并返回 0.0 退出\",\"Airtable 记录不存在或字段值不符合预期:对应组件不得分\",\"Gmail 无新邮件/草稿:对应组件不得分\",\"新邮件未发送给 enablement@company.com:对应组件不得分\",\"Slack #marketing 无 user_1 新消息:对应组件不得分\",\"Slack 消息内容不包含所需关键词:对应组件不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 airtable_mock、slack_mock、gmail_mock 发送 HTTP GET 请求获取 current_state。若任何步骤失败则直接返回 0.0。随后按顺序执行 6 项检查:1)Airtable 记录 rec_mbony82h2 的 Website Redesign Status 字段是否为 Done(0.3 分);2)同一记录的 Approved 复选框是否为 True(0.2 分);3)Gmail 是否存在新的 sent/drafts 邮件(0.1 分);4)新邮件是否发送给 enablement@company.com(0.2 分);5)Slack #marketing 是否有 user_1 的新消息(0.1 分);6)该消息内容是否包含 publish/live/redesign/approved 任一关键词(0.1 分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 限制后四舍五入输出。\",\"confidence\":1.0}" +} diff --git a/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/_cua_gym_vm_bridge.sh b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/initial_setup.py b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..081b1c2e2526ce19a47f6af3a35cb6c09c3c2b3e --- /dev/null +++ b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/initial_setup.py @@ -0,0 +1,327 @@ +""" +Initial Setup: cm_brief_to_draft_b97 +Task ID: 4619652a-02e6-5961-83df-6860dfb3ef29 +Domain: mock_websites +Mocks: notion_mock, google_docs_mock, trello_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a product manager. Your tools for this task are: the Notion workspace, shared documents, the Trello board, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Notion workspace with pages 'Content Brief: Remote Onboarding'; Google Docs with documents 'Brand Style Guide'; Trello 'Project Alpha' board with lists Draft, Review, Published; Slack workspace with channels #general, #marketing, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: new article draft created (+0.2); draft has both H2s and the demo CTA (+0.3); card moved to Review list (+0.3); slack_new_msg (+0.1); tells team it's in review (+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 = { + "notion_mock": "http://28.7.186.212:8186", + "google_docs_mock": "http://28.7.186.212:8162", + "trello_mock": "http://28.7.186.212:8202", + "slack_mock": "http://28.7.186.212:8198" +} +PRIMARY_URL = 'http://28.7.186.212:8186' + +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 = { 'notion_mock': { 'user': { 'id': 'user-1', + 'name': 'Sarah Chen', + 'email': 'sarah.chen@acme.com', + 'avatar': ''}, + 'workspace': { 'id': 'ws-1', + 'name': 'Acme Product', + 'icon': '', + 'members': ['user-1']}, + 'pages': { 'page-brief': { 'id': 'page-brief', + 'title': 'Content Brief: Remote Onboarding', + 'icon': '', + 'cover': None, + 'parentId': None, + 'blockIds': ['blk-b1', 'blk-b2'], + 'favorite': False, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-06-05T00:00:00.000Z', + 'properties': {}}}, + 'blocks': { 'blk-b1': { 'id': 'blk-b1', + 'type': 'text', + 'content': 'Working title: The Remote ' + 'Onboarding Playbook. Audience: new ' + 'remote hires.', + 'properties': {}, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-05-20T00:00:00.000Z'}, + 'blk-b2': { 'id': 'blk-b2', + 'type': 'text', + 'content': 'Required H2s: First Week; Tools & ' + 'Access. CTA: book a demo.', + 'properties': {}, + 'createdDate': '2026-05-20T00:00:00.000Z', + 'lastEditedDate': '2026-05-20T00:00:00.000Z'}}, + 'trash': [], + 'comments': {}, + 'settings': { 'appearance': 'light', + 'startWeekMonday': False, + 'fontSize': 'default'}, + 'notifications': [], + 'pageOrder': ['page-brief'], + 'focusBlockId': None}, + '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-style': { 'id': 'd-style', + 'title': 'Brand Style Guide', + 'content': '

style

', + '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': ''}}, + 'trello_mock': { 'currentUser': 'u1', + 'users': { 'u1': { 'id': 'u1', + 'name': 'Sarah Chen', + 'username': 'sarah', + 'initials': 'SC', + 'email': 'sarah.chen@acme.com', + 'avatarUrl': ''}, + 'u2': { 'id': 'u2', + 'name': 'Bob Lee', + 'username': 'bob', + 'initials': 'BL', + 'email': 'bob@acme.com', + 'avatarUrl': ''}}, + 'boards': { 'board-1': { 'id': 'board-1', + 'title': 'Project Alpha', + 'description': '', + 'background': '#0079BF', + 'listIds': ['list-1', 'list-2', 'list-3'], + 'starred': False, + 'visibility': 'workspace', + 'archivedListIds': [], + 'archivedCardIds': [], + 'labels': [], + 'memberIds': ['u1', 'u2'], + 'createdAt': '2026-01-15T10:00:00.000Z'}}, + 'lists': { 'list-1': { 'id': 'list-1', + 'title': 'Draft', + 'boardId': 'board-1', + 'cardIds': ['card-ro'], + 'archived': False}, + 'list-2': { 'id': 'list-2', + 'title': 'Review', + 'boardId': 'board-1', + 'cardIds': [], + 'archived': False}, + 'list-3': { 'id': 'list-3', + 'title': 'Published', + 'boardId': 'board-1', + 'cardIds': [], + 'archived': False}}, + 'cards': { 'card-ro': { 'id': 'card-ro', + 'title': 'Remote Onboarding article', + 'description': '', + 'listId': 'list-1', + 'boardId': 'board-1', + 'labelIds': [], + 'memberIds': [], + 'dueDate': None, + 'startDate': None, + 'completed': False, + 'cover': None, + 'checklists': [], + 'comments': [], + 'attachments': [], + 'archived': False, + 'watching': False, + 'position': 0, + 'createdAt': '2026-01-20T10:00:00.000Z'}, + 'card-x': { 'id': 'card-x', + 'title': 'Q3 webinar recap', + 'description': '', + 'listId': 'list-1', + 'boardId': 'board-1', + 'labelIds': [], + 'memberIds': [], + 'dueDate': None, + 'startDate': None, + 'completed': False, + 'cover': None, + 'checklists': [], + 'comments': [], + 'attachments': [], + 'archived': False, + 'watching': False, + 'position': 0, + 'createdAt': '2026-01-20T10:00:00.000Z'}}, + 'boardOrder': ['board-1']}, + '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': 'marketing', + 'name': 'marketing', + 'description': 'marketing 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': [], + 'marketing': [ { 'messageId': 'm1', + 'senderId': 'user_2', + 'content': 'is the remote onboarding ' + 'piece drafted yet?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward.py b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..3e50a75a945c9b43b8130965e7689c055ba876d8 --- /dev/null +++ b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward.py @@ -0,0 +1,116 @@ +""" +Reward Script: cm_brief_to_draft_b97 +Task ID: 4619652a-02e6-5961-83df-6860dfb3ef29 +Domain: mock_websites +Mocks: notion_mock, google_docs_mock, trello_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.2] new article draft created + - [0.3] draft has both H2s and the demo CTA + - [0.3] card moved to Review list + - [0.1] slack_new_msg + - [0.1] tells team it's in review +""" +import re +import sys + +import requests + +MOCK_URLS = { + "notion_mock": "http://28.7.186.212:8186", + "google_docs_mock": "http://28.7.186.212:8162", + "trello_mock": "http://28.7.186.212:8202", + "slack_mock": "http://28.7.186.212:8198" +} +SEED = { + "slack_mock:general": [], + "slack_mock:marketing": [ + "m1" + ], + "slack_mock:random": [] +} + +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +STATES = {} +for _name, _url in MOCK_URLS.items(): + try: + _r = requests.get(f'{_url}/go?sid={sid}', timeout=15) + _r.raise_for_status() + STATES[_name] = _r.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {_name}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def cur(mock): + return (STATES.get(mock) or {}).get('current_state') or {} + + +def _lc(s): + return (s or '').lower() + + +total = 0.0 + +# c0: a new google doc titled about (new article draft 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 ['remote onboarding playbook', 'remote onboarding'])] +if c0_new: + print('PASS: new article draft created (0.2)') + total += 0.2 +else: + print('FAIL: new article draft created') + +# c1: new google doc body (draft has both H2s and the demo CTA) +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 ['remote onboarding playbook', 'remote onboarding'])] +c1_txt = _lc(' '.join(d.get('content','') for d in c1_new)) +if c1_new and all(t in c1_txt for t in ['first week', 'tools & access', 'demo']): + print('PASS: draft has both H2s and the demo CTA (0.3)') + total += 0.3 +else: + print('FAIL: draft has both H2s and the demo CTA') + +# c2: trello card card-ro listId == 'list-2' +c2_card = (cur('trello_mock').get('cards') or {}).get('card-ro') +if c2_card and c2_card.get('listId') == 'list-2': + print('PASS: card moved to Review list (0.3)') + total += 0.3 +else: + print('FAIL: card moved to Review list') + +# c3: new message by user_1 in #marketing +c3_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or [] +c3_seed = set(SEED.get('slack_mock:marketing', [])) +c3_new = [m for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1'] +c3_blob = _lc(' '.join((m.get('content') or '') for m in c3_new)) +if c3_new: + print('PASS: new message by user_1 in #marketing (0.1)') + total += 0.1 +else: + print('FAIL: no new user_1 message in #marketing') + +# c4: slack #marketing contains (tells team it\'s in review) +c4_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or [] +c4_seed = set(SEED.get('slack_mock:marketing', [])) +c4_blob = _lc(' '.join((m.get('content') or '') for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1')) +if any(t in c4_blob for t in ['review', 'draft']): + print('PASS: tells team it\'s in review (0.1)') + total += 0.1 +else: + print('FAIL: tells team it\'s in review') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward_label.json b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..cf13c4dbcb12fe117ece7d6df0c2aa0b3f352a82 --- /dev/null +++ b/legacy/4619652a-02e6-5961-83df-6860dfb3ef29/reward_label.json @@ -0,0 +1,71 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/4619652a-02e6-5961-83df-6860dfb3ef29/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:18:50", + "label": { + "task_id": "4619652a-02e6-5961-83df-6860dfb3ef29", + "domain": "mock_websites", + "summary": "验证用户是否根据 brief 在 Google Docs 创建包含特定 H2 和 demo CTA 的新文章草稿,将 Trello 卡片移到 Review 列表,并在 Slack #marketing 频道通知团队稿件已进入 review 阶段", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "notion_mock", + "google_docs_mock", + "trello_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 0", + "weight": 0.2, + "description": "检查是否在 Google Docs 中创建了新的文章草稿", + "check_logic": "对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 documentId 不在初始集合中的新文档,并检查其 title(转小写后)是否包含 'remote onboarding playbook' 或 'remote onboarding'", + "pass_condition": "存在至少一个新增文档且标题包含指定关键词" + }, + { + "name": "Component 1", + "weight": 0.3, + "description": "检查新文章草稿正文是否包含两个指定的 H2 标题和 demo CTA", + "check_logic": "获取 Component 0 中识别出的新文档,将其 content 拼接并转小写为 c1_txt,检查是否同时包含 'first week'、'tools & access' 和 'demo'", + "pass_condition": "新文档内容同时包含 'first week'、'tools & access' 和 'demo'" + }, + { + "name": "Component 2", + "weight": 0.3, + "description": "检查 Trello 卡片是否被移动到 Review 列表", + "check_logic": "检查 trello_mock current_state 中 cards['card-ro'] 的 listId 字段是否等于 'list-2'", + "pass_condition": "card-ro 的 listId 为 'list-2'" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "检查 user_1 是否在 Slack #marketing 频道发送了新消息", + "check_logic": "获取 slack_mock current_state 中 marketing 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 中),筛选出发送者为 user_1 的新消息", + "pass_condition": "存在至少一条由 user_1 发送的、不在 seed 中的新消息" + }, + { + "name": "Component 4", + "weight": 0.1, + "description": "检查 Slack 新消息是否告知团队稿件已进入 review 阶段", + "check_logic": "将 user_1 在 #marketing 频道的新消息内容拼接并转小写,检查是否包含 'review' 或 'draft'", + "pass_condition": "消息内容包含 'review' 或 'draft'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或 sid 为空时提前退出并返回 0.0", + "从任一 mock 服务(notion_mock、google_docs_mock、trello_mock、slack_mock)拉取 current_state 失败时提前退出并返回 0.0", + "Google Docs 未新增标题匹配的文章草稿时 Component 0 不得分", + "新增草稿内容未同时包含 'first week'、'tools & access' 和 'demo' 时 Component 1 不得分", + "Trello 卡片 card-ro 的 listId 不是 'list-2' 时 Component 2 不得分", + "Slack #marketing 频道没有 user_1 发送的新消息时 Component 3 不得分", + "Slack 新消息内容不包含 'review' 或 'draft' 时 Component 4 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后依次向四个 mock 服务请求当前状态并缓存到 STATES 字典中,任一请求失败也会直接返回 0.0。评分按以下顺序执行:1)Component 0 检查 Google Docs 中是否新增了标题包含 'remote onboarding playbook' 或 'remote onboarding' 的文档,通过则加 0.2;2)Component 1 检查这些新增文档的正文内容(转小写后)是否同时包含 'first week'、'tools & access' 和 'demo',通过则加 0.3;3)Component 2 检查 trello_mock 中 cards['card-ro'] 的 listId 是否等于 'list-2',通过则加 0.3;4)Component 3 检查 slack_mock 的 #marketing 频道中是否存在由 user_1 发送的、不在 SEED 预置消息中的新消息,通过则加 0.1;5)Component 4 检查上述 user_1 的新消息内容(转小写后)是否包含 'review' 或 'draft',通过则加 0.1。各组件独立计分,最终总分通过 min(total, 1.0) 钳制到 1.0 上限并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. **Docstring 信息**:\n - Reward Script: cm_brief_to_draft_b97\n - Task ID: 4619652a-02e6-5961-83df-6860dfb3ef29\n - Domain: mock_websites\n - Mocks: notion_mock, google_docs_mock, trello_mock, slack_mock\n - Scoring: total = 1.0\n - [0.2] new article draft created\n - [0.3] draft has both H2s and the demo CTA\n - [0.3] card moved to Review list\n - [0.1] slack_new_msg\n - [0.1] tells team it's in review\n\n2. **数据源**:\n - `/tmp/task_web_sid` 文件获取 sid\n - 四个 mock 服务: notion_mock, google_docs_mock, trello_mock, slack_mock\n - 通过 HTTP GET 请求获取状态\n\n3. **评分组件**:\n - **Component 0 (0.2)**: 检查 google_docs_mock 中是否有新创建的文档,标题包含 'remote onboarding playbook' 或 'remote onboarding'\n - **Component 1 (0.3)**: 检查新创建的 google doc 内容是否包含 'first week', 'tools & access', 'demo'(不区分大小写)\n - **Component 2 (0.3)**: 检查 trello_mock 中 card-ro 的 listId 是否为 'list-2'\n - **Component 3 (0.1)**: 检查 slack_mock 的 marketing 频道中是否有 user_1 发送的新消息(排除 seed 中的消息)\n - **Component 4 (0.1)**: 检查 slack_mock 的 marketing 频道中 user_1 的新消息内容是否包含 'review' 或 'draft'\n\n4. **分数汇总**:\n - 各组件分数相加\n - 最后 `final = round(min(total, 1.0), 4)`,即相加后钳制到 1.0\n\n5. **失败模式**:\n - 读取 sid 失败 -> 打印 CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取任何 mock 状态失败 -> 打印 CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出\n\n6. **is_placeholder**: false,因为这是一个真正的评分脚本,有具体的检查逻辑。\n\n7. **confidence**: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON:\n\n- task_id: \"4619652a-02e6-5961-83df-6860dfb3ef29\"\n- domain: \"mock_websites\"\n- summary: \"验证用户是否根据 brief 在 Google Docs 创建包含特定 H2 和 CTA 的新文章草稿,将 Trello 卡片移到 Review 列表,并在 Slack marketing 频道通知团队稿件已进入 review 阶段\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"notion_mock\", \"google_docs_mock\", \"trello_mock\", \"slack_mock\"]\n- scoring_components: 5 个组件\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到 4 位小数\"\n- failure_modes: [\"读取 /tmp/task_web_sid 失败或 sid 为空\", \"从任一 mock 服务拉取当前状态失败\"]\n- scoring_logic_explanation: 详细说明执行顺序...\n- confidence: 1.0\n\n确保所有字符串 value 使用中文,但代码标识符保留原样。\n\n检查每个组件的 check_logic 和 pass_condition:\n\nComponent 1:\n- name: \"Component 0\" 或 \"new article draft created\"\n- weight: 0.2\n- description: \"检查是否在 Google Docs 中创建了新的文章草稿\"\n- check_logic: \"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出不在初始集合中的新文档,并检查其 title(转小写后)是否包含 'remote onboarding playbook' 或 'remote onboarding'\"\n- pass_condition: \"存在至少一个新增文档且标题包含指定关键词\"\n\nComponent 2:\n- name: \"Component 1\" 或 \"draft has both H2s and the demo CTA\"\n- weight: 0.3\n- description: \"检查新文章草稿正文是否包含两个指定的 H2 标题和 demo CTA\"\n- check_logic: \"获取 Component 0 中识别出的新文档,将其 content 拼接并转小写,检查是否同时包含 'first week'、'tools & access' 和 'demo'\"\n- pass_condition: \"新文档内容同时包含 'first week'、'tools & access' 和 'demo'\"\n\nComponent 3:\n- name: \"Component 2\" 或 \"card moved to Review list\"\n- weight: 0.3\n- description: \"检查 Trello 卡片是否被移动到 Review 列表\"\n- check_logic: \"检查 trello_mock current_state 中 cards['card-ro'] 的 listId 字段是否等于 'list-2'\"\n- pass_condition: \"card-ro 的 listId 为 'list-2'\"\n\nComponent 4:\n- name: \"Component 3\" 或 \"slack_new_msg\"\n- weight: 0.1\n- description: \"检查 user_1 是否在 Slack #marketing 频道发送了新消息\"\n- check_logic: \"获取 slack_mock current_state 中 marketing 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 中),筛选出发送者为 user_1 的新消息\"\n- pass_condition: \"存在至少一条由 user_1 发送的、不在 seed 中的新消息\"\n\nComponent 5:\n- name: \"Component 4\" 或 \"tells team it's in review\"\n- weight: 0.1\n- description: \"检查 Slack 新消息是否告知团队稿件已进入 review 阶段\"\n- check_logic: \"将 user_1 在 #marketing 频道的新消息内容拼接并转小写,检查是否包含 'review' 或 'draft'\"\n- pass_condition: \"消息内容包含 'review' 或 'draft'\"\n\nfailure_modes 还需要包括各组件失败只是不得分,但有两个 critical 提前退出。\n\n让我再仔细看看代码中的变量名和逻辑,确保准确。\n\nc0_init: 从 STATES['google_docs_mock'].get('initial_state') 获取 documents 的 keys\nc0_docs: cur('google_docs_mock').get('documents') or {}\nc0_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 ['remote onboarding playbook', 'remote onboarding'])]\n\nc1 和 c0 类似,但检查 content。\n\nc2_card = (cur('trello_mock').get('cards') or {}).get('card-ro')\nif c2_card and c2_card.get('listId') == 'list-2':\n\nc3: c3_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or []\nc3_seed = set(SEED.get('slack_mock:marketing', []))\nc3_new = [m for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1']\n\nc4: c4_msgs = ... 同上\nc4_seed = ... 同上\nc4_blob = _lc(' '.join((m.get('content') or '') for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1'))\nif any(t in c4_blob for t in ['review', 'draft']):\n\n注意 c4 检查的是所有 user_1 的新消息(不一定是 c3_new 中的,但逻辑一样),内容包含 review 或 draft。\n\n最终输出 JSON,不要 markdown 代码块,第一个字符是 {,最后一个是 }。\n\n确保 JSON 格式正确,没有 trailing comma。\n\nsummary 用中文。\n\nscoring_logic_explanation 要详细:\n1. 从 /tmp/task_web_sid 读取会话 ID\n2. 向四个 mock 服务获取 current_state\n3. 组件 0:检查 Google Docs 新增文档标题\n4. 组件 1:检查新增文档内容关键词\n5. 组件 2:检查 Trello 卡片 listId\n6. 组件 3:检查 Slack #marketing 新消息\n7. 组件 4:检查 Slack 消息内容\n8. 累加分数,min(total, 1.0) 并四舍五入\n\nconfidence: 1.0\n\nis_placeholder: false\n\ndomain: mock_websites\n\ntask_id: 4619652a-02e6-5961-83df-6860dfb3ef29\n\ndata_sources: [\"/tmp/task_web_sid\", \"notion_mock\", \"google_docs_mock\", \"trello_mock\", \"slack_mock\"] (notion_mock 虽然在 MOCK_URLS 中,但评分逻辑里没有用到,不过它确实从该数据源获取了状态,所以应该包含)\n\n让我再确认一下 docstring 中的 task_id 和 domain。docstring 明确写了 Task ID: 4619652a-02e6-5961-83df-6860dfb3ef29 和 Domain: mock_websites。\n\n好,构建最终 JSON。 {\"task_id\":\"4619652a-02e6-5961-83df-6860dfb3ef29\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否根据 brief 在 Google Docs 创建包含特定 H2 和 demo CTA 的新文章草稿,将 Trello 卡片移到 Review 列表,并在 Slack #marketing 频道通知团队稿件已进入 review 阶段\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"notion_mock\",\"google_docs_mock\",\"trello_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 0\",\"weight\":0.2,\"description\":\"检查是否在 Google Docs 中创建了新的文章草稿\",\"check_logic\":\"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 documentId 不在初始集合中的新文档,并检查其 title(转小写后)是否包含 'remote onboarding playbook' 或 'remote onboarding'\",\"pass_condition\":\"存在至少一个新增文档且标题包含指定关键词\"},{\"name\":\"Component 1\",\"weight\":0.3,\"description\":\"检查新文章草稿正文是否包含两个指定的 H2 标题和 demo CTA\",\"check_logic\":\"获取 Component 0 中识别出的新文档,将其 content 拼接并转小写为 c1_txt,检查是否同时包含 'first week'、'tools & access' 和 'demo'\",\"pass_condition\":\"新文档内容同时包含 'first week'、'tools & access' 和 'demo'\"},{\"name\":\"Component 2\",\"weight\":0.3,\"description\":\"检查 Trello 卡片是否被移动到 Review 列表\",\"check_logic\":\"检查 trello_mock current_state 中 cards['card-ro'] 的 listId 字段是否等于 'list-2'\",\"pass_condition\":\"card-ro 的 listId 为 'list-2'\"},{\"name\":\"Component 3\",\"weight\":0.1,\"description\":\"检查 user_1 是否在 Slack #marketing 频道发送了新消息\",\"check_logic\":\"获取 slack_mock current_state 中 marketing 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 中),筛选出发送者为 user_1 的新消息\",\"pass_condition\":\"存在至少一条由 user_1 发送的、不在 seed 中的新消息\"},{\"name\":\"Component 4\",\"weight\":0.1,\"description\":\"检查 Slack 新消息是否告知团队稿件已进入 review 阶段\",\"check_logic\":\"将 user_1 在 #marketing 频道的新消息内容拼接并转小写,检查是否包含 'review' 或 'draft'\",\"pass_condition\":\"消息内容包含 'review' 或 'draft'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或 sid 为空时提前退出并返回 0.0\",\"从任一 mock 服务(notion_mock、google_docs_mock、trello_mock、slack_mock)拉取 current_state 失败时提前退出并返回 0.0\",\"Google Docs 未新增标题匹配的文章草稿时 Component 0 不得分\",\"新增草稿内容未同时包含 'first week'、'tools & access' 和 'demo' 时 Component 1 不得分\",\"Trello 卡片 card-ro 的 listId 不是 'list-2' 时 Component 2 不得分\",\"Slack #marketing 频道没有 user_1 发送的新消息时 Component 3 不得分\",\"Slack 新消息内容不包含 'review' 或 'draft' 时 Component 4 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后依次向四个 mock 服务请求当前状态并缓存到 STATES 字典中,任一请求失败也会直接返回 0.0。评分按以下顺序执行:1)Component 0 检查 Google Docs 中是否新增了标题包含 'remote onboarding playbook' 或 'remote onboarding' 的文档,通过则加 0.2;2)Component 1 检查这些新增文档的正文内容(转小写后)是否同时包含 'first week'、'tools & access' 和 'demo',通过则加 0.3;3)Component 2 检查 trello_mock 中 cards['card-ro'] 的 listId 是否等于 'list-2',通过则加 0.3;4)Component 3 检查 slack_mock 的 #marketing 频道中是否存在由 user_1 发送的、不在 SEED 预置消息中的新消息,通过则加 0.1;5)Component 4 检查上述 user_1 的新消息内容(转小写后)是否包含 'review' 或 'draft',通过则加 0.1。各组件独立计分,最终总分通过 min(total, 1.0) 钳制到 1.0 上限并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/_cua_gym_vm_bridge.sh b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/initial_setup.py b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb1789fe742e006b5a8aca83f709722fb69bfad --- /dev/null +++ b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/initial_setup.py @@ -0,0 +1,307 @@ +""" +Initial Setup: cm_editorial_plan_b99 +Task ID: 57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f +Domain: mock_websites +Mocks: asana_mock, google_calendar_mock, google_docs_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a marketing program manager. Your tools for this task are: the Asana project, the team calendar, shared documents, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Asana 'Q1 Product Launch' project with 1 task(s); an empty Google Calendar; Google Docs with documents 'Editorial Calendar'; Slack workspace with channels #general, #marketing, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: new July feature task in Asana (+0.25); cal_new_event (+0.1); publish event titled (+0.1); publish date July 2 (+0.15); outline doc created (+0.1); outline has Problem/Approach/Results (+0.1); slack_new_msg (+0.1); names the July 2 publish date (+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 = { + "asana_mock": "http://28.7.186.212:8134", + "google_calendar_mock": "http://28.7.186.212:8161", + "google_docs_mock": "http://28.7.186.212:8162", + "slack_mock": "http://28.7.186.212:8198" +} +PRIMARY_URL = 'http://28.7.186.212:8134' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# Full initial state for every mock involved (all required top-level keys present). +STATES = { 'asana_mock': { 'currentUser': { 'userId': 'user-0', + 'name': 'Alex Johnson', + 'email': 'alex.johnson@company.com', + 'avatar': 'https://picsum.photos/100/100?random=user0', + 'title': 'Product Manager', + 'department': 'Product', + 'location': 'SF', + 'timezone': 'PST', + 'theme': 'light'}, + 'users': [ { 'userId': 'user-0', + 'name': 'Alex Johnson', + 'email': 'alex.johnson@company.com'}, + { 'userId': 'user-1', + 'name': 'Sarah Chen', + 'email': 'sarah.chen@company.com'}, + { 'userId': 'user-2', + 'name': 'Mike Rodriguez', + 'email': 'mike.r@company.com'}], + 'teams': [ { 'teamId': 'team-1', + 'name': 'Product', + 'description': '', + 'memberIds': ['user-0', 'user-1', 'user-2'], + 'ownerId': 'user-0', + 'privacy': 'public', + 'createdDate': '2026-01-01T00:00:00Z'}], + 'projects': [ { 'projectId': 'project-1', + 'name': 'Q1 Product Launch', + 'teamId': 'team-1', + 'description': '', + 'color': 'blue', + 'icon': 'rocket', + 'ownerId': 'user-0', + 'memberIds': ['user-0', 'user-1', 'user-2'], + 'sections': [ { 'sectionId': 'section-1-1', + 'name': 'To Do', + 'collapsed': False}, + { 'sectionId': 'section-1-2', + 'name': 'In Progress', + 'collapsed': False}], + 'customFields': [], + 'privacy': 'public', + 'startDate': None, + 'dueDate': None, + 'archived': False, + 'starred': False, + 'createdDate': '2026-01-01T00:00:00Z', + 'modifiedDate': '2026-01-01T00:00:00Z'}], + 'tasks': [ { 'taskId': 't-seed', + 'name': 'Update media kit', + 'projectId': 'project-1', + 'sectionId': 'section-1-1', + 'description': '', + 'assigneeId': None, + 'creatorId': 'user-0', + 'dueDate': None, + 'startDate': None, + 'completed': False, + 'completedDate': None, + 'parentTaskId': None, + 'dependencies': [], + 'tags': [], + 'attachmentIds': [], + 'customFieldValues': {}, + 'likeCount': 0, + 'createdDate': '2026-06-01T00:00:00Z', + 'modifiedDate': '2026-06-01T00:00:00Z'}], + 'comments': [], + 'portfolios': [], + 'goals': [], + 'notifications': [], + 'attachments': []}, + 'google_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}}, + '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-cal': { 'id': 'd-cal', + 'title': 'Editorial Calendar', + 'content': '

cal

', + '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': ''}}, + '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': 'marketing', + 'name': 'marketing', + 'description': 'marketing 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': [], + 'marketing': [ { 'messageId': 'm1', + 'senderId': 'user_2', + 'content': "what's the July feature " + 'plan?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward.py b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7157f2fea7e950b5c0d00d1785a105f2555160 --- /dev/null +++ b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward.py @@ -0,0 +1,146 @@ +""" +Reward Script: cm_editorial_plan_b99 +Task ID: 57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f +Domain: mock_websites +Mocks: asana_mock, google_calendar_mock, google_docs_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.25] new July feature task in Asana + - [0.1] cal_new_event + - [0.1] publish event titled + - [0.15] publish date July 2 + - [0.1] outline doc created + - [0.1] outline has Problem/Approach/Results + - [0.1] slack_new_msg + - [0.1] names the July 2 publish date +""" +import re +import sys + +import requests + +MOCK_URLS = { + "asana_mock": "http://28.7.186.212:8134", + "google_calendar_mock": "http://28.7.186.212:8161", + "google_docs_mock": "http://28.7.186.212:8162", + "slack_mock": "http://28.7.186.212:8198" +} +SEED = { + "slack_mock:general": [], + "slack_mock:marketing": [ + "m1" + ], + "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 asana task about (new July feature task in Asana) +c0_init = {t.get('taskId') for t in ((STATES['asana_mock'].get('initial_state') or {}).get('tasks') or [])} +c0_new = [t for t in (cur('asana_mock').get('tasks') or []) if t.get('taskId') not in c0_init and any(x in _lc(t.get('name','')) for x in ['july feature', 'ai in support'])] +if c0_new: + print('PASS: new July feature task in Asana (0.25)') + total += 0.25 +else: + print('FAIL: new July feature task in Asana') + +# c1: a new calendar event was created +c1_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])} +c1_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c1_init_ids] +globals()['cal_new_events'] = c1_new +if c1_new: + print('PASS: new calendar event (0.1)') + total += 0.1 +else: + print('FAIL: no new calendar event') + +# c2: new event title (publish event titled) +c2_new = globals().get('cal_new_events', []) +if any(any(t in _lc(e.get('title','')) for t in ['publish: ai in support', 'ai in support', 'publish']) for e in c2_new): + print('PASS: publish event titled (0.1)') + total += 0.1 +else: + print('FAIL: publish event titled') + +# c3: new event date contains '2026-07-02' +c3_new = globals().get('cal_new_events', []) +if any('2026-07-02' in (e.get('start','') or '') for e in c3_new): + print('PASS: publish date July 2 (0.15)') + total += 0.15 +else: + print('FAIL: publish date July 2') + +# c4: a new google doc titled about (outline doc created) +c4_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys()) +c4_docs = cur('google_docs_mock').get('documents') or {} +c4_new = [d for did, d in c4_docs.items() if did not in c4_init and any(t in _lc(d.get('title','')) for t in ['ai in support - outline', 'ai in support'])] +if c4_new: + print('PASS: outline doc created (0.1)') + total += 0.1 +else: + print('FAIL: outline doc created') + +# c5: new google doc body (outline has Problem/Approach/Results) +c5_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys()) +c5_docs = cur('google_docs_mock').get('documents') or {} +c5_new = [d for did, d in c5_docs.items() if did not in c5_init and any(t in _lc(d.get('title','')) for t in ['ai in support'])] +c5_txt = _lc(' '.join(d.get('content','') for d in c5_new)) +if c5_new and all(t in c5_txt for t in ['problem', 'approach', 'results']): + print('PASS: outline has Problem/Approach/Results (0.1)') + total += 0.1 +else: + print('FAIL: outline has Problem/Approach/Results') + +# c6: new message by user_1 in #marketing +c6_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or [] +c6_seed = set(SEED.get('slack_mock:marketing', [])) +c6_new = [m for m in c6_msgs if m.get('messageId') not in c6_seed and m.get('senderId') == 'user_1'] +c6_blob = _lc(' '.join((m.get('content') or '') for m in c6_new)) +if c6_new: + print('PASS: new message by user_1 in #marketing (0.1)') + total += 0.1 +else: + print('FAIL: no new user_1 message in #marketing') + +# c7: slack #marketing contains (names the July 2 publish date) +c7_msgs = (cur('slack_mock').get('messages') or {}).get('marketing', []) or [] +c7_seed = set(SEED.get('slack_mock:marketing', [])) +c7_blob = _lc(' '.join((m.get('content') or '') for m in c7_msgs if m.get('messageId') not in c7_seed and m.get('senderId') == 'user_1')) +if any(t in c7_blob for t in ['july 2', 'july 2nd', '2026-07-02', 'july feature']): + print('PASS: names the July 2 publish date (0.1)') + total += 0.1 +else: + print('FAIL: names the July 2 publish date') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward_label.json b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..83904eceb0e549a32b8b947ef05dfb6c3713c633 --- /dev/null +++ b/legacy/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/reward_label.json @@ -0,0 +1,88 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f/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:40", + "label": { + "task_id": "57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f", + "domain": "mock_websites", + "summary": "验证在 Asana、Google Calendar、Google Docs 和 Slack 中是否完成了关于 AI in Support 的编辑计划任务,包括创建任务、日历事件、文档大纲和营销频道消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "asana_mock", + "google_calendar_mock", + "google_docs_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.25, + "description": "在 Asana 中创建关于 July feature 的新任务", + "check_logic": "对比 asana_mock 的 initial_state 与 current_state 中的 tasks,找出 taskId 不在初始集合中的新任务,检查其 name 字段(转小写后)是否包含 'july feature' 或 'ai in support'", + "pass_condition": "存在新任务且任务名称包含 'july feature' 或 'ai in support'" + }, + { + "name": "Component 2", + "weight": 0.1, + "description": "在 Google Calendar 中创建新事件", + "check_logic": "对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,找出 id 不在初始集合中的新事件", + "pass_condition": "存在至少一个新创建的事件" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "新日历事件的标题包含发布相关字样", + "check_logic": "在 Component 2 筛选出的新事件中,检查 title 字段(转小写后)是否包含 'publish: ai in support'、'ai in support' 或 'publish'", + "pass_condition": "新事件标题包含 'publish: ai in support'、'ai in support' 或 'publish'" + }, + { + "name": "Component 4", + "weight": 0.15, + "description": "新日历事件的日期为 2026-07-02", + "check_logic": "在 Component 2 筛选出的新事件中,检查 start 字段是否包含字符串 '2026-07-02'", + "pass_condition": "新事件的开始日期包含 '2026-07-02'" + }, + { + "name": "Component 5", + "weight": 0.1, + "description": "在 Google Docs 中创建 AI in Support 大纲文档", + "check_logic": "对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 document id 不在初始集合中的新文档,检查 title 字段(转小写后)是否包含 'ai in support - outline' 或 'ai in support'", + "pass_condition": "存在新文档且标题包含 'ai in support - outline' 或 'ai in support'" + }, + { + "name": "Component 6", + "weight": 0.1, + "description": "新文档内容包含 Problem、Approach、Results 三部分", + "check_logic": "在标题包含 'ai in support' 的新文档中,提取 content 字段拼接并转小写,检查是否同时包含 'problem'、'approach'、'results'", + "pass_condition": "存在标题包含 'ai in support' 的新文档,且其内容同时包含 'problem'、'approach'、'results'" + }, + { + "name": "Component 7", + "weight": 0.1, + "description": "在 Slack #marketing 频道中 user_1 发送了新消息", + "check_logic": "检查 slack_mock current_state 中 messages.marketing 列表,筛选出 messageId 不在 SEED['slack_mock:marketing'] 中且 senderId 为 'user_1' 的消息", + "pass_condition": "存在至少一条 user_1 在 #marketing 频道发送的新消息" + }, + { + "name": "Component 8", + "weight": 0.1, + "description": "Slack 消息中提及 July 2 发布日期", + "check_logic": "提取 #marketing 频道中 user_1 的新消息内容,拼接转小写后,检查是否包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'", + "pass_condition": "user_1 在 #marketing 的新消息内容包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最后用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并返回 0.0 后退出", + "请求任意 mock 服务(asana_mock、google_calendar_mock、google_docs_mock、slack_mock)状态失败时,打印 CRITICAL 并返回 0.0 后退出", + "各组件检查不通过时仅不加分,不会导致提前退出" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 asana_mock、google_calendar_mock、google_docs_mock 和 slack_mock 发送 HTTP GET 请求获取当前状态与初始状态。接着按顺序执行 8 项独立检查:1)Asana 中是否有名称包含 'july feature' 或 'ai in support' 的新任务;2)Google Calendar 中是否有新事件;3)新事件标题是否包含发布相关字样;4)新事件日期是否为 2026-07-02;5)Google Docs 中是否创建了 AI in Support 大纲文档;6)新文档内容是否同时包含 Problem、Approach、Results;7)Slack #marketing 中 user_1 是否发送了新消息;8)该消息是否提及 July 2 发布日期。每项通过即累加对应分值,最终总分通过 min(total, 1.0) 限制在 1.0 以内,四舍五入后输出 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 看,Task ID 是 `57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f`,但 docstring 开头也写了 `Reward Script: cm_editorial_plan_b99`。根据要求\"从文件 docstring 中提取的任务 ID\",这里明确写了 Task ID: 57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f,所以 task_id 应该是这个 UUID。\n\n2. **Domain**: docstring 中写了 `Domain: mock_websites`\n\n3. **Summary**: 一句话概括。这个脚本验证在多个 mock 服务(Asana、Google Calendar、Google Docs、Slack)中是否完成了关于\"AI in Support\"的编辑计划任务,包括创建任务、日历事件、文档大纲和 Slack 消息。\n\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n\n5. **data_sources**: 脚本从 `/tmp/task_web_sid` 读取 sid,然后从 `asana_mock`, `google_calendar_mock`, `google_docs_mock`, `slack_mock` 获取状态。\n\n6. **scoring_components**: 有 8 个组件,分值在 docstring 中明确给出:\n - c0: 0.25 - new July feature task in Asana\n - c1: 0.1 - cal_new_event\n - c2: 0.1 - publish event titled\n - c3: 0.15 - publish date July 2\n - c4: 0.1 - outline doc created\n - c5: 0.1 - outline has Problem/Approach/Results\n - c6: 0.1 - slack_new_msg\n - c7: 0.1 - names the July 2 publish date\n\n让我详细分析每个组件的检查逻辑:\n\n**Component 1 (c0)**: \n- 检查 Asana 中是否有新任务(taskId 不在 initial_state 中)\n- 任务名称包含 'july feature' 或 'ai in support'\n- 通过则 +0.25\n\n**Component 2 (c1)**:\n- 检查 Google Calendar 中是否有新事件(id 不在 initial_state 中)\n- 通过则 +0.1\n\n**Component 3 (c2)**:\n- 检查新事件的标题(在 c1_new 中)是否包含 'publish: ai in support'、'ai in support' 或 'publish'\n- 通过则 +0.1\n\n**Component 4 (c3)**:\n- 检查新事件的开始日期是否包含 '2026-07-02'\n- 通过则 +0.15\n\n**Component 5 (c4)**:\n- 检查 Google Docs 中是否有新文档(document id 不在 initial_state 中)\n- 标题包含 'ai in support - outline' 或 'ai in support'\n- 通过则 +0.1\n\n**Component 6 (c5)**:\n- 检查 Google Docs 新文档(标题包含 'ai in support')的内容\n- 内容(转小写后)必须同时包含 'problem'、'approach'、'results'\n- 通过则 +0.1\n\n**Component 7 (c6)**:\n- 检查 Slack #marketing 频道中是否有 user_1 发送的新消息(messageId 不在 SEED 中,senderId == 'user_1')\n- 通过则 +0.1\n\n**Component 8 (c7)**:\n- 检查 Slack #marketing 中 user_1 的新消息内容是否包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'\n- 通过则 +0.1\n\n7. **total_max_score**: 1.0\n\n8. **score_aggregation**: 各组件分数相加,最后用 `min(total, 1.0)` 钳制到上限 1.0,再四舍五入到 4 位小数。\n\n9. **failure_modes**:\n - 读取 `/tmp/task_web_sid` 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 获取任何 mock 服务状态失败:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出\n\n10. **scoring_logic_explanation**: 详细中文解释,按执行顺序:\n - 从 /tmp/task_web_sid 读取会话 ID\n - 向四个 mock 服务获取当前状态(current_state)和初始状态(initial_state)\n - 逐项检查 8 个条件,每个条件独立评分,通过则累加对应分值\n - 总分用 min(total, 1.0) 限制在 1.0 以内,四舍五入后输出\n\n11. **confidence**: 1.0,因为代码逻辑非常清晰。\n\n让我再仔细检查一下 task_id。docstring 中明确写了 \"Task ID: 57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f\",虽然文件名路径中也有这个 UUID,但 docstring 是明确标注的。\n\n检查各组件的 pass_condition:\n- c0: Asana 中有新任务,且任务名称(小写)包含 'july feature' 或 'ai in support'\n- c1: Google Calendar 中有新创建的事件(id 不在 initial_state 中)\n- c2: 新事件的标题(小写)包含 'publish: ai in support' 或 'ai in support' 或 'publish'\n- c3: 新事件的开始日期字符串包含 '2026-07-02'\n- c4: Google Docs 中有新文档,且标题(小写)包含 'ai in support - outline' 或 'ai in support'\n- c5: 新文档标题包含 'ai in support',且文档内容(小写)同时包含 'problem'、'approach'、'results'\n- c6: Slack #marketing 频道中有 senderId 为 'user_1' 且 messageId 不在 SEED 中的新消息\n- c7: Slack #marketing 中 user_1 的新消息内容(小写)包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'\n\n注意 c5 和 c4 的区别:c4 检查标题包含 'ai in support - outline' 或 'ai in support',c5 检查标题包含 'ai in support'(更宽),然后检查内容。\n\n注意 c7 和 c6 的区别:c6 只看是否有新消息,c7 看内容是否包含日期。\n\nJSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Asana、Google Calendar、Google Docs 和 Slack 中是否完成了关于 AI in Support 的编辑计划任务,包括创建任务、日历事件、文档大纲和营销频道消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"asana_mock\", \"google_calendar_mock\", \"google_docs_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.25,\n \"description\": \"在 Asana 中创建关于 July feature 的新任务\",\n \"check_logic\": \"对比 asana_mock 的 initial_state 与 current_state 中的 tasks,找出 taskId 不在初始集合中的新任务,检查其 name 字段(转小写后)是否包含 'july feature' 或 'ai in support'\",\n \"pass_condition\": \"存在新任务且任务名称包含 'july feature' 或 'ai in support'\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.1,\n \"description\": \"在 Google Calendar 中创建新事件\",\n \"check_logic\": \"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,找出 id 不在初始集合中的新事件\",\n \"pass_condition\": \"存在至少一个新创建的事件\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.1,\n \"description\": \"新日历事件的标题包含发布相关字样\",\n \"check_logic\": \"在 Component 2 筛选出的新事件中,检查 title 字段(转小写后)是否包含 'publish: ai in support'、'ai in support' 或 'publish'\",\n \"pass_condition\": \"新事件标题包含 'publish: ai in support'、'ai in support' 或 'publish'\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.15,\n \"description\": \"新日历事件的日期为 2026-07-02\",\n \"check_logic\": \"在 Component 2 筛选出的新事件中,检查 start 字段是否包含字符串 '2026-07-02'\",\n \"pass_condition\": \"新事件的开始日期包含 '2026-07-02'\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.1,\n \"description\": \"在 Google Docs 中创建 AI in Support 大纲文档\",\n \"check_logic\": \"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 document id 不在初始集合中的新文档,检查 title 字段(转小写后)是否包含 'ai in support - outline' 或 'ai in support'\",\n \"pass_condition\": \"存在新文档且标题包含 'ai in support - outline' 或 'ai in support'\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.1,\n \"description\": \"新文档内容包含 Problem、Approach、Results 三部分\",\n \"check_logic\": \"在标题包含 'ai in support' 的新文档中,提取 content 字段拼接并转小写,检查是否同时包含 'problem'、'approach'、'results'\",\n \"pass_condition\": \"存在标题包含 'ai in support' 的新文档,且其内容同时包含 'problem'、'approach'、'results'\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.1,\n \"description\": \"在 Slack #marketing 频道中 user_1 发送了新消息\",\n \"check_logic\": \"检查 slack_mock current_state 中 messages.marketing 列表,筛选出 messageId 不在 SEED['slack_mock:marketing'] 中且 senderId 为 'user_1' 的消息\",\n \"pass_condition\": \"存在至少一条 user_1 在 #marketing 频道发送的新消息\"\n },\n {\n \"name\": \"Component 8\",\n \"weight\": 0.1,\n \"description\": \"Slack 消息中提及 July 2 发布日期\",\n \"check_logic\": \"提取 #marketing 频道中 user_1 的新消息内容,拼接转小写后,检查是否包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'\",\n \"pass_condition\": \"user_1 在 #marketing 的新消息内容包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'\"\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 服务(asana_mock、google_calendar_mock、google_docs_mock、slack_mock)状态失败时,打印 CRITICAL 并返回 0.0 后退出\",\n \"各组件检查不通过时仅不加分,不会导致提前退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 asana_mock、google_calendar_mock、google_docs_mock 和 slack_mock 发送 HTTP GET 请求获取当前状态与初始状态。接着按顺序执行 8 项独立检查:1)Asana 中是否有名称包含 'july feature' 或 'ai in support' 的新任务;2)Google Calendar 中是否有新事件;3)新事件标题是否包含发布相关字样;4)新事件日期是否为 2026-07-02;5)Google Docs 中是否创建了 AI in Support 大纲文档;6)新文档内容是否同时包含 Problem、Approach、Results;7)Slack #marketing 中 user_1 是否发送了新消息;8)该消息是否提及 July 2 发布日期。每项通过即累加对应分值,最终总分通过 min(total, 1.0) 限制在 1.0 以内,四舍五入后输出 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查是否符合所有要求:\n- 只输出 JSON 对象:是\n- 没有 Markdown 代码块:是\n- 没有额外解释:是\n- 没有 thinking 标签:是\n- 第一个字符是 {,最后一个是 }:是\n- task_id、domain 正确:是\n- is_placeholder: false:是\n- data_sources 完整:是\n- scoring_components 有 8 个,weight 正确:是\n- total_max_score: 1.0:是\n- score_aggregation 正确:是\n- failure_modes 包含提前退出路径:是\n- scoring_logic_explanation 详细且按执行顺序:是\n- confidence: 1.0:是\n\n看起来都正确。 {\n \"task_id\": \"57f76e1c-93b4-5bc1-aa92-9ff6bab42d2f\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Asana、Google Calendar、Google Docs 和 Slack 中是否完成了关于 AI in Support 的编辑计划任务,包括创建任务、日历事件、文档大纲和营销频道消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"asana_mock\", \"google_calendar_mock\", \"google_docs_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.25,\n \"description\": \"在 Asana 中创建关于 July feature 的新任务\",\n \"check_logic\": \"对比 asana_mock 的 initial_state 与 current_state 中的 tasks,找出 taskId 不在初始集合中的新任务,检查其 name 字段(转小写后)是否包含 'july feature' 或 'ai in support'\",\n \"pass_condition\": \"存在新任务且任务名称包含 'july feature' 或 'ai in support'\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.1,\n \"description\": \"在 Google Calendar 中创建新事件\",\n \"check_logic\": \"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,找出 id 不在初始集合中的新事件\",\n \"pass_condition\": \"存在至少一个新创建的事件\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.1,\n \"description\": \"新日历事件的标题包含发布相关字样\",\n \"check_logic\": \"在 Component 2 筛选出的新事件中,检查 title 字段(转小写后)是否包含 'publish: ai in support'、'ai in support' 或 'publish'\",\n \"pass_condition\": \"新事件标题包含 'publish: ai in support'、'ai in support' 或 'publish'\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.15,\n \"description\": \"新日历事件的日期为 2026-07-02\",\n \"check_logic\": \"在 Component 2 筛选出的新事件中,检查 start 字段是否包含字符串 '2026-07-02'\",\n \"pass_condition\": \"新事件的开始日期包含 '2026-07-02'\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.1,\n \"description\": \"在 Google Docs 中创建 AI in Support 大纲文档\",\n \"check_logic\": \"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 document id 不在初始集合中的新文档,检查 title 字段(转小写后)是否包含 'ai in support - outline' 或 'ai in support'\",\n \"pass_condition\": \"存在新文档且标题包含 'ai in support - outline' 或 'ai in support'\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.1,\n \"description\": \"新文档内容包含 Problem、Approach、Results 三部分\",\n \"check_logic\": \"在标题包含 'ai in support' 的新文档中,提取 content 字段拼接并转小写,检查是否同时包含 'problem'、'approach'、'results'\",\n \"pass_condition\": \"存在标题包含 'ai in support' 的新文档,且其内容同时包含 'problem'、'approach'、'results'\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.1,\n \"description\": \"在 Slack #marketing 频道中 user_1 发送了新消息\",\n \"check_logic\": \"检查 slack_mock current_state 中 messages.marketing 列表,筛选出 messageId 不在 SEED['slack_mock:marketing'] 中且 senderId 为 'user_1' 的消息\",\n \"pass_condition\": \"存在至少一条 user_1 在 #marketing 频道发送的新消息\"\n },\n {\n \"name\": \"Component 8\",\n \"weight\": 0.1,\n \"description\": \"Slack 消息中提及 July 2 发布日期\",\n \"check_logic\": \"提取 #marketing 频道中 user_1 的新消息内容,拼接转小写后,检查是否包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'\",\n \"pass_condition\": \"user_1 在 #marketing 的新消息内容包含 'july 2'、'july 2nd'、'2026-07-02' 或 'july feature'\"\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 服务(asana_mock、google_calendar_mock、google_docs_mock、slack_mock)状态失败时,打印 CRITICAL 并返回 0.0 后退出\",\n \"各组件检查不通过时仅不加分,不会导致提前退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 asana_mock、google_calendar_mock、google_docs_mock 和 slack_mock 发送 HTTP GET 请求获取当前状态与初始状态。接着按顺序执行 8 项独立检查:1)Asana 中是否有名称包含 'july feature' 或 'ai in support' 的新任务;2)Google Calendar 中是否有新事件;3)新事件标题是否包含发布相关字样;4)新事件日期是否为 2026-07-02;5)Google Docs 中是否创建了 AI in Support 大纲文档;6)新文档内容是否同时包含 Problem、Approach、Results;7)Slack #marketing 中 user_1 是否发送了新消息;8)该消息是否提及 July 2 发布日期。每项通过即累加对应分值,最终总分通过 min(total, 1.0) 限制在 1.0 以内,四舍五入后输出 REWARD。\",\n \"confidence\": 1.0\n}" +} diff --git a/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward.py b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..49c0cf59aff7dc8db1c83a09d2f196fa0de299b5 --- /dev/null +++ b/legacy/a91f29df-e380-5d54-b965-27aecef4d2b3/reward.py @@ -0,0 +1,112 @@ +""" +Reward Script: se_linear_github_triage_b91 +Task ID: a91f29df-e380-5d54-b965-27aecef4d2b3 +Domain: mock_websites +Mocks: linear_mock, github_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.3] ENG-15 (memory leak) moved to In Progress + - [0.2] ENG-15 assigned to Sam Patel + - [0.2] GitHub issue opened for the leak + - [0.1] slack_new_msg + - [0.2] Slack names ENG-15 exactly +""" +import re +import sys + +import requests + +MOCK_URLS = { + "linear_mock": "http://28.7.186.212:8176", + "github_mock": "http://28.7.186.212:8156", + "slack_mock": "http://28.7.186.212:8198" +} +SEED = { + "slack_mock:general": [], + "slack_mock:engineering": [ + "e1", + "e2" + ], + "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: linear issue i15 stateId == 'ws_eng_in_progress' +c0_i = next((i for i in (cur('linear_mock').get('issues') or []) if i.get('id') == 'i15'), None) +if c0_i and c0_i.get('stateId') == 'ws_eng_in_progress': + print('PASS: ENG-15 (memory leak) moved to In Progress (0.3)') + total += 0.3 +else: + print('FAIL: ENG-15 (memory leak) moved to In Progress (got ' + str(c0_i.get('stateId') if c0_i else 'missing') + ')') + +# c1: linear issue i15 assigneeId == 'u3' +c1_i = next((i for i in (cur('linear_mock').get('issues') or []) if i.get('id') == 'i15'), None) +if c1_i and c1_i.get('assigneeId') == 'u3': + print('PASS: ENG-15 assigned to Sam Patel (0.2)') + total += 0.2 +else: + print('FAIL: ENG-15 assigned to Sam Patel (got ' + str(c1_i.get('assigneeId') if c1_i else 'missing') + ')') + +# c2: a new github issue about (GitHub issue opened for the leak) +c2_init = {i.get('id') for i in ((STATES['github_mock'].get('initial_state') or {}).get('issues') or [])} +c2_new = [i for i in (cur('github_mock').get('issues') or []) if i.get('id') not in c2_init and any(t in _lc(i.get('title','')) for t in ['memory leak in real-time notifications', 'memory leak'])] +if c2_new: + print('PASS: GitHub issue opened for the leak (0.2)') + total += 0.2 +else: + print('FAIL: GitHub issue opened for the leak') + +# c3: new message by user_1 in #engineering +c3_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c3_seed = set(SEED.get('slack_mock:engineering', [])) +c3_new = [m for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1'] +c3_blob = _lc(' '.join((m.get('content') or '') for m in c3_new)) +if c3_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') + +# c4: slack #engineering contains (Slack names ENG-15 exactly) +c4_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c4_seed = set(SEED.get('slack_mock:engineering', [])) +c4_blob = _lc(' '.join((m.get('content') or '') for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1')) +if all(t in c4_blob for t in ['eng-15']): + print('PASS: Slack names ENG-15 exactly (0.2)') + total += 0.2 +else: + print('FAIL: Slack names ENG-15 exactly') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/ae_forecast_001/_cua_gym_vm_bridge.sh b/legacy/ae_forecast_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/ae_forecast_001/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/ae_forecast_001/initial_setup.py b/legacy/ae_forecast_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a05cb37c01ef79f2f5bc15618afd7efe7ac6bd --- /dev/null +++ b/legacy/ae_forecast_001/initial_setup.py @@ -0,0 +1,553 @@ +# --- 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.186.212"): + 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: Q3 forecast prep across Salesforce, Notion, and Slack. +Task ID: ae_forecast_001 +Domain: mock_websites (multi-mock) +Mocks: salesforce, notion, slack + +Persona: Alex Rivera (user-1 / user_1), AE at Northwind Cloud. Today = 2026-06-24. + +Pre-task state ONLY. MUST NOT contain task-completed elements: + - Notion 'Q3 Forecast' database has exactly 3 rows whose Opportunity titles + are 'Globex - Platform Expansion', 'Initech - Annual Renewal', + 'Soylent - New Logo'. Amount / Stage / Close Date / Next Step are EMPTY + in every one of those rows (the agent fills them). + - Slack channel 'sales' exists but has NO message from today (and no forecast + summary message at all). +Distractor that MUST exist and be left untouched by the golden state: + - Salesforce opp-6 'Globex - SMB Add-on' (Closed Lost) — must NOT be + forecast and must remain unchanged. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Networking --- +# Mock servers are reachable directly on the fixed internal host. + +# --- Mock registry --- +MOCKS = { + 'salesforce': 'http://28.7.186.212:8195', + 'notion': 'http://28.7.186.212:8186', + 'slack': 'http://28.7.186.212:8198', +} + +# --- Shared session id --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid = {sid}') + + +# ---------------------------------------------------------------------------- +# Salesforce state +# user-1 Alex Rivera; 3 accounts + 3 contacts; 4 opportunities +# (opp-1/2/3 OPEN + opp-6 Closed Lost distractor). Read-only in this task. +# ---------------------------------------------------------------------------- +def salesforce_state(): + user_1 = { + "userId": "user-1", "firstName": "Alex", "lastName": "Rivera", + "email": "alex.rivera@northwindcloud.com", "phone": "(555) 240-1188", + "title": "Account Executive", "department": "Sales", "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning", + } + user_2 = { + "userId": "user-2", "firstName": "Sam", "lastName": "Lee", + "email": "sam.lee@northwindcloud.com", "phone": "(555) 240-1190", + "title": "Sales Manager", "department": "Sales", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning", + } + + accounts = [ + {"accountId": "account-1", "name": "Globex Corporation", + "type": "Customer", "industry": "Manufacturing", "revenue": 48000000, + "employees": 1200, "ownerId": "user-1", "billingStreet": "500 Globex Pkwy", + "billingCity": "San Jose", "billingState": "CA", "billingZip": "95110", + "billingCountry": "USA"}, + {"accountId": "account-2", "name": "Initech LLC", "type": "Customer", + "industry": "Software", "revenue": 22000000, "employees": 320, + "ownerId": "user-1", "billingStreet": "78 Office Park Dr", + "billingCity": "Austin", "billingState": "TX", "billingZip": "73301", + "billingCountry": "USA"}, + {"accountId": "account-3", "name": "Soylent Industries", + "type": "Prospect", "industry": "Food & Beverage", "revenue": 9000000, + "employees": 140, "ownerId": "user-1", "billingStreet": "12 Greenway Blvd", + "billingCity": "Portland", "billingState": "OR", "billingZip": "97201", + "billingCountry": "USA"}, + ] + + contacts = [ + {"contactId": "contact-1", "accountId": "account-1", + "firstName": "Maria", "lastName": "Gomez", "title": "VP Operations", + "department": "Operations", "email": "maria.gomez@globex.com", + "phone": "(555) 401-3321", "ownerId": "user-1"}, + {"contactId": "contact-2", "accountId": "account-2", + "firstName": "Daniel", "lastName": "Park", "title": "CTO", + "department": "Engineering", "email": "daniel.park@initech.com", + "phone": "(555) 330-2201", "ownerId": "user-1"}, + {"contactId": "contact-3", "accountId": "account-3", + "firstName": "Priya", "lastName": "Nair", "title": "Head of Procurement", + "department": "Procurement", "email": "priya.nair@soylent.com", + "phone": "(555) 661-7788", "ownerId": "user-1"}, + ] + + opportunities = [ + {"opportunityId": "opp-1", "name": "Globex - Platform Expansion", + "accountId": "account-1", "contactId": "contact-1", "amount": 120000, + "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 75, + "ownerId": "user-1"}, + {"opportunityId": "opp-2", "name": "Initech - Annual Renewal", + "accountId": "account-2", "contactId": "contact-2", "amount": 60000, + "closeDate": "2026-06-30", "stage": "Proposal", "probability": 60, + "ownerId": "user-1"}, + {"opportunityId": "opp-3", "name": "Soylent - New Logo", + "accountId": "account-3", "contactId": "contact-3", "amount": 45000, + "closeDate": "2026-08-20", "stage": "Value Proposition", + "probability": 40, "ownerId": "user-1"}, + # DISTRACTOR — closed, must NOT be forecast and must remain unchanged. + {"opportunityId": "opp-6", "name": "Globex - SMB Add-on", + "accountId": "account-1", "contactId": "contact-1", "amount": 9000, + "closeDate": "2026-04-01", "stage": "Closed Lost", "probability": 0, + "ownerId": "user-1"}, + ] + + return { + "user": user_1, + "users": [user_1, user_2], + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# ---------------------------------------------------------------------------- +# Notion state +# 'Q3 Forecast' database (table view). Three rows with Opportunity titles +# filled; Amount / Stage / Close Date / Next Step all EMPTY. +# ---------------------------------------------------------------------------- +def notion_state(): + db_id = "db-q3-forecast" + # NOTE: notion_mock stores database-row property values as a FLAT map + # ({propId: primitiveValue}) and select options as a string array. The + # built-in "Name" column renders page.title, so there is no "title"-typed + # property (that type is unsupported and crashes DatabaseView -> blank page). + properties = [ + {"id": "prop_amt", "name": "Amount", "type": "number"}, + {"id": "prop_stage", "name": "Stage", "type": "select", + "options": ["Prospecting", "Qualification", "Needs Analysis", + "Value Proposition", "Proposal", "Negotiation", + "Closed Won", "Closed Lost"]}, + {"id": "prop_date", "name": "Close Date", "type": "date"}, + {"id": "prop_next", "name": "Next Step", "type": "text"}, + ] + + def make_empty_row(page_id, opp_title): + # Title filled (via page.title / Name column); all other cells EMPTY. + return { + "id": page_id, + "title": opp_title, + "icon": "", "cover": None, "parentId": db_id, + "blockIds": [], "favorite": False, + "createdDate": "2026-06-20T09:00:00.000Z", + "lastEditedDate": "2026-06-20T09:00:00.000Z", + "properties": { + "prop_amt": "", + "prop_stage": "", + "prop_date": "", + "prop_next": "", + }, + } + + row_globex = make_empty_row("row-globex", "Globex - Platform Expansion") + row_initech = make_empty_row("row-initech", "Initech - Annual Renewal") + row_soylent = make_empty_row("row-soylent", "Soylent - New Logo") + + db_page = { + "id": db_id, + "title": "Q3 Forecast", + "icon": "📊", "cover": None, "parentId": None, + "type": "database", "viewType": "table", + "properties": properties, + "views": [{ + "id": "view-q3", "name": "Table", "type": "table", + "filters": [], "sorts": [], "groupBy": None, + "visibleProperties": ["prop_amt", "prop_stage", + "prop_date", "prop_next"], + }], + "items": ["row-globex", "row-initech", "row-soylent"], + "blockIds": [], "favorite": False, + "createdDate": "2026-06-20T09:00:00.000Z", + } + + return { + "user": {"id": "user-1", "name": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com", "avatar": ""}, + "workspace": {"id": "ws-1", "name": "Northwind Sales", "icon": "🏢", + "members": ["user-1"]}, + "pages": { + db_id: db_page, + "row-globex": row_globex, + "row-initech": row_initech, + "row-soylent": row_soylent, + }, + "blocks": {}, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, + "fontSize": "default"}, + "notifications": [], + "pageOrder": [db_id], + } + + +# ---------------------------------------------------------------------------- +# Slack state +# workspace 'Northwind Cloud'; currentUser user_1 Alex Rivera. +# Public channel 'sales' (alongside defaults). No forecast message yet. +# ---------------------------------------------------------------------------- +def slack_state(): + user_1 = { + "userId": "user_1", "fullName": "Alex Rivera", "displayName": "Alex", + "email": "alex.rivera@northwindcloud.com", + "avatar": "https://picsum.photos/200/200?random=1", "title": "Account Executive", + "status": "online", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/Los_Angeles", + } + user_2 = { + "userId": "user_2", "fullName": "Sam Lee", "displayName": "Sam", + "email": "sam.lee@northwindcloud.com", + "avatar": "https://picsum.photos/200/200?random=2", "title": "Sales Manager", + "status": "online", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/Los_Angeles", + } + user_3 = { + "userId": "user_3", "fullName": "Nina Torres", "displayName": "Nina", + "email": "nina.torres@northwindcloud.com", + "avatar": "https://picsum.photos/200/200?random=3", "title": "Sales Engineer", + "status": "away", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/New_York", + } + users = [user_1, user_2, user_3] + all_members = ["user_1", "user_2", "user_3"] + + def channel(cid, name, desc, topic): + return { + "channelId": cid, "name": name, "description": desc, "topic": topic, + "isPrivate": False, "isStarred": False, "members": all_members, + "createdBy": "user_2", "createdAt": "2026-01-05T09:00:00Z", + "pinnedMessages": [], "unreadCount": 0, + } + + channels = [ + channel("general", "general", "Company-wide announcements", "Welcome to Northwind Cloud"), + channel("random", "random", "Non-work chatter", ""), + channel("engineering", "engineering", "Engineering team", ""), + channel("design", "design", "Design team", ""), + channel("marketing", "marketing", "Marketing team", ""), + channel("project-alpha", "project-alpha", "Project Alpha working group", ""), + channel("sales", "sales", "Sales team — pipeline, forecasts, wins", "Q3 forecast prep"), + ] + + # Channels have some realistic prior chatter, but NO forecast summary today. + messages = { + "general": [ + {"messageId": "msg_gen_1", "senderId": "user_2", + "content": "Morning team — reminder we have the Q3 sales sync this afternoon.", + "timestamp": "2026-06-24T15:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + "random": [], + "engineering": [], + "design": [], + "marketing": [], + "project-alpha": [], + "sales": [ + {"messageId": "msg_sales_1", "senderId": "user_2", + "content": "Let's get the Q3 forecast numbers locked before the sync.", + "timestamp": "2026-06-22T16:30:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + } + + return { + "currentUser": user_1, + "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 all states +# ---------------------------------------------------------------------------- +STATE_BUILDERS = { + 'salesforce': salesforce_state, + 'notion': notion_state, + 'slack': slack_state, +} + +for name, build in STATE_BUILDERS.items(): + url = MOCKS[name] + state = build() + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, \ + f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f' injected {name}: initial_state OK') + +print(f'All 3 mocks injected with sid={sid}') + + +# ---------------------------------------------------------------------------- +# GUI-ready: launch Chrome on Salesforce (primary app — where the source data is) +# ---------------------------------------------------------------------------- +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["salesforce"]}/?sid={sid}"', + delay_sec=2.0, +) +_open_remaining_mock_tabs(MOCKS["salesforce"]) +wait_mocks_loaded() +print(f'GUI_READY: launched browser tabs with sid={sid}') diff --git a/legacy/ae_forecast_001/reward.py b/legacy/ae_forecast_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..cce7ed28e90782c2198f2a0894332fc06fdfe50e --- /dev/null +++ b/legacy/ae_forecast_001/reward.py @@ -0,0 +1,524 @@ +# --- 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.186.212"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +""" +Reward Script: Q3 forecast — copy 3 open Salesforce opps into Notion 'Q3 Forecast' + table and post a Slack #sales summary with the combined total. +Task ID: ae_forecast_001 +Domain: mock_websites (multi-mock: notion_mock, slack_mock; salesforce read-only) + +Scoring (all components verify task-introduced changes; each FAILS on initial_env): + - Component 1: Notion 'Globex - Platform Expansion' row filled (0.20) + amount, stage, closeDate match the Salesforce source opportunity + - Component 2: Notion 'Initech - Annual Renewal' row filled (0.20) + amount, stage, closeDate match the Salesforce source opportunity + - Component 3: Notion 'Soylent - New Logo' row filled (0.20) + amount, stage, closeDate match the Salesforce source opportunity + - Component 4: exactly 3 forecast rows; Closed Lost distractor (0.15) + 'Globex - SMB Add-on' NOT added to the table + - Component 5: Slack #sales message by current user with combined (0.25) + runtime Salesforce total AND naming Globex, Initech, Soylent + Total = 1.0 + +NOTE: Salesforce opportunity data is a read-only precondition (must stay +unchanged); it is NOT scored. All scored items are empty/absent in initial_env. +""" +import datetime as dt +import json +import os +import re +import sys + +import requests + + +def _comp(idx, name, weight, passed, score, detail=""): + """Emit a structured COMPONENT line for per-module scoring visibility. + + Parsed by the cua_gym_reward metric to build a + _cua_reward_components.json sidecar alongside the captured stdout, so the + evaluator can report which modules were done correctly instead of only a + single aggregate float. Output format: ``COMPONENT: ``. + """ + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + })) + + +# --- 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) + +SALESFORCE_URL = 'http://28.7.186.212:8195' +NOTION_URL = 'http://28.7.186.212:8186' +SLACK_URL = 'http://28.7.186.212:8198' + +TARGET_OPPORTUNITIES = [ + 'Globex - Platform Expansion', + 'Initech - Annual Renewal', + 'Soylent - New Logo', +] + + +def fetch_state(base_url): + """Fetch /go for a mock; returns (initial_state, current_state) dicts.""" + data = requests.get(f'{base_url}/go?sid={sid}', timeout=15).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + + +# ---------- helpers for robust property extraction ---------- +def normalize_text(value): + """Case/punctuation/spacing-insensitive text normalization.""" + text = '' if value is None else str(value) + text = text.replace('&', ' and ') + text = re.sub(r'[\u2010-\u2015]', '-', text) + text = re.sub(r'[^a-zA-Z0-9]+', ' ', text.lower()) + return re.sub(r'\s+', ' ', text).strip() + + +def normalized_contains(text, needle): + norm_text = normalize_text(text) + norm_needle = normalize_text(needle) + return bool(norm_needle and norm_needle in norm_text) + + +def get_prop(props, *keys): + """Fetch a Notion property by stable id or display name.""" + if not isinstance(props, dict): + return None + for key in keys: + if key in props: + return props[key] + wanted = {normalize_text(key) for key in keys} + for key, value in props.items(): + if normalize_text(key) in wanted: + return value + return None + + +def get_number(prop): + """prop expected shape: {'number': }; tolerate raw value too.""" + if isinstance(prop, dict): + return prop.get('number') + return prop + + +def get_select(prop): + """prop expected shape: {'select': 'Stage'} or {'select': {'name': ...}}.""" + if isinstance(prop, dict): + val = prop.get('select', prop) + else: + val = prop + if isinstance(val, dict): + return val.get('name') + return val + + +def get_date_start(prop): + """prop expected shape: {'date': {'start': 'YYYY-MM-DD'}} or {'date': 'YYYY-MM-DD'}.""" + if isinstance(prop, dict): + val = prop.get('date', prop) + else: + val = prop + if isinstance(val, dict): + return val.get('start') + return val + + +def parse_amount(value): + """Parse common money/number formats such as $225,000, 225k, or 225000.""" + if value is None: + return None + if isinstance(value, (int, float)): + return float(value) + text = str(value).strip().lower() + if not text: + return None + mult = 1 + if re.search(r'\b(k|thousand)\b', text): + mult = 1000 + text = re.sub(r'[$,\s]', '', text) + text = re.sub(r'(usd|dollars?|k|thousand)', '', text) + match = re.search(r'-?\d+(?:\.\d+)?', text) + if not match: + return None + return float(match.group(0)) * mult + + +def amounts_equal(actual, expected): + actual_num = parse_amount(actual) + expected_num = parse_amount(expected) + return actual_num is not None and expected_num is not None and abs(actual_num - expected_num) < 0.01 + + +def normalize_stage(value): + norm = normalize_text(value) + aliases = { + 'value prop': 'value proposition', + 'value proposition': 'value proposition', + 'proposal quote': 'proposal', + 'proposal': 'proposal', + 'negotiating': 'negotiation', + 'negotiation review': 'negotiation', + 'negotiation': 'negotiation', + } + return aliases.get(norm, norm) + + +def parse_date(value): + """Return a date object from common UI/API date strings.""" + if value is None: + return None + if isinstance(value, dt.datetime): + return value.date() + if isinstance(value, dt.date): + return value + if isinstance(value, dict): + for key in ('start', 'date', 'value'): + parsed = parse_date(value.get(key)) + if parsed: + return parsed + return None + + text = str(value).strip() + if not text: + return None + text = re.sub(r'(\d)(st|nd|rd|th)\b', r'\1', text, flags=re.I) + iso_text = text.replace('Z', '+00:00') + try: + return dt.datetime.fromisoformat(iso_text).date() + except ValueError: + pass + if 'T' in text: + text = text.split('T', 1)[0] + for fmt in ( + '%Y-%m-%d', + '%Y/%m/%d', + '%m/%d/%Y', + '%m/%d/%y', + '%b %d, %Y', + '%B %d, %Y', + '%d %b %Y', + '%d %B %Y', + ): + try: + return dt.datetime.strptime(text, fmt).date() + except ValueError: + continue + return None + + +def dates_equal(actual, expected): + actual_date = parse_date(actual) + expected_date = parse_date(expected) + return ( + actual_date is not None + and expected_date is not None + and (actual_date.year, actual_date.month, actual_date.day) + == (expected_date.year, expected_date.month, expected_date.day) + ) + + +def row_matches(props, expected): + """Return True only if amount, stage AND close date all match the source opp.""" + exp_amount = expected.get('amount') + exp_stage = expected.get('stage') + exp_date = expected.get('closeDate') + amt = get_number(get_prop(props, 'prop_amt', 'Amount')) + stage = get_select(get_prop(props, 'prop_stage', 'Stage')) + date = get_date_start(get_prop(props, 'prop_date', 'Close Date')) + amt_ok = amounts_equal(amt, exp_amount) + stage_ok = normalize_stage(stage) == normalize_stage(exp_stage) + date_ok = dates_equal(date, exp_date) + print(f' amount={amt} (exp {exp_amount}, {"ok" if amt_ok else "BAD"}), ' + f'stage={stage!r} (exp {exp_stage!r}, {"ok" if stage_ok else "BAD"}), ' + f'date={date!r} (exp {exp_date!r}, {"ok" if date_ok else "BAD"})') + return amt_ok and stage_ok and date_ok + + +def find_row(pages, title): + """Find a database row page whose title matches despite case/punctuation.""" + for pid, page in pages.items(): + if not isinstance(page, dict): + continue + if page.get('parentId') != 'db-q3-forecast': + continue + props = page.get('properties', {}) + t = page.get('title') or get_prop(props, 'prop_opp', 'Opportunity') + if isinstance(t, dict): + t = t.get('title') or t.get('name') or t.get('plain_text') + if t and normalize_text(t) == normalize_text(title): + return page + return None + + +def is_open_stage(stage): + return normalize_stage(stage) not in {'closed won', 'closed lost'} + + +def get_expected_opportunities(salesforce_state): + opportunities = salesforce_state.get('opportunities', []) + accounts = { + account.get('accountId'): account.get('name') + for account in salesforce_state.get('accounts', []) + if isinstance(account, dict) + } + expected = {} + for target_name in TARGET_OPPORTUNITIES: + target_norm = normalize_text(target_name) + for opp in opportunities: + if not isinstance(opp, dict): + continue + if normalize_text(opp.get('name')) != target_norm: + continue + if not is_open_stage(opp.get('stage')): + continue + opp_copy = dict(opp) + opp_copy['accountName'] = accounts.get(opp.get('accountId'), '') + expected[target_name] = opp_copy + break + return expected + + +def channel_id_for(slack_state, name): + for channel in slack_state.get('channels', []) or []: + if isinstance(channel, dict) and normalize_text(channel.get('name')) == normalize_text(name): + return channel.get('channelId') or channel.get('name') + return name + + +def content_has_amount(content, expected_amount): + expected_num = parse_amount(expected_amount) + if expected_num is None: + return False + compact = re.sub(r'[,$\s]', '', str(content).lower()) + if str(int(expected_num)) in compact: + return True + for match in re.finditer( + r'\$?\s*(-?\d+(?:[,\s]\d{3})*(?:\.\d+)?|-?\d+(?:\.\d+)?)\s*(k|thousand|usd|dollars?)?', + str(content), + flags=re.I, + ): + num = parse_amount(''.join(part or '' for part in match.groups())) + if num is not None and abs(num - expected_num) < 0.01: + return True + return False + + +def account_aliases(opp): + aliases = [] + account_name = opp.get('accountName') + if account_name: + aliases.append(account_name) + aliases.append(re.sub(r'\b(corporation|corp|llc|inc|industries|ltd)\b', '', account_name, flags=re.I)) + opp_name = opp.get('name') + if opp_name: + aliases.append(str(opp_name).split('-', 1)[0]) + return [alias for alias in aliases if normalize_text(alias)] + + +def content_mentions_all_accounts(content, expected_opps): + for opp in expected_opps.values(): + aliases = account_aliases(opp) + if not any(normalized_contains(content, alias) for alias in aliases): + return False + return True + + +def verify_task(): + total_score = 0.0 + + # --- Fetch Salesforce + Notion + Slack state --- + try: + salesforce_init, _ = fetch_state(SALESFORCE_URL) + expected_opps = get_expected_opportunities(salesforce_init) + missing = [name for name in TARGET_OPPORTUNITIES if name not in expected_opps] + if missing: + raise ValueError(f'missing open source opportunities: {missing}') + except Exception as e: + print(f'CRITICAL: cannot build expected values from Salesforce state: {e}') + print('REWARD: 0.0') + return 0.0 + try: + _, notion_cur = fetch_state(NOTION_URL) + except Exception as e: + print(f'CRITICAL: cannot fetch Notion state: {e}') + print('REWARD: 0.0') + return 0.0 + try: + slack_init, slack_cur = fetch_state(SLACK_URL) + except Exception as e: + print(f'CRITICAL: cannot fetch Slack state: {e}') + print('REWARD: 0.0') + return 0.0 + + notion_pages = notion_cur.get('pages', {}) if isinstance(notion_cur, dict) else {} + + # Component 1: Globex row filled (0.20) + try: + row = find_row(notion_pages, 'Globex - Platform Expansion') + if row is None: + print('FAIL: Component 1 — Globex row not found') + _comp(1, 'Globex row filled', 0.20, False, 0.0, 'row not found') + else: + print('CHECK Component 1 — Globex - Platform Expansion:') + if row_matches(row.get('properties', {}), + expected_opps['Globex - Platform Expansion']): + print('PASS: Component 1 — Globex row fully correct (0.20 pts)') + total_score += 0.20 + _comp(1, 'Globex row filled', 0.20, True, 0.20, + 'amount/stage/date ok') + else: + print('FAIL: Component 1 — Globex row values incorrect') + _comp(1, 'Globex row filled', 0.20, False, 0.0, + 'values incorrect') + except Exception as e: + print(f'ERROR: Component 1 — {e}') + _comp(1, 'Globex row filled', 0.20, False, 0.0, f'error: {e}') + + # Component 2: Initech row filled (0.20) + try: + row = find_row(notion_pages, 'Initech - Annual Renewal') + if row is None: + print('FAIL: Component 2 — Initech row not found') + _comp(2, 'Initech row filled', 0.20, False, 0.0, 'row not found') + else: + print('CHECK Component 2 — Initech - Annual Renewal:') + if row_matches(row.get('properties', {}), + expected_opps['Initech - Annual Renewal']): + print('PASS: Component 2 — Initech row fully correct (0.20 pts)') + total_score += 0.20 + _comp(2, 'Initech row filled', 0.20, True, 0.20, + 'amount/stage/date ok') + else: + print('FAIL: Component 2 — Initech row values incorrect') + _comp(2, 'Initech row filled', 0.20, False, 0.0, + 'values incorrect') + except Exception as e: + print(f'ERROR: Component 2 — {e}') + _comp(2, 'Initech row filled', 0.20, False, 0.0, f'error: {e}') + + # Component 3: Soylent row filled (0.20) + try: + row = find_row(notion_pages, 'Soylent - New Logo') + if row is None: + print('FAIL: Component 3 — Soylent row not found') + _comp(3, 'Soylent row filled', 0.20, False, 0.0, 'row not found') + else: + print('CHECK Component 3 — Soylent - New Logo:') + if row_matches(row.get('properties', {}), + expected_opps['Soylent - New Logo']): + print('PASS: Component 3 — Soylent row fully correct (0.20 pts)') + total_score += 0.20 + _comp(3, 'Soylent row filled', 0.20, True, 0.20, + 'amount/stage/date ok') + else: + print('FAIL: Component 3 — Soylent row values incorrect') + _comp(3, 'Soylent row filled', 0.20, False, 0.0, + 'values incorrect') + except Exception as e: + print(f'ERROR: Component 3 — {e}') + _comp(3, 'Soylent row filled', 0.20, False, 0.0, f'error: {e}') + + # Component 4: exactly 3 forecast rows; Closed Lost distractor NOT added (0.15) + # This anchors to the task change: rows are only "complete" (filled) in golden, + # and we additionally guard that the agent did not add a 4th row for the + # Closed Lost 'Globex - SMB Add-on' distractor. + try: + db = notion_pages.get('db-q3-forecast', {}) + items = db.get('items', []) if isinstance(db, dict) else [] + # rows actually parented to the forecast DB + child_rows = [p for p in notion_pages.values() + if isinstance(p, dict) and p.get('parentId') == 'db-q3-forecast'] + titles = [normalize_text(p.get('title', '')) for p in child_rows] + distractor_present = any(normalized_contains(t, 'smb add on') for t in titles) + # Require: at least one row already correctly filled (a real task change), + # exactly 3 rows, and no distractor row. + any_filled = total_score > 0 + comp4_ok = (any_filled and len(items) == 3 + and len(child_rows) == 3 and not distractor_present) + if comp4_ok: + total_score += 0.15 + print('PASS: Component 4 — exactly 3 rows, no Closed Lost distractor ' + '(0.15 pts)') + _comp(4, 'exactly 3 rows, no distractor', 0.15, True, 0.15, + 'items=3, child_rows=3, no distractor') + else: + print(f'FAIL: Component 4 — items={len(items)}, child_rows=' + f'{len(child_rows)}, distractor_present={distractor_present}, ' + f'any_filled={any_filled}') + _comp(4, 'exactly 3 rows, no distractor', 0.15, False, 0.0, + f'items={len(items)}, child_rows={len(child_rows)}, ' + f'distractor={distractor_present}, any_filled={any_filled}') + except Exception as e: + print(f'ERROR: Component 4 — {e}') + _comp(4, 'exactly 3 rows, no distractor', 0.15, False, 0.0, + f'error: {e}') + + # Component 5: Slack #sales message with runtime total + 3 accounts (0.25) + try: + sales_channel_id = channel_id_for(slack_cur, 'sales') + init_messages = slack_init.get('messages', {}) or {} + cur_messages = slack_cur.get('messages', {}) or {} + init_msgs = init_messages.get(sales_channel_id, init_messages.get('sales', [])) + cur_msgs = cur_messages.get(sales_channel_id, cur_messages.get('sales', [])) + 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 + or not m.get('messageId')] + expected_sender = (slack_cur.get('currentUser', {}) or {}).get('userId', 'user_1') + total_amount = sum(parse_amount(opp.get('amount')) or 0 for opp in expected_opps.values()) + match = None + for m in new_msgs: + content = str(m.get('content', '')) + sender = m.get('senderId') + has_total = content_has_amount(content, total_amount) + has_accounts = content_mentions_all_accounts(content, expected_opps) + mentions_distractor = normalized_contains(content, 'Globex SMB Add-on') + if (sender == expected_sender and has_total and has_accounts + and not mentions_distractor): + match = m + break + if match: + print(f'PASS: Component 5 — Slack #sales update by current user with ' + f'${total_amount:,.0f} and all three accounts (0.25 pts)') + total_score += 0.25 + _comp(5, 'Slack #sales message with total + 3 accounts', 0.25, + True, 0.25, 'sender + total + three accounts') + else: + print(f'FAIL: Component 5 — no qualifying new #sales message ' + f'(new msgs: {len(new_msgs)}; need sender + total ' + f'{total_amount:g} + three accounts)') + _comp(5, 'Slack #sales message with total + 3 accounts', 0.25, + False, 0.0, f'new msgs={len(new_msgs)}, no qualifying message') + except Exception as e: + print(f'ERROR: Component 5 — {e}') + _comp(5, 'Slack #sales message with total + 3 accounts', 0.25, + False, 0.0, f'error: {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/legacy/ae_forecast_001/reward_label.json b/legacy/ae_forecast_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..e70ecf705bda45ea43d667a04f90587f6355c112 --- /dev/null +++ b/legacy/ae_forecast_001/reward_label.json @@ -0,0 +1,68 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ae_forecast_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 18:50:07", + "label": { + "task_id": "ae_forecast_001", + "domain": "mock_websites", + "summary": "验证将3个开放的Salesforce机会复制到Notion的Q3 Forecast表格,并在Slack #sales频道发布包含实时合计金额与三个客户名称的摘要消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "salesforce_mock (http://28.7.186.212:8195)", + "notion_mock (http://28.7.186.212:8186)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.2, + "description": "Notion中'Globex - Platform Expansion'行已正确填充", + "check_logic": "调用find_row在notion_pages中查找parentId为'db-q3-forecast'且标题归一化后匹配'Globex - Platform Expansion'的页面;若找到,使用row_matches对比其properties中的Amount(prop_amt/Amount)、Stage(prop_stage/Stage)、Close Date(prop_date/Close Date)是否与Salesforce源机会一致(amounts_equal、normalize_stage、dates_equal)", + "pass_condition": "存在匹配行且amount、stage、closeDate三项均与Salesforce源数据匹配" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "Notion中'Initech - Annual Renewal'行已正确填充", + "check_logic": "与Component 1相同,查找标题匹配'Initech - Annual Renewal'的行并校验amount、stage、closeDate", + "pass_condition": "存在匹配行且三项属性均与Salesforce源数据匹配" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "Notion中'Soylent - New Logo'行已正确填充", + "check_logic": "与Component 1相同,查找标题匹配'Soylent - New Logo'的行并校验amount、stage、closeDate", + "pass_condition": "存在匹配行且三项属性均与Salesforce源数据匹配" + }, + { + "name": "Component 4", + "weight": 0.15, + "description": "Notion Q3 Forecast表格恰好有3行且未添加Closed Lost干扰项", + "check_logic": "检查notion_pages中'db-q3-forecast'的items长度为3;统计parentId为'db-q3-forecast'的child_rows数量为3;检查所有子行标题归一化后不含'smb add on';且要求前面至少有一个组件已通过(any_filled = total_score > 0)", + "pass_condition": "items==3、child_rows==3、无distractor且any_filled为真" + }, + { + "name": "Component 5", + "weight": 0.25, + "description": "Slack #sales频道由当前用户发送包含合计金额与三个账户名称的新消息", + "check_logic": "获取#sales频道初始与当前消息,筛选出messageId不在初始集合中的new_msgs;计算三个预期机会的amount总和total_amount;遍历新消息,检查senderId等于当前用户、content_has_amount匹配total_amount、content_mentions_all_accounts提及Globex/Initech/Soylent三个账户、且不包含'Globex SMB Add-on'干扰项", + "pass_condition": "存在一条由当前用户发送的新消息,内容包含实时总金额、提及全部三个账户且不提及干扰项" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留4位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,返回 0.0", + "从 Salesforce 拉取状态失败或缺少目标开放机会:打印 CRITICAL,返回 0.0", + "从 Notion 拉取状态失败:打印 CRITICAL,返回 0.0", + "从 Slack 拉取状态失败:打印 CRITICAL,返回 0.0", + "各组件单独失败时仅该组件得 0 分,不会导致整体提前退出(Critical 路径除外)" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话ID,失败则直接返回0.0。随后并行(按代码顺序)从Salesforce、Notion、Slack三个mock服务拉取状态:Salesforce取初始状态以构建3个目标开放机会的预期值(amount/stage/closeDate),若缺失则直接返回0.0;Notion取当前状态用于检查表格行;Slack取初始和当前状态用于检测新消息。接着逐项评分:组件1-3分别在Notion的Q3 Forecast数据库(parentId='db-q3-forecast')中查找指定标题行,使用容错逻辑(金额解析、阶段别名归一化、多格式日期解析)对比Amount、Stage、Close Date是否与Salesforce源数据一致,每项正确加0.20分。组件4检查该数据库的items数量和实际子行数量均恰好为3,且不存在标题含'smb add on'的Closed Lost干扰项,同时要求前面至少有一行已正确填充(any_filled),满足加0.15分。组件5在Slack #sales频道中筛选当前用户发送的新消息,验证消息内容包含三个机会的实时计算总金额、提及全部三个账户名称(Globex、Initech、Soylent),且不包含干扰项'Globex SMB Add-on',满足加0.25分。最终汇总得分,经min(score, 1.0)钳制并四舍五入到4位小数后返回。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: ae_forecast_001\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock: notion_mock, slack_mock; salesforce read-only)\"\n3. **summary**: 一句话概括:验证将3个开放的Salesforce机会复制到Notion的Q3 Forecast表格,并在Slack #sales频道发布包含合计金额和三个客户名称的摘要消息。\n4. **is_placeholder**: false,因为脚本有详细的验证逻辑,不是占位脚本。\n5. **data_sources**: \n - /tmp/task_web_sid (读取sid)\n - salesforce_mock (通过 http://28.7.186.212:8195)\n - notion_mock (通过 http://28.7.186.212:8186)\n - slack_mock (通过 http://28.7.186.212:8198)\n\n6. **scoring_components**:\n - Component 1: Notion 'Globex - Platform Expansion' row filled (0.20)\n - Component 2: Notion 'Initech - Annual Renewal' row filled (0.20)\n - Component 3: Notion 'Soylent - New Logo' row filled (0.20)\n - Component 4: exactly 3 forecast rows; Closed Lost distractor NOT added (0.15)\n - Component 5: Slack #sales message by current user with combined runtime Salesforce total AND naming Globex, Initech, Soylent (0.25)\n\n每个组件的详细逻辑:\n- Component 1: 查找 Notion 中 parentId 为 'db-q3-forecast' 且标题匹配 'Globex - Platform Expansion' 的行,检查 amount、stage、closeDate 是否与 Salesforce 源机会匹配。\n- Component 2: 同上,检查 'Initech - Annual Renewal'。\n- Component 3: 同上,检查 'Soylent - New Logo'。\n- Component 4: 检查 notion_pages 中 db-q3-forecast 的 items 数量为 3,child_rows(parentId 为 db-q3-forecast 的页面)数量为 3,且不存在标题包含 'smb add on' 的 distractor 行。同时要求至少有一个前面的组件已填充(any_filled = total_score > 0)。\n- Component 5: 检查 Slack #sales 频道中由当前用户发送的新消息,消息内容需包含三个机会的总金额(运行时计算),并提及所有三个账户(Globex, Initech, Soylent),且不能提及 distractor 'Globex SMB Add-on'。\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到4位小数。\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\n - 从 Salesforce 获取状态失败或缺少目标机会:打印 CRITICAL 并返回 0.0\n - 从 Notion 获取状态失败:打印 CRITICAL 并返回 0.0\n - 从 Slack 获取状态失败:打印 CRITICAL 并返回 0.0\n - 各组件单独失败时只扣该组件分数,不会导致整体 0.0(除非前面 critical 退出)\n\n10. **scoring_logic_explanation**: 详细中文解释,按执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。\n - 然后依次从三个 mock 服务获取状态:Salesforce(只读,获取初始状态以确定预期值)、Notion(获取当前状态)、Slack(获取初始和当前状态以检测新消息)。\n - 如果无法从 Salesforce 构建预期机会列表(缺少3个目标开放机会),直接返回 0.0。\n - 组件1-3:在 Notion 的 Q3 Forecast 数据库(parentId='db-q3-forecast')中分别查找三个指定标题的行,对比 Amount、Stage、Close Date 是否与 Salesforce 源数据一致(使用金额解析、阶段别名归一化、日期解析等容错逻辑)。一致则加 0.20 分。\n - 组件4:检查 Notion 中该数据库的 items 数量和实际子行数量都恰好为 3,且不存在标题包含 \"smb add on\" 的干扰项(Closed Lost distractor),同时要求前面至少有一个行已正确填充(any_filled)。满足则加 0.15 分。\n - 组件5:在 Slack #sales 频道中找出当前用户发送的新消息,检查消息内容是否包含三个机会的实时计算总金额,是否提及全部三个账户名称(Globex、Initech、Soylent),且不包含干扰项 \"Globex SMB Add-on\"。满足则加 0.25 分。\n - 最终汇总各组件得分,用 min(score, 1.0) 钳制上限,四舍五入到4位小数后返回。\n\n11. **confidence**: 1.0(代码逻辑清晰完整)\n\n让我再仔细检查一下 Component 4 的 any_filled 条件。代码中是 `any_filled = total_score > 0`,这里的 total_score 是前面三个组件累加后的值。所以 Component 4 要求至少前面有一个行是正确的。\n\nComponent 5 的 total_amount 是运行时计算的:`sum(parse_amount(opp.get('amount')) or 0 for opp in expected_opps.values())`\n\nSlack 消息检测:比较 init_msgs 和 cur_msgs,找出 messageId 不在 init_ids 中的新消息。\n\n所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\nJSON 格式要求:不要 Markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我构建 JSON。 {\"task_id\":\"ae_forecast_001\",\"domain\":\"mock_websites\",\"summary\":\"验证将3个开放的Salesforce机会复制到Notion的Q3 Forecast表格,并在Slack #sales频道发布包含实时合计金额与三个客户名称的摘要消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"salesforce_mock (http://28.7.186.212:8195)\",\"notion_mock (http://28.7.186.212:8186)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.2,\"description\":\"Notion中'Globex - Platform Expansion'行已正确填充\",\"check_logic\":\"调用find_row在notion_pages中查找parentId为'db-q3-forecast'且标题归一化后匹配'Globex - Platform Expansion'的页面;若找到,使用row_matches对比其properties中的Amount(prop_amt/Amount)、Stage(prop_stage/Stage)、Close Date(prop_date/Close Date)是否与Salesforce源机会一致(amounts_equal、normalize_stage、dates_equal)\",\"pass_condition\":\"存在匹配行且amount、stage、closeDate三项均与Salesforce源数据匹配\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"Notion中'Initech - Annual Renewal'行已正确填充\",\"check_logic\":\"与Component 1相同,查找标题匹配'Initech - Annual Renewal'的行并校验amount、stage、closeDate\",\"pass_condition\":\"存在匹配行且三项属性均与Salesforce源数据匹配\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"Notion中'Soylent - New Logo'行已正确填充\",\"check_logic\":\"与Component 1相同,查找标题匹配'Soylent - New Logo'的行并校验amount、stage、closeDate\",\"pass_condition\":\"存在匹配行且三项属性均与Salesforce源数据匹配\"},{\"name\":\"Component 4\",\"weight\":0.15,\"description\":\"Notion Q3 Forecast表格恰好有3行且未添加Closed Lost干扰项\",\"check_logic\":\"检查notion_pages中'db-q3-forecast'的items长度为3;统计parentId为'db-q3-forecast'的child_rows数量为3;检查所有子行标题归一化后不含'smb add on';且要求前面至少有一个组件已通过(any_filled = total_score > 0)\",\"pass_condition\":\"items==3、child_rows==3、无distractor且any_filled为真\"},{\"name\":\"Component 5\",\"weight\":0.25,\"description\":\"Slack #sales频道由当前用户发送包含合计金额与三个账户名称的新消息\",\"check_logic\":\"获取#sales频道初始与当前消息,筛选出messageId不在初始集合中的new_msgs;计算三个预期机会的amount总和total_amount;遍历新消息,检查senderId等于当前用户、content_has_amount匹配total_amount、content_mentions_all_accounts提及Globex/Initech/Soylent三个账户、且不包含'Globex SMB Add-on'干扰项\",\"pass_condition\":\"存在一条由当前用户发送的新消息,内容包含实时总金额、提及全部三个账户且不提及干扰项\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留4位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,返回 0.0\",\"从 Salesforce 拉取状态失败或缺少目标开放机会:打印 CRITICAL,返回 0.0\",\"从 Notion 拉取状态失败:打印 CRITICAL,返回 0.0\",\"从 Slack 拉取状态失败:打印 CRITICAL,返回 0.0\",\"各组件单独失败时仅该组件得 0 分,不会导致整体提前退出(Critical 路径除外)\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话ID,失败则直接返回0.0。随后并行(按代码顺序)从Salesforce、Notion、Slack三个mock服务拉取状态:Salesforce取初始状态以构建3个目标开放机会的预期值(amount/stage/closeDate),若缺失则直接返回0.0;Notion取当前状态用于检查表格行;Slack取初始和当前状态用于检测新消息。接着逐项评分:组件1-3分别在Notion的Q3 Forecast数据库(parentId='db-q3-forecast')中查找指定标题行,使用容错逻辑(金额解析、阶段别名归一化、多格式日期解析)对比Amount、Stage、Close Date是否与Salesforce源数据一致,每项正确加0.20分。组件4检查该数据库的items数量和实际子行数量均恰好为3,且不存在标题含'smb add on'的Closed Lost干扰项,同时要求前面至少有一行已正确填充(any_filled),满足加0.15分。组件5在Slack #sales频道中筛选当前用户发送的新消息,验证消息内容包含三个机会的实时计算总金额、提及全部三个账户名称(Globex、Initech、Soylent),且不包含干扰项'Globex SMB Add-on',满足加0.25分。最终汇总得分,经min(score, 1.0)钳制并四舍五入到4位小数后返回。\",\"confidence\":1.0}" +} diff --git a/legacy/ae_meeting_followup_002/_cua_gym_vm_bridge.sh b/legacy/ae_meeting_followup_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/ae_meeting_followup_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/ae_meeting_followup_002/initial_setup.py b/legacy/ae_meeting_followup_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..21417359fd27a86abf6dd1ae4fa80c23eb2e7d4e --- /dev/null +++ b/legacy/ae_meeting_followup_002/initial_setup.py @@ -0,0 +1,576 @@ +# --- 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.186.212"): + 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: Post-meeting follow-up across Notion, Gmail, and Salesforce. +Task ID: ae_meeting_followup_002 +Domain: mock_websites (multi-mock) +Mocks: notion, gmail, salesforce + +Persona: Alex Rivera (user-1), AE at Northwind Cloud + (alex.rivera@northwindcloud.com). Today = 2026-06-24. + +Pre-task state ONLY. MUST NOT contain task-completed elements: + - Notion 'Meetings' database holds ONLY unrelated past events + (no Initech technical deep-dive row). + - Gmail: NO follow-up sent to Daniel Park (sent folder has no such mail). + - Salesforce: opp-2 'Initech - Annual Renewal' has NO open activities + (no pricing-proposal task). +Distractors that MUST exist and be left untouched by the golden state: + - Notion page 'Meeting Notes - Globex Expansion'. + - Salesforce contact-7 'Daniela Park' at account 'Initrode'. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Mock registry --- +MOCKS = { + 'notion': 'http://28.7.186.212:8186', + 'gmail': 'http://28.7.186.212:8158', + 'salesforce': 'http://28.7.186.212:8195', +} + +# --- Shared session id --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid = {sid}') + + +# ---------------------------------------------------------------------------- +# Notion state +# - Meeting notes page (Initech renewal) with attendee + action items +# - 'Meetings' database with only unrelated past events +# - Distractor 'Meeting Notes - Globex Expansion' page +# ---------------------------------------------------------------------------- +def notion_state(): + user = {"id": "user-1", "name": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com", "avatar": ""} + workspace = {"id": "ws-1", "name": "Northwind Sales", "icon": "🏢", + "members": ["user-1"]} + + # --- Meeting notes page (Initech) --- + notes_page_id = "page-initech-notes" + blocks = { + "blk-attendee": { + "id": "blk-attendee", "type": "text", + "content": "Attendee: Daniel Park, CTO, Initech LLC " + "(daniel.park@initech.com)", + "properties": {}, + "createdDate": "2026-06-18T15:00:00.000Z", + "lastEditedDate": "2026-06-18T15:00:00.000Z", + }, + "blk-disc-head": { + "id": "blk-disc-head", "type": "heading-2", + "content": "Discussion", "properties": {}, + "createdDate": "2026-06-18T15:01:00.000Z", + "lastEditedDate": "2026-06-18T15:01:00.000Z", + }, + "blk-disc-body": { + "id": "blk-disc-body", "type": "text", + "content": "Reviewed the annual renewal. Daniel wants an updated " + "pricing proposal and a technical deep-dive with his " + "engineering team before signing.", + "properties": {}, + "createdDate": "2026-06-18T15:02:00.000Z", + "lastEditedDate": "2026-06-18T15:02:00.000Z", + }, + "blk-action-head": { + "id": "blk-action-head", "type": "heading-2", + "content": "Action Items", "properties": {}, + "createdDate": "2026-06-18T15:03:00.000Z", + "lastEditedDate": "2026-06-18T15:03:00.000Z", + }, + "blk-action-1": { + "id": "blk-action-1", "type": "todo", + "content": "Send the updated pricing proposal to Daniel by " + "Friday 2026-06-26", + "properties": {"checked": False}, + "createdDate": "2026-06-18T15:04:00.000Z", + "lastEditedDate": "2026-06-18T15:04:00.000Z", + }, + "blk-action-2": { + "id": "blk-action-2", "type": "todo", + "content": "Schedule a technical deep-dive call for 2026-06-24 " + "at 10:00 AM", + "properties": {"checked": False}, + "createdDate": "2026-06-18T15:05:00.000Z", + "lastEditedDate": "2026-06-18T15:05:00.000Z", + }, + # Distractor page content + "blk-globex": { + "id": "blk-globex", "type": "text", + "content": "Globex expansion kickoff — discussed adding 200 seats " + "in Q3. Unrelated to the Initech renewal.", + "properties": {}, + "createdDate": "2026-06-19T09:00:00.000Z", + "lastEditedDate": "2026-06-19T09:00:00.000Z", + }, + } + + notes_page = { + "id": notes_page_id, + "title": "Meeting Notes - Initech Renewal (2026-06-18)", + "icon": "📝", "cover": None, "parentId": None, + "blockIds": ["blk-attendee", "blk-disc-head", "blk-disc-body", + "blk-action-head", "blk-action-1", "blk-action-2"], + "favorite": False, + "createdDate": "2026-06-18T15:00:00.000Z", + "lastEditedDate": "2026-06-18T15:05:00.000Z", + "properties": {}, + } + + # --- Distractor: Globex meeting notes page --- + globex_page_id = "page-globex-notes" + globex_page = { + "id": globex_page_id, + "title": "Meeting Notes - Globex Expansion", + "icon": "📝", "cover": None, "parentId": None, + "blockIds": ["blk-globex"], + "favorite": False, + "createdDate": "2026-06-19T09:00:00.000Z", + "lastEditedDate": "2026-06-19T09:00:00.000Z", + "properties": {}, + } + + # --- 'Meetings' database (table view) --- + meetings_db_id = "db-meetings" + # notion_mock stores row property values as a FLAT map and has no "title" + # property type (title comes from page.title / the built-in Name column). + meetings_props = [ + {"id": "prop_date", "name": "Date", "type": "date"}, + {"id": "prop_attendee", "name": "Attendee", "type": "text"}, + ] + + def make_event_row(page_id, event, date, attendee, created): + return { + "id": page_id, + "title": event, + "icon": "", "cover": None, "parentId": meetings_db_id, + "blockIds": [], "favorite": False, + "createdDate": created, "lastEditedDate": created, + "properties": { + "prop_date": date, + "prop_attendee": attendee, + }, + } + + # Unrelated PAST events only (no Initech technical deep-dive). + row_past_1 = make_event_row( + "evt-globex-sync", "Globex Quarterly Sync", "2026-06-10", + "Maria Lopez", "2026-06-01T12:00:00.000Z") + row_past_2 = make_event_row( + "evt-internal-fcst", "Northwind Sales Forecast Review", "2026-06-12", + "Sam Lee", "2026-06-02T12:00:00.000Z") + + meetings_db = { + "id": meetings_db_id, + "title": "Meetings", + "icon": "📅", "cover": None, "parentId": None, + "type": "database", "viewType": "table", + "properties": meetings_props, + "views": [{ + "id": "view-meetings", "name": "Table", "type": "table", + "filters": [], "sorts": [], "groupBy": None, + "visibleProperties": ["prop_date", "prop_attendee"], + }], + "items": ["evt-globex-sync", "evt-internal-fcst"], + "blockIds": [], "favorite": False, + "createdDate": "2026-05-01T09:00:00.000Z", + } + + pages = { + notes_page_id: notes_page, + globex_page_id: globex_page, + meetings_db_id: meetings_db, + "evt-globex-sync": row_past_1, + "evt-internal-fcst": row_past_2, + } + + return { + "user": user, + "workspace": workspace, + "pages": pages, + "blocks": blocks, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, + "fontSize": "default"}, + "notifications": [], + "pageOrder": [notes_page_id, globex_page_id, meetings_db_id], + } + + +# ---------------------------------------------------------------------------- +# Gmail state — Alex Rivera; inbound thread from Daniel Park, NO follow-up sent +# ---------------------------------------------------------------------------- +def gmail_state(): + return { + "user": {"userId": "user-1", "username": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com", "avatar": ""}, + "emails": [ + { + "id": "email_1", "threadId": "thread_initech", + "from": {"name": "Daniel Park", "email": "daniel.park@initech.com"}, + "to": [{"name": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com"}], + "cc": [], "bcc": [], + "subject": "Initech renewal - thanks for today", + "body": ("Hi Alex,

Thanks for the call today on the annual " + "renewal. To recap, we agreed you'll send the updated " + "pricing proposal by Friday, and we'll do the technical " + "deep-dive with my team. Looking forward to it.

" + "Best,
Daniel Park
CTO, Initech LLC"), + "timestamp": "2026-06-18T16:30:00Z", + "read": True, "starred": False, "important": True, + "labels": ["l1"], "category": "primary", "folder": "inbox", + "attachments": [], + }, + { + "id": "email_2", "threadId": "thread_2", + "from": {"name": "Sam Lee", "email": "sam.lee@northwindcloud.com"}, + "to": [{"name": "Alex Rivera", + "email": "alex.rivera@northwindcloud.com"}], + "cc": [], "bcc": [], + "subject": "Great work on the Initech call", + "body": "Nice job, Alex. Let me know how the follow-ups go.", + "timestamp": "2026-06-18T17:00:00Z", + "read": False, "starred": False, "important": False, + "labels": ["l1"], "category": "primary", "folder": "inbox", + "attachments": [], + }, + ], + "labels": [ + {"id": "l1", "name": "Work", "color": "#ef4444"}, + {"id": "l2", "name": "Personal", "color": "#3b82f6"}, + {"id": "l3", "name": "Travel", "color": "#22c55e"}, + {"id": "l4", "name": "Finance", "color": "#eab308"}, + ], + "drafts": [], + } + + +# ---------------------------------------------------------------------------- +# Salesforce state +# - opp-2 'Initech - Annual Renewal' (account-2, contact-2 Daniel Park) +# - distractor contact-7 'Daniela Park' at account 'Initrode' +# - NO open activities +# ---------------------------------------------------------------------------- +def salesforce_state(): + user_1 = { + "userId": "user-1", "firstName": "Alex", "lastName": "Rivera", + "email": "alex.rivera@northwindcloud.com", "phone": "(555) 240-1188", + "title": "Account Executive", "department": "Sales", "role": "Rep", + "avatar": "https://i.pravatar.cc/150?u=user-1", + "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning", + } + user_2 = { + "userId": "user-2", "firstName": "Sam", "lastName": "Lee", + "email": "sam.lee@northwindcloud.com", "phone": "(555) 240-1190", + "title": "Sales Manager", "department": "Sales", "role": "Manager", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning", + } + + accounts = [ + {"accountId": "account-2", "name": "Initech LLC", "type": "Customer", + "industry": "Software", "revenue": 22000000, "employees": 320, + "ownerId": "user-1", "billingStreet": "78 Office Park Dr", + "billingCity": "Austin", "billingState": "TX", + "billingZip": "73301", "billingCountry": "USA"}, + # Distractor account + {"accountId": "account-7", "name": "Initrode", "type": "Prospect", + "industry": "Consulting", "revenue": 5000000, "employees": 60, + "ownerId": "user-1", "billingStreet": "9 Rodeo Ln", + "billingCity": "Dallas", "billingState": "TX", + "billingZip": "75201", "billingCountry": "USA"}, + ] + + contacts = [ + {"contactId": "contact-2", "accountId": "account-2", + "firstName": "Daniel", "lastName": "Park", "title": "CTO", + "department": "Engineering", "email": "daniel.park@initech.com", + "phone": "(555) 330-2201", "ownerId": "user-1"}, + # Distractor contact — different person, different account + {"contactId": "contact-7", "accountId": "account-7", + "firstName": "Daniela", "lastName": "Park", "title": "Operations Lead", + "department": "Operations", "email": "daniela.park@initrode.com", + "phone": "(555) 770-9912", "ownerId": "user-1"}, + ] + + opportunities = [ + {"opportunityId": "opp-2", "name": "Initech - Annual Renewal", + "accountId": "account-2", "contactId": "contact-2", "amount": 60000, + "closeDate": "2026-06-30", "stage": "Proposal", "probability": 60, + "ownerId": "user-1"}, + ] + + return { + "user": user_1, + "users": [user_1, user_2], + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": [], # NO open activities yet + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# ---------------------------------------------------------------------------- +# Inject all states +# ---------------------------------------------------------------------------- +STATE_BUILDERS = { + 'notion': notion_state, + 'gmail': gmail_state, + 'salesforce': salesforce_state, +} + +for name, build in STATE_BUILDERS.items(): + url = MOCKS[name] + state = build() + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, \ + f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f' injected {name}: initial_state OK') + +print(f'All 3 mocks injected with sid={sid}') + + +# ---------------------------------------------------------------------------- +# GUI-ready: launch Chrome on Notion (primary app — where the notes live) +# ---------------------------------------------------------------------------- +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"]}/?sid={sid}"', + delay_sec=2.0, +) +_open_remaining_mock_tabs(MOCKS["notion"]) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {MOCKS["notion"]}/?sid={sid}') diff --git a/legacy/ae_meeting_followup_002/reward.py b/legacy/ae_meeting_followup_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..34f6e3d57b764a597c791d5268591dd37b5d8db7 --- /dev/null +++ b/legacy/ae_meeting_followup_002/reward.py @@ -0,0 +1,560 @@ +# --- 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.186.212"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +""" +Reward Script: AE meeting follow-up across Gmail, Salesforce, and Notion +Task ID: ae_meeting_followup_002 +Domain: mock_websites (multi-mock: gmail, salesforce, notion) + +Task: After the Initech renewal call, the agent must + (1) send Daniel a follow-up email from Gmail recapping the two agreed items + (pricing proposal due 2026-06-26, technical deep-dive call 2026-06-24), + (2) log the pricing-proposal action as a task on the Initech opportunity (opp-2) + in Salesforce with due date 2026-06-26, assigned to user-1, + (3) add the technical deep-dive call to the Notion 'Meetings' calendar + (Date 2026-06-24, Attendee Daniel Park). + Distractors (Daniela Park / Initrode, Globex notes) must remain untouched. + +Scoring (programmatic only — task is fully deterministic): + Gmail 0.35 : sent follow-up to daniel.park@initech.com (0.20) recapping both agreed items and dates (0.15) + Salesforce 0.35 : task on opp-2 referencing pricing proposal, assigned user-1 (0.20) + dueDate 2026-06-26 (0.15) + Notion 0.30 : new Meetings row for the deep-dive (0.15) + Date 2026-06-24 & Attendee Daniel Park (0.15) + Distractor gate : if a distractor was clearly acted on, zero out the relevant mock's credit. +""" +import re +import sys +from datetime import date, timedelta +from html import unescape + +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 = { + 'gmail': 'http://28.7.186.212:8158', + 'salesforce': 'http://28.7.186.212:8195', + 'notion': 'http://28.7.186.212:8186', +} + +# --- Fetch state from all three mocks --- +states = {} +for name, url in MOCKS.items(): + try: + resp = requests.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) + +gmail_initial = states['gmail'].get('initial_state') or {} +gmail_cur = states['gmail'].get('current_state') or {} +sf_initial = states['salesforce'].get('initial_state') or {} +sf_cur = states['salesforce'].get('current_state') or {} +notion_initial = states['notion'].get('initial_state') or {} +notion_cur = states['notion'].get('current_state') or {} + +DANIEL_EMAIL = 'daniel.park@initech.com' +DANIELA_EMAIL = 'daniela.park@initrode.com' +DANIEL_NAME = 'daniel park' +DANIELA_NAME = 'daniela park' +TASK_TODAY = date(2026, 6, 24) +DEFAULT_YEAR = TASK_TODAY.year +FALLBACK_PROPOSAL_DATE = date(2026, 6, 26) +FALLBACK_DEEPDIVE_DATE = date(2026, 6, 24) +FALLBACK_DEEPDIVE_TIME = (10, 0) + +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, +} +WEEKDAYS = { + 'monday': 0, 'mon': 0, + 'tuesday': 1, 'tue': 1, 'tues': 1, + 'wednesday': 2, 'wed': 2, + 'thursday': 3, 'thu': 3, 'thur': 3, 'thurs': 3, + 'friday': 4, 'fri': 4, + 'saturday': 5, 'sat': 5, + 'sunday': 6, 'sun': 6, +} + +PRICING_TERMS = ( + 'pricing proposal', 'price proposal', 'updated proposal', + 'proposal', 'pricing', 'quote', 'commercial proposal', + 'renewal proposal', +) +DEEPDIVE_TERMS = ( + 'technical deep dive', 'technical deep-dive', 'deep dive', + 'deep-dive', 'deepdive', 'technical review', 'technical session', + 'technical call', 'technical meeting', 'engineering call', + 'engineering session', 'architecture review', +) + + +def _plain_text(value): + text = unescape(str(value or '')) + text = re.sub(r'<[^>]+>', ' ', text) + text = text.replace('\u2010', '-').replace('\u2011', '-') + text = text.replace('\u2012', '-').replace('\u2013', '-') + text = text.replace('\u2014', '-').replace('\u00a0', ' ') + return re.sub(r'\s+', ' ', text).strip().lower() + + +def _token_text(value): + text = _plain_text(value) + text = re.sub(r'[^a-z0-9@._:+/-]+', ' ', text) + text = text.replace('-', ' ') + return re.sub(r'\s+', ' ', text).strip() + + +def _has_any(value, terms): + text = _token_text(value) + return any(_token_text(term) in text for term in terms) + + +def _safe_date(year, month, day): + try: + return date(int(year), int(month), int(day)) + except Exception: + return None + + +def _normalize_year(year): + if year is None or year == '': + return DEFAULT_YEAR + year = int(year) + if year < 100: + return 2000 + year + return year + + +def _next_or_same_weekday(base, weekday): + delta = (weekday - base.weekday()) % 7 + return base + timedelta(days=delta) + + +def _extract_dates(value, base_date=TASK_TODAY): + text = _plain_text(value) + found = set() + + for y, m, d in re.findall(r'\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b', text): + dt = _safe_date(y, m, d) + if dt: + found.add(dt) + + month_re = r'jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?' + for mon, d, y in re.findall( + rf'\b({month_re})\.?\s+(\d{{1,2}})(?:st|nd|rd|th)?(?:,?\s+(\d{{2,4}}))?\b', + text): + dt = _safe_date(_normalize_year(y), MONTHS[mon[:3]], d) + if dt: + found.add(dt) + + for d, mon, y in re.findall( + rf'\b(\d{{1,2}})(?:st|nd|rd|th)?\s+({month_re})\.?(?:,?\s+(\d{{2,4}}))?\b', + text): + dt = _safe_date(_normalize_year(y), MONTHS[mon[:3]], d) + if dt: + found.add(dt) + + for m, d, y in re.findall(r'\b(\d{1,2})[/-](\d{1,2})(?:[/-](\d{2,4}))?\b', text): + dt = _safe_date(_normalize_year(y), m, d) + if dt: + found.add(dt) + + if re.search(r'\btoday\b', text): + found.add(base_date) + if re.search(r'\bday after tomorrow\b', text): + found.add(base_date + timedelta(days=2)) + if re.search(r'(? 0.0\n - 无法从 mock 获取状态 -> 0.0\n - 发送给 Daniela(干扰项)-> Gmail 分数被扣减\n - 没有找到对应的项目 -> 该组件失败\n\n6. **分数汇总**:\n - 各组件分数相加\n - 最终 `round(min(total, 1.0), 4)`\n\n7. **is_placeholder**:\n - false,因为脚本确实进行了详细的状态检查和评分\n\n8. **confidence**:\n - 1.0,因为代码逻辑非常清晰\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"ae_meeting_followup_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证代理在Initech续约电话后,是否通过Gmail向Daniel发送跟进邮件、在Salesforce的opp-2上记录定价提案任务,并在Notion的Meetings日历中添加技术深入交流会议。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"gmail_mock (http://28.7.186.212:8158)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"notion_mock (http://28.7.186.212:8186)\"],\n \"scoring_components\": [\n {\n \"name\": \"Gmail Component 1a\",\n \"weight\": 0.2,\n \"description\": \"检查是否向Daniel Park发送了跟进邮件\",\n \"check_logic\": \"遍历gmail_current_state中folder为'sent'且id不在initial_email_ids中的邮件,检查to字段是否包含daniel.park@initech.com;同时检查是否错误发送给daniela.park@initrode.com。若发送给Daniel且未发送给Daniela,则通过。\",\n \"pass_condition\": \"存在一封发送给daniel.park@initech.com的新邮件,且未发送给daniela.park@initrode.com\"\n },\n {\n \"name\": \"Gmail Component 1b\",\n \"weight\": 0.15,\n \"description\": \"检查邮件内容是否回顾了两个约定事项及其日期\",\n \"check_logic\": \"对发送给Daniel的邮件,合并subject、body、snippet进行文本分析。检查是否同时包含pricing proposal相关术语且日期匹配DATE_PROPOSAL,以及deep-dive相关术语且日期匹配DATE_DEEPDIVE、时间匹配TIME_DEEPDIVE。\",\n \"pass_condition\": \"邮件正文同时包含pricing proposal(含日期2026-06-26)和technical deep-dive(含日期2026-06-24及对应时间)的回顾\"\n },\n {\n \"name\": \"Salesforce Component 2a\",\n \"weight\": 0.2,\n \"description\": \"检查是否在opp-2上创建了引用定价提案的任务并分配给user-1\",\n \"check_logic\": \"遍历salesforce_current_state中activityId不在initial_activity_ids、type为'task'、relatedToId为'opp-2'的活动,检查文本是否包含pricing相关术语,且assignedToId为'user-1'。\",\n \"pass_condition\": \"存在新任务关联到opp-2,内容引用pricing proposal,且assignedToId等于'user-1'\"\n },\n {\n \"name\": \"Salesforce Component 2b\",\n \"weight\": 0.15,\n \"description\": \"检查Salesforce任务的截止日期是否为2026-06-26\",\n \"check_logic\": \"对找到的pricing-proposal任务,使用_date_matches检查dueDate字段是否匹配DATE_PROPOSAL(2026-06-26)。\",\n \"pass_condition\": \"任务的dueDate匹配2026-06-26\"\n },\n {\n \"name\": \"Notion Component 3a\",\n \"weight\": 0.15,\n \"description\": \"检查是否在Notion的Meetings数据库中新增了引用技术深入交流的行\",\n \"check_logic\": \"遍历notion_current_state中pages下db-meetings的items,排除initial_items,检查parentId为'db-meetings'的行。合并title和prop_event文本,检查是否包含deep-dive相关术语,且不含干扰项(Daniela/Initrode)。\",\n \"pass_condition\": \"存在新的Meetings行,内容引用technical deep-dive,且不包含Daniela Park或Initrode等干扰信息\"\n },\n {\n \"name\": \"Notion Component 3b\",\n \"weight\": 0.15,\n \"description\": \"检查Notion行的日期是否为2026-06-24且参与者为Daniel Park\",\n \"check_logic\": \"对找到的deep-dive行,检查prop_date是否匹配DATE_DEEPDIVE(2026-06-24),且prop_attendee是否包含Daniel Park(不含Daniela)。\",\n \"pass_condition\": \"行的Date属性匹配2026-06-24,且Attendee属性包含Daniel Park\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终通过round(min(total, 1.0), 4)钳制到1.0并保留4位小数\",\n \"failure_modes\": [\n \"无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0\",\n \"无法从任一mock服务获取状态时打印CRITICAL并返回0.0\",\n \"Gmail邮件同时发送给Daniela Park(干扰项)时,Gmail相关credit被扣减(不加分)\",\n \"Notion行包含Daniela/Initrode等干扰项时,event_ok为False导致该组件不得分\",\n \"各mock中未找到符合条件的新增项目时对应组件不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID,然后分别向gmail、salesforce、notion三个mock服务拉取initial_state和current_state。对于Gmail,扫描Sent文件夹中新增邮件,优先匹配发送给daniel.park@initech.com的邮件,若同时发送给daniela.park@initrode.com则触发干扰项门控;对有效邮件检查正文是否同时包含pricing proposal(含日期2026-06-26)和technical deep-dive(含日期2026-06-24及时间)。对于Salesforce,扫描activities中新增且type为task、relatedToId为opp-2的记录,检查是否引用pricing proposal、assignedToId为user-1、dueDate为2026-06-26。对于Notion,扫描db-meetings中新增行,检查是否引用deep-dive(无干扰项)、Date为2026-06-24、Attendee为Daniel Park。各子项通过则累加对应权重(0.20/0.15/0.20/0.15/0.15/0.15),最终总分经min(total, 1.0)钳制后四舍五入到4位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查字段:\n- task_id: ae_meeting_followup_002 ✓\n- domain: mock_websites ✓\n- summary: 一句话概括 ✓\n- is_placeholder: false ✓\n- data_sources: 包含三个mock和sid文件 ✓\n- scoring_components: 6个组件,权重正确 ✓\n- total_max_score: 1.0 ✓\n- score_aggregation: 相加并钳制 ✓\n- failure_modes: 列出了关键失败路径 ✓\n- scoring_logic_explanation: 详细中文解释 ✓\n- confidence: 1.0 ✓\n\n确保没有Markdown代码块,第一个字符是{,最后一个字符是}。 {\n \"task_id\": \"ae_meeting_followup_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证代理在Initech续约电话后,是否通过Gmail向Daniel发送跟进邮件、在Salesforce的opp-2上记录定价提案任务,并在Notion的Meetings日历中添加技术深入交流会议。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"gmail_mock (http://28.7.186.212:8158)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"notion_mock (http://28.7.186.212:8186)\"],\n \"scoring_components\": [\n {\n \"name\": \"Gmail Component 1a\",\n \"weight\": 0.2,\n \"description\": \"检查是否向Daniel Park发送了跟进邮件\",\n \"check_logic\": \"遍历gmail_current_state中folder为'sent'且id不在initial_email_ids中的邮件,检查to字段是否包含daniel.park@initech.com;同时检查是否错误发送给daniela.park@initrode.com。若发送给Daniel且未发送给Daniela,则通过。\",\n \"pass_condition\": \"存在一封发送给daniel.park@initech.com的新邮件,且未发送给daniela.park@initrode.com\"\n },\n {\n \"name\": \"Gmail Component 1b\",\n \"weight\": 0.15,\n \"description\": \"检查邮件内容是否回顾了两个约定事项及其日期\",\n \"check_logic\": \"对发送给Daniel的邮件,合并subject、body、snippet进行文本分析。检查是否同时包含pricing proposal相关术语且日期匹配DATE_PROPOSAL,以及deep-dive相关术语且日期匹配DATE_DEEPDIVE、时间匹配TIME_DEEPDIVE。\",\n \"pass_condition\": \"邮件正文同时包含pricing proposal(含日期2026-06-26)和technical deep-dive(含日期2026-06-24及对应时间)的回顾\"\n },\n {\n \"name\": \"Salesforce Component 2a\",\n \"weight\": 0.2,\n \"description\": \"检查是否在opp-2上创建了引用定价提案的任务并分配给user-1\",\n \"check_logic\": \"遍历salesforce_current_state中activityId不在initial_activity_ids、type为'task'、relatedToId为'opp-2'的活动,检查文本是否包含pricing相关术语,且assignedToId为'user-1'。\",\n \"pass_condition\": \"存在新任务关联到opp-2,内容引用pricing proposal,且assignedToId等于'user-1'\"\n },\n {\n \"name\": \"Salesforce Component 2b\",\n \"weight\": 0.15,\n \"description\": \"检查Salesforce任务的截止日期是否为2026-06-26\",\n \"check_logic\": \"对找到的pricing-proposal任务,使用_date_matches检查dueDate字段是否匹配DATE_PROPOSAL(2026-06-26)。\",\n \"pass_condition\": \"任务的dueDate匹配2026-06-26\"\n },\n {\n \"name\": \"Notion Component 3a\",\n \"weight\": 0.15,\n \"description\": \"检查是否在Notion的Meetings数据库中新增了引用技术深入交流的行\",\n \"check_logic\": \"遍历notion_current_state中pages下db-meetings的items,排除initial_items,检查parentId为'db-meetings'的行。合并title和prop_event文本,检查是否包含deep-dive相关术语,且不含干扰项(Daniela/Initrode)。\",\n \"pass_condition\": \"存在新的Meetings行,内容引用technical deep-dive,且不包含Daniela Park或Initrode等干扰信息\"\n },\n {\n \"name\": \"Notion Component 3b\",\n \"weight\": 0.15,\n \"description\": \"检查Notion行的日期是否为2026-06-24且参与者为Daniel Park\",\n \"check_logic\": \"对找到的deep-dive行,检查prop_date是否匹配DATE_DEEPDIVE(2026-06-24),且prop_attendee是否包含Daniel Park(不含Daniela)。\",\n \"pass_condition\": \"行的Date属性匹配2026-06-24,且Attendee属性包含Daniel Park\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终通过round(min(total, 1.0), 4)钳制到1.0并保留4位小数\",\n \"failure_modes\": [\n \"无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0\",\n \"无法从任一mock服务获取状态时打印CRITICAL并返回0.0\",\n \"Gmail邮件同时发送给Daniela Park(干扰项)时,Gmail相关credit被扣减(不加分)\",\n \"Notion行包含Daniela/Initrode等干扰项时,event_ok为False导致该组件不得分\",\n \"各mock中未找到符合条件的新增项目时对应组件不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID,然后分别向gmail、salesforce、notion三个mock服务拉取initial_state和current_state。对于Gmail,扫描Sent文件夹中新增邮件,优先匹配发送给daniel.park@initech.com的邮件,若同时发送给daniela.park@initrode.com则触发干扰项门控;对有效邮件检查正文是否同时包含pricing proposal(含日期2026-06-26)和technical deep-dive(含日期2026-06-24及时间)。对于Salesforce,扫描activities中新增且type为task、relatedToId为opp-2的记录,检查是否引用pricing proposal、assignedToId为user-1、dueDate为2026-06-26。对于Notion,扫描db-meetings中新增行,检查是否引用deep-dive(无干扰项)、Date为2026-06-24、Attendee为Daniel Park。各子项通过则累加对应权重(0.20/0.15/0.20/0.15/0.15/0.15),最终总分经min(total, 1.0)钳制后四舍五入到4位小数输出。\",\n \"confidence\": 1.0\n}" +} diff --git a/legacy/am_renewal_cycle_004/_cua_gym_vm_bridge.sh b/legacy/am_renewal_cycle_004/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/am_renewal_cycle_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/am_renewal_cycle_004/initial_setup.py b/legacy/am_renewal_cycle_004/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..70a4c1da4b2d988e485b50e8e5e939ba849998d1 --- /dev/null +++ b/legacy/am_renewal_cycle_004/initial_setup.py @@ -0,0 +1,675 @@ +# --- 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.186.212"): + 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: High-risk strategic renewal motion for Initech across five apps. +Task ID: am_renewal_cycle_004 +Domain: mock_websites (multi-mock) +Mocks: salesforce, notion, gmail, docusign, slack + +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. MUST NOT contain task-completed elements: + - Salesforce: opp-3 stage stays 'Qualification' (NOT Negotiation); NO renewal-planning task activity. + - Notion: Initech row Status stays 'Not Started'; NO renewal brief page. + - Gmail: NO sent renewal email to Priya Nair at priya.nair@initech.example.com + (only unrelated inbound context). + - DocuSign: NO Initech renewal envelope (address book + template exist). + - Slack: NO Initech summary message in #deal-desk. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Mock registry --- +MOCKS = { + 'salesforce': 'http://28.7.186.212:8195', + 'notion': 'http://28.7.186.212:8186', + 'gmail': 'http://28.7.186.212:8158', + 'docusign': 'http://28.7.186.212:8150', + 'slack': 'http://28.7.186.212:8198', +} + +# --- 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 a working proxy: 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 direct connection first. + 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"}') + +# --- Shared session id --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid = {sid}') + + +# ---------------------------------------------------------------------------- +# Salesforce state +# ---------------------------------------------------------------------------- +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", + } + user_2 = { + "userId": "user-2", "firstName": "Dana", "lastName": "Whitfield", + "email": "dana.whitfield@vertexcloud.example.com", "phone": "(555) 310-7750", + "title": "VP Sales", "department": "Sales", "role": "Executive", + "avatar": "https://i.pravatar.cc/150?u=user-2", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + } + + accounts = [ + {"accountId": "account-1", "name": "Northwind Traders", "type": "Customer", + "industry": "Retail", "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": "Technology", "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"}, + ] + + contacts = [ + {"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 = [ + # DISTRACTOR — Northwind annual renewal + {"opportunityId": "opp-1", "name": "Northwind Traders – Annual Renewal", + "accountId": "account-1", "contactId": None, "amount": 85000, + "closeDate": "2026-08-01", "stage": "Proposal", "probability": 70, + "ownerId": "user-1"}, + # DISTRACTOR — Globex platform renewal + {"opportunityId": "opp-2", "name": "Globex Corp – Platform Renewal", + "accountId": "account-2", "contactId": None, "amount": 130000, + "closeDate": "2026-10-15", "stage": "Needs Analysis", "probability": 55, + "ownerId": "user-1"}, + # TARGET — Initech renewal & upsell (high ARR, low win prob -> escalation) + {"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 — same-customer small add-on (must NOT be acted on) + {"opportunityId": "opp-4", "name": "Initech – Sandbox Add-on", + "accountId": "account-3", "contactId": "contact-3", "amount": 8000, + "closeDate": "2026-07-20", "stage": "Qualification", "probability": 60, + "ownerId": "user-1"}, + ] + + return { + "user": user_1, + "users": [user_1, user_2], + "leads": [], + "accounts": accounts, + "contacts": contacts, + "opportunities": opportunities, + "cases": [], + "activities": [], + "chatterPosts": [], + "files": [], + "following": [], + "recentlyViewed": [], + "dismissedNotifications": [], + } + + +# ---------------------------------------------------------------------------- +# Notion state — 'Renewal Tracker 2026' database with Initech row + distractors +# ---------------------------------------------------------------------------- +def notion_state(): + db_id = "db-renewal-tracker-2026" + properties = [ + {"id": "prop_account", "name": "Account", "type": "title"}, + {"id": "prop_arr", "name": "ARR", "type": "number"}, + {"id": "prop_date", "name": "Renewal Date", "type": "date"}, + {"id": "prop_risk", "name": "Risk", "type": "select", + "options": [{"id": "opt_low", "name": "Low"}, + {"id": "opt_med", "name": "Medium"}, + {"id": "opt_high", "name": "High"}]}, + {"id": "prop_status", "name": "Status", "type": "select", + "options": [{"id": "opt_ns", "name": "Not Started"}, + {"id": "opt_ip", "name": "In Progress"}, + {"id": "opt_sfs", "name": "Sent for Signature"}]}, + ] + + def make_row(page_id, account, arr, date, risk, status): + return { + "id": page_id, + "title": account, + "icon": "", + "cover": None, + "parentId": db_id, + "blockIds": [], + "favorite": False, + "createdDate": "2026-06-01T09:00:00.000Z", + "lastEditedDate": "2026-06-01T09:00:00.000Z", + "properties": { + "prop_account": {"title": account}, + "prop_arr": {"number": arr}, + "prop_date": {"date": {"start": date, "end": None}}, + "prop_risk": {"select": risk}, + "prop_status": {"select": status}, + }, + } + + row_initech = make_row("row-initech", "Initech", 240000, "2026-09-10", "High", "Not Started") + row_northwind = make_row("row-northwind", "Northwind Traders", 85000, "2026-08-01", "Low", "In Progress") + row_globex = make_row("row-globex", "Globex Corp", 130000, "2026-10-15", "Medium", "Not Started") + + db_page = { + "id": db_id, + "title": "Renewal Tracker 2026", + "icon": "📊", + "cover": None, + "parentId": None, + "type": "database", + "viewType": "table", + "properties": properties, + "views": [{ + "id": "view-1", "name": "Table", "type": "table", + "filters": [], "sorts": [], "groupBy": None, + "visibleProperties": ["prop_account", "prop_arr", "prop_date", "prop_risk", "prop_status"], + }], + "items": ["row-initech", "row-northwind", "row-globex"], + "blockIds": [], + "favorite": False, + "createdDate": "2026-06-01T09:00:00.000Z", + } + + return { + "user": {"id": "user-1", "name": "Jordan Avery", + "email": "jordan.avery@vertexcloud.example.com", "avatar": ""}, + "workspace": {"id": "ws-1", "name": "Vertex Cloud Renewals", "icon": "🏢", + "members": ["user-1"]}, + "pages": { + db_id: db_page, + "row-initech": row_initech, + "row-northwind": row_northwind, + "row-globex": row_globex, + }, + "blocks": {}, + "trash": [], + "comments": {}, + "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"}, + "notifications": [], + "pageOrder": [db_id], + "focusBlockId": None, + } + + +# ---------------------------------------------------------------------------- +# Gmail state — Jordan Avery, only an unrelated old Initech support thread +# ---------------------------------------------------------------------------- +def gmail_state(): + return { + "user": {"userId": "user-1", "username": "Jordan Avery", + "email": "jordan.avery@vertexcloud.example.com", "avatar": ""}, + "emails": [ + { + "id": "email_1", "threadId": "thread_1", + "from": {"name": "Initech Support", "email": "support@initech.example.com"}, + "to": [{"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}], + "cc": [], "bcc": [], + "subject": "Re: Initech sandbox login issue (resolved)", + "body": "Hi Jordan, thanks for your help last month — the sandbox login " + "issue is fully resolved on our end. Best, Initech Support", + "timestamp": "2026-05-12T15:42:00Z", + "read": True, "starred": False, "important": False, + "labels": ["l1"], "category": "primary", "folder": "inbox", + "attachments": [], + }, + { + "id": "email_2", "threadId": "thread_2", + "from": {"name": "Dana Whitfield", "email": "dana.whitfield@vertexcloud.example.com"}, + "to": [{"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}], + "cc": [], "bcc": [], + "subject": "Initech renewal — let's run the high-risk playbook", + "body": "Jordan, Initech ($240K ARR, 35% win prob) qualifies for the " + "strategic-renewal playbook. Their VP Finance is Priya Nair " + "(priya.nair@initech.example.com). Please drive the full motion this week. — Dana", + "timestamp": "2026-06-24T08:05:00Z", + "read": False, "starred": True, "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": [], + } + + +# ---------------------------------------------------------------------------- +# DocuSign state — address book + template, NO Initech renewal envelope +# ---------------------------------------------------------------------------- +def docusign_state(): + return { + "user": { + "id": "user-1", "name": "Jordan Avery", + "email": "jordan.avery@vertexcloud.example.com", + "title": "Account Manager", "company": "Vertex Cloud", + "memberSince": "2024-02-01", + "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120, + "timezone": "America/New_York"}, + }, + "envelopes": [ + # Distractor: an unrelated completed envelope, nothing to do with Initech renewal + { + "id": "env_globex_1", + "subject": "Globex Corp - Platform Renewal Agreement", + "message": "Please review and sign.", + "status": "completed", + "createdAt": "2026-04-02T10:00:00Z", + "sentAt": "2026-04-02T10:05:00Z", + "completedAt": "2026-04-05T16:20:00Z", + "voidedAt": None, "declinedAt": None, + "lastActivityAt": "2026-04-05T16:20:00Z", + "expiresAt": "2026-08-01T10:05:00Z", + "senderId": "user-1", "folderId": None, "templateId": None, + "reminderEnabled": True, "reminderDays": 3, "reminderFrequency": 2, + "documents": [{"id": "doc_globex_1", "name": "Globex_Platform_Renewal.pdf", + "pageCount": 8, "order": 1, + "fileUrl": "https://picsum.photos/seed/globex/800/1100", + "fileType": "pdf"}], + "recipients": [{"id": "rec_globex_1", "name": "Hank Scorpio", + "email": "hank@globex.example.com", "role": "signer", + "routingOrder": 1, "status": "signed", + "signedAt": "2026-04-05T16:20:00Z", + "viewedAt": "2026-04-03T09:00:00Z", + "deliveredAt": "2026-04-02T10:06:00Z", + "declinedAt": None, "declineReason": None}], + "fields": [], + "history": [ + {"id": "evt_globex_1", "timestamp": "2026-04-02T10:00:00Z", + "action": "created", "actorName": "Jordan Avery", + "actorEmail": "jordan.avery@vertexcloud.example.com", + "details": "Envelope created"}, + {"id": "evt_globex_2", "timestamp": "2026-04-05T16:20:00Z", + "action": "completed", "actorName": "Hank Scorpio", + "actorEmail": "hank@globex.example.com", + "details": "All recipients signed"}, + ], + }, + ], + "templates": [ + {"id": "tmpl_renewal", "name": "Annual Renewal Agreement", + "description": "Standard Vertex Cloud annual renewal agreement template.", + "createdAt": "2025-01-10T09:00:00Z", "lastUsedAt": "2026-04-02T10:00:00Z", + "usageCount": 14, "ownerId": "user-1", "shared": True, + "documents": [{"id": "tdoc_renewal_1", "name": "Annual_Renewal_Agreement.pdf", + "pageCount": 6, "order": 1, + "fileUrl": "https://picsum.photos/seed/renewaltmpl/800/1100", + "fileType": "pdf"}], + "roles": [{"id": "trole_signer", "name": "Customer Signer", "role": "signer", + "routingOrder": 1}, + {"id": "trole_cc", "name": "Vertex Finance", "role": "cc", + "routingOrder": 2}], + "fields": []}, + ], + "folders": [], + "contacts": [ + {"id": "con_priya", "name": "Priya Nair", "email": "priya.nair@initech.example.com", + "company": "Initech", "title": "VP Finance"}, + {"id": "con_finance", "name": "Vertex Finance", "email": "finance@vertexcloud.example.com", + "company": "Vertex Cloud", "title": "Finance Mailbox"}, + {"id": "con_hank", "name": "Hank Scorpio", "email": "hank@globex.example.com", + "company": "Globex Corp", "title": "CEO"}, + ], + "auditLog": [ + {"id": "audit_1", "timestamp": "2026-04-05T16:20:00Z", "action": "COMPLETE_ENVELOPE", + "details": "Globex Corp - Platform Renewal Agreement completed", + "envelopeId": "env_globex_1"}, + ], + } + + +# ---------------------------------------------------------------------------- +# Slack state — Vertex Cloud, #deal-desk with Jordan, finance, legal +# ---------------------------------------------------------------------------- +def slack_state(): + user_1 = {"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": "", + "title": "Account Manager", "timeZone": "America/New_York"} + user_fin = {"userId": "user_2", "fullName": "Finance Team", "displayName": "finance", + "email": "finance@vertexcloud.example.com", + "avatar": "https://picsum.photos/200/200?random=2", + "status": "online", "statusMessage": "", "statusEmoji": "", + "title": "Finance", "timeZone": "America/New_York"} + user_legal = {"userId": "user_3", "fullName": "Legal Team", "displayName": "legal", + "email": "legal@vertexcloud.example.com", + "avatar": "https://picsum.photos/200/200?random=3", + "status": "online", "statusMessage": "", "statusEmoji": "", + "title": "Legal", "timeZone": "America/New_York"} + return { + "currentUser": user_1, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Vertex Cloud", "icon": ""}, + "users": [user_1, user_fin, user_legal], + "channels": [ + {"channelId": "deal-desk", "name": "deal-desk", + "description": "Deal desk: finance + legal review of strategic deals", + "topic": "Strategic renewals & approvals", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3"], "createdBy": "user_2", + "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "general", "name": "general", "description": "Company-wide chat", + "topic": "", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3"], "createdBy": "user_2", + "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "deal-desk": [ + {"messageId": "msg_1", "senderId": "user_2", + "content": "Reminder: anything ARR >= $200K with win prob < 50% needs the " + "high-risk strategic-renewal playbook and a closure summary here.", + "timestamp": "2026-06-22T09:00:00Z", "threadId": None, + "reactions": [], "attachments": [], "isEdited": False}, + ], + "general": [], + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", + "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + + +# ---------------------------------------------------------------------------- +# Inject all states +# ---------------------------------------------------------------------------- +STATE_BUILDERS = { + 'salesforce': salesforce_state, + 'notion': notion_state, + 'gmail': gmail_state, + 'docusign': docusign_state, + 'slack': slack_state, +} + +for name, build in STATE_BUILDERS.items(): + url = MOCKS[name] + state = build() + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': state}, timeout=30, + 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=10, proxies=PROXIES).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f' injected {name}: initial_state OK') + +print(f'All 5 mocks injected with sid={sid}') + + +# ---------------------------------------------------------------------------- +# GUI-ready: launch Chrome on Salesforce (primary app) +# ---------------------------------------------------------------------------- +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} (proxy={PROXY or "direct"})') diff --git a/legacy/am_renewal_cycle_004/reward.py b/legacy/am_renewal_cycle_004/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/legacy/am_renewal_cycle_004/reward_label.json b/legacy/am_renewal_cycle_004/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..07e7623db96de67edfee9d67f76c83a93395bb8f --- /dev/null +++ b/legacy/am_renewal_cycle_004/reward_label.json @@ -0,0 +1,23 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_cycle_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-14 10:21:32", + "label": { + "task_id": null, + "domain": null, + "summary": "未提供 reward.py 源码,无法分析评分逻辑", + "is_placeholder": true, + "data_sources": [], + "scoring_components": [], + "total_max_score": 1.0, + "score_aggregation": "无法确定", + "failure_modes": [ + "未提供源码,无法识别任何失败路径" + ], + "scoring_logic_explanation": "输入中未包含 reward.py 的源码内容,因此无法依据源码分析其评分逻辑、状态读取方式、检查组件及分数汇总方式。", + "confidence": 0.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。但是,用户提供的源码部分是空的——在【reward.py 源码】后面没有实际代码内容。\n\n我需要根据分析原则如实依据源码填写。由于没有提供源码,我无法确定 task_id、domain、评分逻辑等。在这种情况下,我应该:\n\n1. 检查是否有任何代码内容——看起来没有。\n2. 由于无法读取文件,且用户没有提供源码,我只能基于\"无源码\"这一事实进行分析。\n3. 但是,用户明确说\"请分析下面这个 reward.py\",可能是在某个上下文中遗漏了代码。作为AI,我只能基于实际提供的输入进行判断。\n\n等等,让我仔细看用户消息。用户说:\n【reward.py 源码】\n\n后面确实没有内容。\n\n在这种情况下,我应该:\n- task_id: 从文件路径看,文件名似乎是 am_renewal_cycle_004,所以 task_id 可能是 am_renewal_cycle_004\n- domain: 从路径看,可能是 mini_osworld_xiangwu,但这不是标准领域。从 task_id 前缀 am_ 看,可能是 account_management 或类似?但无法从源码确定,因为没给源码。\n- 由于没有源码,我无法确定评分逻辑。\n\n但是,用户可能期望我基于路径中的 task_id 给出某种回应。然而,分析原则说\"如实依据源码填写,不要臆测未在代码中出现的信息\"。由于没有源码,几乎所有字段都无法确定。\n\n不过,文件路径中包含 \"am_renewal_cycle_004\",这可能就是 task_id。但 domain 无法确定。\n\n等等,也许用户忘记粘贴代码了?但我必须基于给定输入回答。\n\n如果完全没有源码,我应该:\n- task_id: \"am_renewal_cycle_004\"(从路径提取,但这不算 docstring)\n- 实际上,task_id 要求\"从文件 docstring 中提取\",如果没有 docstring 且无法确定,填 null。\n- domain: null\n- summary: \"未提供源码,无法分析评分逻辑\"\n- is_placeholder: 无法确定,但由于没有源码,实际上无法判断。不过也许应该设为 true?不,不能臆测。\n\n实际上,如果源码完全缺失,我无法进行任何有意义的分析。但用户明确要求输出 JSON。我应该诚实地说明没有提供源码。\n\n但是,等等,我再看一遍。用户消息以\"【reward.py 源码】\"结束,后面确实没有代码。这可能是用户的错误。\n\n在这种情况下,最严谨的做法是输出一个 JSON,表明无法分析,因为源码未提供。但格式必须符合要求。\n\n让我重新阅读指令:\"请只输出一个 JSON 对象... 不要输出额外解释\"。\n\n如果源码未提供,我无法填写 scoring_components 等。但也许我可以基于文件路径做一些最小程度的填充:\n\n- task_id: null(因为 docstring 未提供,路径中的不是 docstring)\n- domain: null\n- summary: \"未提供 reward.py 源码,无法分析评分逻辑\"\n- is_placeholder: true(因为没有实际可检查的代码内容)\n- data_sources: []\n- scoring_components: []\n- total_max_score: 1.0\n- score_aggregation: \"无法确定\"\n- failure_modes: [\"未提供源码\"]\n- scoring_logic_explanation: \"用户未提供 reward.py 的源码内容,因此无法分析其评分逻辑、数据源、检查组件及分数汇总方式。\"\n- confidence: 0.0\n\n这看起来是最诚实和严谨的。我不能编造代码逻辑。\n\n但是,等等,用户可能在之前的消息中提供了代码,或者这是一个多轮对话?不,这是第一轮。\n\n另一个想法:也许用户期望我分析路径中的 task_id。文件路径是 .../am_renewal_cycle_004/reward.py。在某些系统中,task_id 就是目录名。但指令明确说\"从文件 docstring 中提取的任务 ID\",所以如果没有 docstring,应该填 null。\n\n我决定输出一个表明\"未提供源码\"的 JSON。这符合\"如实依据源码填写\"的原则——源码确实为空。\n\n让我构造 JSON:\n\n{\n \"task_id\": null,\n \"domain\": null,\n \"summary\": \"未提供 reward.py 源码,无法分析评分逻辑\",\n \"is_placeholder\": true,\n \"data_sources\": [],\n \"scoring_components\": [],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"无法确定\",\n \"failure_modes\": [\"未提供源码,无法识别任何失败路径\"],\n \"scoring_logic_explanation\": \"用户未提供 reward.py 的源码内容,因此无法分析其评分逻辑、数据源、检查组件及分数汇总方式。\",\n \"confidence\": 0.0\n}\n\n等等,is_placeholder 设为 true 是否合适?占位脚本通常指脚本存在但只是 return 0.0。这里连脚本内容都没有。不过设为 true 表示\"这不是一个有效的可分析脚本\"也勉强可以。或者我可以写 null?但字段要求是 true 或 false。\n\n实际上,如果没有源码,说 is_placeholder: true 有点不准确,因为不知道它是不是占位脚本。但既然没有内容,也许可以认为是\"事实上的占位\"。不过严格来说,我不应该臆测。\n\n让我再想想。用户明确说\"请分析下面这个 reward.py 评分脚本的评分逻辑\",然后没有给源码。这可能是系统错误。作为AI,我只能基于已有信息。\n\n也许我应该直接输出 JSON,说明源码缺失。\n\n但等等,我注意到路径中有 \"am_renewal_cycle_004\"。\"am\" 可能代表 \"account management\"?但 domain 要求从 docstring 提取,所以仍是 null。\n\n我坚持输出\"无源码\"的 JSON。这是最诚实的。\n\n再检查一下 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n\n好的,我直接输出 JSON。\n\n等等,我突然想到,也许用户是在测试我是否会 hallucinate 代码逻辑。如果是这样,编造内容是大错。所以坚决不能编。\n\n最终 JSON:\n\n{\n \"task_id\": null,\n \"domain\": null,\n \"summary\": \"未提供 reward.py 源码,无法分析评分逻辑\",\n \"is_placeholder\": true,\n \"data_sources\": [],\n \"scoring_components\": [],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"无法确定\",\n \"failure_modes\": [\"未提供源码,无法识别任何失败路径\"],\n \"scoring_logic_explanation\": \"输入中未包含 reward.py 的源码内容,因此无法依据源码分析其评分逻辑、状态读取方式、检查组件及分数汇总方式。\",\n \"confidence\": 0.0\n}\n\n这个 JSON 是合法的。 {\"task_id\":null,\"domain\":null,\"summary\":\"未提供 reward.py 源码,无法分析评分逻辑\",\"is_placeholder\":true,\"data_sources\":[],\"scoring_components\":[],\"total_max_score\":1.0,\"score_aggregation\":\"无法确定\",\"failure_modes\":[\"未提供源码,无法识别任何失败路径\"],\"scoring_logic_explanation\":\"输入中未包含 reward.py 的源码内容,因此无法依据源码分析其评分逻辑、状态读取方式、检查组件及分数汇总方式。\",\"confidence\":0.0}" +} diff --git a/legacy/ar_collections_001/_cua_gym_vm_bridge.sh b/legacy/ar_collections_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/ar_collections_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://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/ar_collections_001/initial_setup.py b/legacy/ar_collections_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..189067b90efdb323101149f87f4141b1ef00f186 --- /dev/null +++ b/legacy/ar_collections_001/initial_setup.py @@ -0,0 +1,186 @@ +""" +Initial Setup: AR collections check (PRE-task state) +Task ID: ar_collections_001 +Domain: libreoffice_calc (HYBRID: local ledger + gmail_mock + slack_mock) + +Pre-task state: + - Ledger /home/user/ar_collections_001.xlsx with INV-1031 & INV-1037 status='Sent' + - Gmail: realistic inbox, NO dunning emails to the two AP contacts + - Slack #collections: prior chatter only, NO overdue roundup +Launches LibreOffice Calc + Chrome (gmail, slack). +""" + +import os +import shlex +import subprocess +import time +import uuid + +import openpyxl +import requests + +WORKDIR = '/home/user' +TASK_ID = 'ar_collections_001' +OUTPUT = f'{WORKDIR}/{TASK_ID}.xlsx' + +GMAIL_URL = 'http://28.7.186.212:8158' +SLACK_URL = 'http://28.7.186.212:8198' + +HEADERS = ['Invoice #', 'Customer', 'Deal/Contract', 'Amount', + 'Issue Date', 'Due Date', 'Status', 'AE/Owner'] + +# Today = 2026-06-24. Overdue = Due Date < today AND Status != 'Paid'. +# INV-1031 and INV-1037 are 'Sent' here (NOT yet flipped to Overdue). +LEDGER_ROWS = [ + ['INV-1029', 'Initech', 'Enterprise License Renewal', 9800, '2026-04-15', '2026-05-15', 'Paid', 'Sarah Chen'], + ['INV-1030', 'Hooli', 'Cloud Platform Q2', 31200, '2026-04-20', '2026-05-20', 'Paid', 'Marcus Johnson'], + ['INV-1031', 'Vandelay Industries', 'Latex Supply Contract', 15000, '2026-04-30', '2026-05-30', 'Sent', 'Priya Patel'], + ['INV-1032', 'Pied Piper', 'Compression SDK', 8400, '2026-05-05', '2026-06-30', 'Sent', 'Sarah Chen'], + ['INV-1033', 'Stark Industries', 'Arc Reactor Maintenance', 47500, '2026-05-10', '2026-07-10', 'Sent', 'David Kim'], + ['INV-1034', 'Wayne Enterprises', 'Security Audit', 12750, '2026-05-12', '2026-06-12', 'Paid', 'Marcus Johnson'], + ['INV-1035', 'Soylent Corp', 'Nutrition Analytics', 6300, '2026-05-18', '2026-07-01', 'Sent', 'Priya Patel'], + ['INV-1036', 'Globex Corporation', 'ERP Integration', 28900, '2026-05-22', '2026-06-22', 'Paid', 'David Kim'], + ['INV-1037', 'Wernham Hogg', 'Paper Supply Agreement', 22400, '2026-05-06', '2026-06-05', 'Sent', 'Sarah Chen'], + ['INV-1038', 'Cyberdyne Systems', 'AI Platform License', 54000, '2026-06-01', '2026-07-15', 'Sent', 'David Kim'], +] + + +def build_ledger(path, overdue_status='Sent'): + """Build the AR Invoice Ledger. overdue_status applied to INV-1031 & INV-1037.""" + wb = openpyxl.Workbook() + ws = wb.active + ws.title = 'AR Invoice Ledger' + for col, h in enumerate(HEADERS, 1): + ws.cell(row=1, column=col, value=h) + for r, row in enumerate(LEDGER_ROWS, 2): + out = list(row) + if out[0] in ('INV-1031', 'INV-1037'): + out[6] = overdue_status # column G = Status + for c, val in enumerate(out, 1): + ws.cell(row=r, column=c, value=val) + wb.save(path) + + +def gmail_state(): + return { + 'user': {'userId': 'u1', 'username': 'Dana Reyes', 'email': 'collections@northwind-saas.com'}, + 'emails': [ + { + 'id': 'email_1', 'threadId': 'thread_1', + 'from': {'name': 'Accounts Payable', 'email': 'ap@globex.com'}, + 'to': [{'name': 'Dana Reyes', 'email': 'collections@northwind-saas.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Remittance advice — INV-1036 paid', + 'body': '

Hi Dana, payment for INV-1036 ($28,900) has been processed. Reference GX-55812.

', + 'timestamp': '2026-06-21T09:14:00Z', + 'read': True, 'starred': False, 'important': False, + 'labels': ['l4'], 'category': 'primary', 'folder': 'inbox', 'attachments': [] + }, + { + 'id': 'email_2', 'threadId': 'thread_2', + 'from': {'name': 'Marcus Johnson', 'email': 'marcus.johnson@northwind-saas.com'}, + 'to': [{'name': 'Dana Reyes', 'email': 'collections@northwind-saas.com'}], + 'cc': [], 'bcc': [], + 'subject': 'AR aging — please run the weekly check', + 'body': '

Dana, can you run the collections pass on the AR Invoice Ledger today? Thanks.

', + 'timestamp': '2026-06-24T07:40:00Z', + 'read': False, 'starred': True, 'important': True, + 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox', 'attachments': [] + }, + { + 'id': 'email_3', 'threadId': 'thread_3', + 'from': {'name': 'Initech AP', 'email': 'ap@initech.com'}, + 'to': [{'name': 'Dana Reyes', 'email': 'collections@northwind-saas.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Payment confirmation INV-1029', + 'body': '

Confirming wire transfer for INV-1029 ($9,800). Thank you.

', + 'timestamp': '2026-06-18T15:02:00Z', + 'read': True, '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'}, + ], + 'drafts': [], + } + + +def slack_state(): + users = [ + {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana', 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Collections Lead', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_2', 'fullName': 'Marcus Johnson', 'displayName': 'Marcus', 'email': 'marcus.johnson@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'AR Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Sarah Chen', 'displayName': 'Sarah', 'email': 'sarah.chen@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Account Executive', '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'], 'createdBy': 'user_2', 'createdAt': '2026-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'], 'createdBy': 'user_2', 'createdAt': '2026-01-05T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'collections', 'name': 'collections', 'description': 'AR collections coordination', 'topic': 'Overdue invoices & dunning', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_2', 'createdAt': '2026-02-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ] + messages = { + 'general': [ + {'messageId': 'msg_g1', 'senderId': 'user_2', 'content': 'Morning all — month-end AR review is this week.', 'timestamp': '2026-06-23T13:30:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'random': [ + {'messageId': 'msg_r1', 'senderId': 'user_3', 'content': 'Coffee machine on 4 is fixed 🎉', 'timestamp': '2026-06-22T16:05:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'collections': [ + {'messageId': 'msg_c1', 'senderId': 'user_2', 'content': 'Reminder: run the weekly collections pass on the AR Invoice Ledger and post the roundup here.', 'timestamp': '2026-06-24T07:45:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_c2', 'senderId': 'user_1', 'content': 'On it — pulling the ledger now.', 'timestamp': '2026-06-24T08:02:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + } + return { + 'currentUser': users[0], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind SaaS', '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(): + # --- sid (shared between gmail + slack on THIS vm) --- + sid = str(uuid.uuid4()) + with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + # --- Ledger (INV-1031 & INV-1037 = 'Sent') --- + build_ledger(OUTPUT, overdue_status='Sent') + print(f'Initial ledger created: {OUTPUT}') + + # --- Inject mock state (action: set => initial_state == current_state) --- + for name, url, state in [('gmail', GMAIL_URL, gmail_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 None' + print(f'{name} state injected: sid={sid}') + + # --- GUI-ready startup --- + launch_gui(f'libreoffice --calc "{OUTPUT}"', delay_sec=3.0) + launch_gui(f'google-chrome "{GMAIL_URL}/?sid={sid}"', delay_sec=2.0) + launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=2.0) + print('GUI_READY: launched LibreOffice Calc + Chrome (gmail, slack) with DISPLAY=:0') + + +main() diff --git a/legacy/ar_collections_001/reward.py b/legacy/ar_collections_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1f423f9f3bb474a5f20aff350c5fef2163706aed --- /dev/null +++ b/legacy/ar_collections_001/reward.py @@ -0,0 +1,206 @@ +""" +Reward Script: AR collections check — flip overdue invoices, send dunning emails, post Slack roundup +Task ID: ar_collections_001 +Domain: libreoffice_calc + mock_websites (HYBRID: local xlsx ledger -> Gmail -> Slack) + +Scoring (all deterministic; each component scores a task-introduced change so initial_env == 0.0): + LOCAL LEDGER (0.40): + C1 (0.15): INV-1031 Status == 'Overdue' + C2 (0.15): INV-1037 Status == 'Overdue' + C3 (0.10): C1 & C2 hold AND exactly those two rows are 'Overdue' (no other row flipped) + GMAIL (0.30): + C4 (0.15): NEW sent email to ap@vandelay.com referencing INV-1031 and $15,000 + C5 (0.15): NEW sent email to billing@wernham-hogg.com referencing INV-1037 and $22,400 + SLACK (0.30): + C6 (0.15): NEW #collections message (delta) mentioning 'overdue' and total 37400 + C7 (0.15): that NEW roundup states a count of 2 overdue invoices +""" +import os +import re +import sys + +import requests + +LEDGER_PATH = '/home/user/ar_collections_001.xlsx' +SHEET_NAME = 'AR Invoice Ledger' +GMAIL_URL = 'http://28.7.186.212:8158' +SLACK_URL = 'http://28.7.186.212:8198' + + +def _norm_amount(text): + """Strip $ and thousands separators so '15,000' / '$15,000.00' / '15000' all match '15000'.""" + return re.sub(r'[,$\s]', '', text or '') + + +def fetch_mock(base_url, sid): + """Return (initial_state, current_state) dicts, or (None, None) on failure.""" + try: + d = requests.get(f'{base_url}/go?sid={sid}', timeout=20).json() + return d.get('initial_state') or {}, d.get('current_state') or {} + except Exception as e: + print(f'ERROR: cannot fetch {base_url}: {e}') + return None, None + + +def verify_task(): + total = 0.0 + + # ---- read sid (shared across mocks on this VM) ---- + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('empty sid') + except Exception as e: + print(f'CRITICAL: cannot read /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + return 0.0 + + # ========================================================= + # LOCAL LEDGER (0.40) + # ========================================================= + rows = {} # invoice# -> status + try: + import openpyxl + wb = openpyxl.load_workbook(LEDGER_PATH, data_only=True) + ws = wb[SHEET_NAME] + for r in ws.iter_rows(min_row=2, values_only=True): + if r and r[0]: + rows[str(r[0]).strip()] = (str(r[6]).strip() if r[6] is not None else '') + print(f'Ledger rows loaded: {len(rows)}') + except Exception as e: + print(f'ERROR: cannot load ledger {LEDGER_PATH}: {e}') + + # C1 (0.15): INV-1031 -> Overdue + try: + if rows.get('INV-1031', '').lower() == 'overdue': + print('PASS C1: INV-1031 Status == Overdue (0.15)') + total += 0.15 + else: + print(f"FAIL C1: INV-1031 Status == {rows.get('INV-1031')!r}, expected 'Overdue'") + except Exception as e: + print(f'ERROR C1: {e}') + + # C2 (0.15): INV-1037 -> Overdue + try: + if rows.get('INV-1037', '').lower() == 'overdue': + print('PASS C2: INV-1037 Status == Overdue (0.15)') + total += 0.15 + else: + print(f"FAIL C2: INV-1037 Status == {rows.get('INV-1037')!r}, expected 'Overdue'") + except Exception as e: + print(f'ERROR C2: {e}') + + # C3 (0.10): exactly INV-1031 & INV-1037 are Overdue, no other row flipped. + # Compound-anchored to the change so it FAILS on initial_env (0 overdue rows). + try: + overdue = {inv for inv, st in rows.items() if st.lower() == 'overdue'} + if overdue == {'INV-1031', 'INV-1037'}: + print('PASS C3: exactly INV-1031 & INV-1037 are Overdue, no other row changed (0.10)') + total += 0.10 + else: + print(f'FAIL C3: Overdue set == {sorted(overdue)}, expected exactly INV-1031 & INV-1037') + except Exception as e: + print(f'ERROR C3: {e}') + + # ========================================================= + # GMAIL (0.30) — score only NEW sent emails (delta vs initial) + # ========================================================= + g_ini, g_cur = fetch_mock(GMAIL_URL, sid) + new_sent = [] + if g_cur is not None: + try: + ini_ids = {e.get('id') for e in g_ini.get('emails', [])} + for e in g_cur.get('emails', []): + if e.get('folder') == 'sent' and e.get('id') not in ini_ids: + new_sent.append(e) + print(f'New sent emails (delta): {len(new_sent)}') + except Exception as e: + print(f'ERROR gmail delta: {e}') + + def sent_matches(recipient, inv, amount): + for e in new_sent: + tos = [r.get('email', '').lower() for r in (e.get('to') or [])] + if recipient.lower() not in tos: + continue + blob = (e.get('subject', '') or '') + ' ' + (e.get('body', '') or '') + if inv.lower() in blob.lower() and amount in _norm_amount(blob): + return True + return False + + # C4 (0.15): dunning email to Vandelay (INV-1031, $15,000) + try: + if sent_matches('ap@vandelay.com', 'INV-1031', '15000'): + print('PASS C4: dunning email sent to ap@vandelay.com (INV-1031, $15,000) (0.15)') + total += 0.15 + else: + print('FAIL C4: no NEW sent email to ap@vandelay.com referencing INV-1031 + $15,000') + except Exception as e: + print(f'ERROR C4: {e}') + + # C5 (0.15): dunning email to Wernham Hogg (INV-1037, $22,400) + try: + if sent_matches('billing@wernham-hogg.com', 'INV-1037', '22400'): + print('PASS C5: dunning email sent to billing@wernham-hogg.com (INV-1037, $22,400) (0.15)') + total += 0.15 + else: + print('FAIL C5: no NEW sent email to billing@wernham-hogg.com referencing INV-1037 + $22,400') + except Exception as e: + print(f'ERROR C5: {e}') + + # ========================================================= + # SLACK (0.30) — score only NEW #collections messages (delta vs initial) + # ========================================================= + s_ini, s_cur = fetch_mock(SLACK_URL, sid) + new_msgs = [] + if s_cur is not None: + try: + ini_msgs = (s_ini.get('messages', {}) or {}).get('collections', []) or [] + cur_msgs = (s_cur.get('messages', {}) or {}).get('collections', []) or [] + ini_mids = {m.get('messageId') for m in ini_msgs} + for m in cur_msgs: + if m.get('messageId') not in ini_mids: + new_msgs.append(m) + print(f'New #collections messages (delta): {len(new_msgs)}') + except Exception as e: + print(f'ERROR slack delta: {e}') + + # C6 (0.15): a NEW roundup message mentions overdue + total outstanding 37400 + roundup = None + try: + for m in new_msgs: + c = m.get('content', '') or '' + if 'overdue' in c.lower() and '37400' in _norm_amount(c): + roundup = m + break + if roundup is not None: + print('PASS C6: NEW #collections roundup mentions overdue + total $37,400 (0.15)') + total += 0.15 + else: + print('FAIL C6: no NEW #collections message mentioning overdue + total 37400') + except Exception as e: + print(f'ERROR C6: {e}') + + # C7 (0.15): the roundup states a count of 2 overdue invoices + try: + ok = False + if roundup is not None: + c = roundup.get('content', '') or '' + cl = c.lower() + # count of 2 stated explicitly, or both invoice numbers enumerated + ok = bool(re.search(r'\b2\b', c)) or ('inv-1031' in cl and 'inv-1037' in cl) + if ok: + print('PASS C7: roundup states 2 invoices overdue (0.15)') + total += 0.15 + else: + print('FAIL C7: roundup does not state a count of 2 overdue invoices') + except Exception as e: + print(f'ERROR C7: {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/legacy/ar_collections_001/reward_label.json b/legacy/ar_collections_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..05e67b6632e80419e8e690996028ccd7a08868ad --- /dev/null +++ b/legacy/ar_collections_001/reward_label.json @@ -0,0 +1,84 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_collections_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:19", + "label": { + "task_id": "ar_collections_001", + "domain": "libreoffice_calc + mock_websites", + "summary": "验证用户是否将本地账本中指定发票状态改为Overdue,并通过Gmail发送两封催款邮件,同时在Slack #collections频道发布包含逾期总额和数量的汇总消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "/home/user/ar_collections_001.xlsx", + "Gmail mock服务 (http://28.7.186.212:8158)", + "Slack mock服务 (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "C1", + "weight": 0.15, + "description": "检查本地Excel账本中INV-1031的状态是否被标记为Overdue", + "check_logic": "使用openpyxl加载LEDGER_PATH指定的工作表'SAR Invoice Ledger',遍历所有行构建字典rows(invoice# -> status),检查rows.get('INV-1031', '').lower() == 'overdue'", + "pass_condition": "INV-1031对应的状态字符串去除首尾空格并转小写后等于'overdue'" + }, + { + "name": "C2", + "weight": 0.15, + "description": "检查本地Excel账本中INV-1037的状态是否被标记为Overdue", + "check_logic": "检查rows.get('INV-1037', '').lower() == 'overdue'", + "pass_condition": "INV-1037对应的状态字符串去除首尾空格并转小写后等于'overdue'" + }, + { + "name": "C3", + "weight": 0.1, + "description": "检查账本中是否仅有INV-1031和INV-1037两行被标记为Overdue,没有其他行被意外修改", + "check_logic": "遍历rows中所有状态转小写等于'overdue'的发票号构成集合overdue,检查overdue == {'INV-1031', 'INV-1037'}", + "pass_condition": "逾期发票集合恰好等于{'INV-1031', 'INV-1037'},不多不少" + }, + { + "name": "C4", + "weight": 0.15, + "description": "检查是否通过Gmail向ap@vandelay.com发送了关于INV-1031和$15,000的新催款邮件", + "check_logic": "调用fetch_mock获取Gmail的initial_state与current_state,筛选folder为'sent'且id不在初始邮件集合中的new_sent邮件;在new_sent中查找收件人包含'ap@vandelay.com',且subject与body拼接后的文本同时包含'INV-1031'和经_norm_amount处理后的金额'15000'的邮件", + "pass_condition": "存在至少一封新的sent邮件,收件人包含ap@vandelay.com,且主题或正文同时引用INV-1031和金额15000" + }, + { + "name": "C5", + "weight": 0.15, + "description": "检查是否通过Gmail向billing@wernham-hogg.com发送了关于INV-1037和$22,400的新催款邮件", + "check_logic": "与C4类似,在new_sent中查找收件人包含'billing@wernham-hogg.com',且主题或正文同时包含'INV-1037'和经_norm_amount处理后的金额'22400'的邮件", + "pass_condition": "存在至少一封新的sent邮件,收件人包含billing@wernham-hogg.com,且主题或正文同时引用INV-1037和金额22400" + }, + { + "name": "C6", + "weight": 0.15, + "description": "检查Slack #collections频道是否有新消息提到overdue和总逾期金额37400", + "check_logic": "调用fetch_mock获取Slack的initial_state与current_state,提取#collections频道中messageId不在初始消息集合中的new_msgs;遍历new_msgs,检查消息内容转小写后包含'overdue'且经_norm_amount处理后包含'37400'", + "pass_condition": "存在至少一条新的#collections消息,其内容同时包含'overdue'和金额37400" + }, + { + "name": "C7", + "weight": 0.15, + "description": "检查C6中找到的汇总消息是否明确说明有2张逾期发票", + "check_logic": "在C6命中的roundup消息内容中,使用正则\\b2\\b查找显式数字2,或检查内容转小写后同时包含'inv-1031'和'inv-1037'", + "pass_condition": "roundup消息内容中显式出现数字2,或同时提及inv-1031与inv-1037" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加求和,最终通过round(min(total, 1.0), 4)将总分钳制在1.0以内并四舍五入保留4位小数", + "failure_modes": [ + "读取/tmp/task_web_sid失败或内容为空:打印CRITICAL并直接返回0.0", + "加载本地Excel账本失败:打印ERROR,对应行状态为空导致C1-C3失败", + "fetch_mock请求Gmail或Slack失败:返回(None, None),对应模块无法计算delta而失败", + "Gmail中无新的sent邮件:C4、C5失败", + "Slack #collections中无新消息:C6、C7失败", + "C6未找到roundup消息:C7因roundup为None而失败", + "任一组件检查过程中抛出异常:捕获后打印ERROR,该组件不得分但不中断后续检查" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接返回0.0。接着加载本地Excel账本/home/user/ar_collections_001.xlsx,提取所有发票号与状态,依次检查C1(INV-1031为Overdue)、C2(INV-1037为Overdue)和C3(仅有这两行是Overdue)。随后通过sid请求mock Gmail服务,对比初始状态与当前状态,筛选出新的sent邮件,检查C4(发给ap@vandelay.com并引用INV-1031和15000)和C5(发给billing@wernham-hogg.com并引用INV-1037和22400)。再请求mock Slack服务,对比#collections频道消息,筛选出新消息,检查C6(内容包含overdue和37400)和C7(该消息中明确说明数量为2,或同时提及两张发票号)。所有通过的组件分值累加到total,最后以min(total, 1.0)钳制上限并四舍五入到4位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 中提取:`ar_collections_001`\n2. **Domain**: 从 docstring 中提取:`libreoffice_calc + mock_websites (HYBRID: local xlsx ledger -> Gmail -> Slack)`,简化可以是 `libreoffice_calc` 或 `mock_websites`。根据要求\"如 libreoffice_calc\",我填 `libreoffice_calc + mock_websites` 或按格式要求。看示例有 `libreoffice_calc`,这里 docstring 明确写了 HYBRID,我可以写 `libreoffice_calc + mock_websites` 或者就按 docstring 的 `libreoffice_calc + mock_websites (HYBRID)`。但示例格式是单个值。我填 `libreoffice_calc + mock_websites` 应该可以,或者更准确地提取。再看要求:\"从 docstring 中提取的领域,如 mock_websites / software_engineer / libreoffice_calc\"。这里 docstring 写的是 `libreoffice_calc + mock_websites (HYBRID: local xlsx ledger -> Gmail -> Slack)`。我填 `libreoffice_calc + mock_websites` 比较准确。\n\n3. **Summary**: 一句话概括。这个脚本验证:将本地 Excel 账本中特定发票状态改为逾期,通过 Gmail 发送催款邮件,并在 Slack #collections 频道发布汇总消息。\n\n4. **is_placeholder**: false。这个脚本有详细的检查逻辑,不是占位脚本。\n\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `GMAIL_URL` (http://28.7.186.212:8158) - mock Gmail 服务\n - `SLACK_URL` (http://28.7.186.212:8198) - mock Slack 服务\n - `LEDGER_PATH` (`/home/user/ar_collections_001.xlsx`) - 本地 Excel 文件\n\n6. **scoring_components**: 有 7 个组件,分值在 docstring 和代码中都有。\n\n - C1: 0.15, 检查 INV-1031 状态是否为 Overdue\n - C2: 0.15, 检查 INV-1037 状态是否为 Overdue\n - C3: 0.10, 检查是否只有 INV-1031 和 INV-1037 是 Overdue,没有其他行被修改\n - C4: 0.15, 检查是否有新的发送给 ap@vandelay.com 的邮件,引用 INV-1031 和 $15,000\n - C5: 0.15, 检查是否有新的发送给 billing@wernham-hogg.com 的邮件,引用 INV-1037 和 $22,400\n - C6: 0.15, 检查 Slack #collections 是否有新消息提到 overdue 和总额 37400\n - C7: 0.15, 检查该汇总消息是否说明有 2 张逾期发票\n\n 每个组件的 check_logic 和 pass_condition 需要详细描述。\n\n7. **total_max_score**: 1.0\n\n8. **score_aggregation**: 各组件分数相加,最后用 `min(total, 1.0)` 钳制到上限 1.0。\n\n9. **failure_modes**:\n - 读取 `/tmp/task_web_sid` 失败或为空:打印 CRITICAL 并返回 0.0\n - 加载本地账本失败:打印 ERROR,但该部分继续检查(只是 rows 为空会导致失败)\n - fetch_mock 失败(Gmail 或 Slack):返回 (None, None),对应部分无法得分\n - 没有新的 sent email 或新的 Slack 消息:对应组件失败\n - 任何异常被捕获:打印 ERROR Cx,该组件不得分\n\n10. **scoring_logic_explanation**: 按执行顺序:\n - 首先读取 `/tmp/task_web_sid` 获取会话 ID,失败则直接返回 0.0。\n - 然后加载本地 Excel 账本 `/home/user/ar_collections_001.xlsx`,读取所有行并提取发票号和状态。\n - 检查 C1 和 C2:确认 INV-1031 和 INV-1037 的状态是否为 \"Overdue\"。\n - 检查 C3:确认整个账本中只有这两行是 Overdue,没有其他行被意外修改。\n - 接着通过 sid 请求 mock Gmail 服务,获取初始状态和当前状态,计算 delta(新发送的邮件)。\n - 检查 C4 和 C5:在新发送的邮件中查找是否包含发给特定收件人、引用特定发票号和金额的催款邮件。\n - 然后请求 mock Slack 服务,获取 #collections 频道的初始和当前消息,计算 delta(新消息)。\n - 检查 C6:在新消息中查找是否提到 \"overdue\" 和总金额 \"37400\"。\n - 检查 C7:在 C6 找到的消息中,进一步确认是否明确说明了 2 张逾期发票(通过数字 2 或同时提到两张发票号)。\n - 所有通过检查的组件分值累加到 total,最后 `min(total, 1.0)` 并四舍五入到 4 位小数返回。\n\n11. **confidence**: 1.0。代码逻辑非常清晰。\n\n现在构建 JSON。注意:\n- 不要输出 Markdown 代码块\n- 第一个字符是 `{`,最后一个字符是 `}`\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- weight 填代码中显式给出的分值\n\n让我确认每个组件的描述:\n\nC1:\n- name: \"C1\"\n- weight: 0.15\n- description: \"检查本地账本中 INV-1031 的状态是否被标记为 Overdue\"\n- check_logic: \"读取 /home/user/ar_collections_001.xlsx 的 'AR Invoice Ledger' 工作表,构建 rows 字典(invoice# -> status),检查 rows.get('INV-1031', '').lower() == 'overdue'\"\n- pass_condition: \"INV-1031 对应的状态字符串(去除首尾空格后转小写)等于 'overdue'\"\n\nC2:\n- name: \"C2\"\n- weight: 0.15\n- description: \"检查本地账本中 INV-1037 的状态是否被标记为 Overdue\"\n- check_logic: \"检查 rows.get('INV-1037', '').lower() == 'overdue'\"\n- pass_condition: \"INV-1037 对应的状态字符串(去除首尾空格后转小写)等于 'overdue'\"\n\nC3:\n- name: \"C3\"\n- weight: 0.10\n- description: \"检查账本中是否仅有 INV-1031 和 INV-1037 两行被标记为 Overdue,无其他行被修改\"\n- check_logic: \"遍历 rows 中所有状态为 'overdue'(不区分大小写)的发票号,构成集合 overdue,检查 overdue == {'INV-1031', 'INV-1037'}\"\n- pass_condition: \"逾期发票集合恰好等于 {'INV-1031', 'INV-1037'},不多不少\"\n\nC4:\n- name: \"C4\"\n- weight: 0.15\n- description: \"检查是否通过 Gmail 向 ap@vandelay.com 发送了关于 INV-1031 和 $15,000 的新催款邮件\"\n- check_logic: \"调用 fetch_mock 获取 Gmail 的 initial_state 和 current_state,筛选 folder 为 'sent' 且 id 不在初始邮件集合中的 new_sent 邮件;在 new_sent 中查找收件人包含 'ap@vandelay.com'、且主题或正文中同时包含 'INV-1031' 和金额 '15000'(经 _norm_amount 去除 $ 和逗号后匹配)的邮件\"\n- pass_condition: \"存在至少一封新的 sent 邮件,收件人包含 ap@vandelay.com,且主题或正文同时引用 INV-1031 和金额 15000\"\n\nC5:\n- name: \"C5\"\n- weight: 0.15\n- description: \"检查是否通过 Gmail 向 billing@wernham-hogg.com 发送了关于 INV-1037 和 $22,400 的新催款邮件\"\n- check_logic: \"与 C4 类似,在 new_sent 中查找收件人包含 'billing@wernham-hogg.com'、且主题或正文同时包含 'INV-1037' 和金额 '22400' 的邮件\"\n- pass_condition: \"存在至少一封新的 sent 邮件,收件人包含 billing@wernham-hogg.com,且主题或正文同时引用 INV-1037 和金额 22400\"\n\nC6:\n- name: \"C6\"\n- weight: 0.15\n- description: \"检查 Slack #collections 频道是否有新消息提到 overdue 和总逾期金额 37400\"\n- check_logic: \"调用 fetch_mock 获取 Slack 的 initial_state 和 current_state,提取 #collections 频道中 messageId 不在初始消息集合中的 new_msgs;遍历 new_msgs,检查消息内容(转小写后)包含 'overdue' 且经 _norm_amount 处理后包含 '37400'\"\n- pass_condition: \"存在至少一条新的 #collections 消息,其内容同时包含 'overdue' 和金额 37400\"\n\nC7:\n- name: \"C7\"\n- weight: 0.15\n- description: \"检查 C6 中找到的汇总消息是否明确说明有 2 张逾期发票\"\n- check_logic: \"在 C6 命中的 roundup 消息内容中,检查是否包含数字 2(正则 \\b2\\b)或同时包含 'inv-1031' 和 'inv-1037'(均转小写)\"\n- pass_condition: \"roundup 消息内容中显式出现数字 2,或同时提及 inv-1031 与 inv-1037\"\n\nscore_aggregation: \"各组件分数累加求和,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0 并四舍五入保留 4 位小数\"\n\nfailure_modes:\n- \"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并直接返回 0.0\"\n- \"加载本地 Excel 账本失败:打印 ERROR,对应行状态为空导致 C1-C3 失败\"\n- \"fetch_mock 请求 Gmail 或 Slack 失败:返回 (None, None),对应模块无法计算 delta 而失败\"\n- \"Gmail 中无新的 sent 邮件:C4、C5 失败\"\n- \"Slack #collections 中无新消息:C6、C7 失败\"\n- \"C6 未找到 roundup 消息:C7 因 roundup 为 None 而失败\"\n- \"任一组件检查过程中抛出异常:捕获后打印 ERROR,该组件不得分但不中断后续检查\"\n\ndomain 的提取:docstring 中明确写了 `Domain: libreoffice_calc + mock_websites (HYBRID: local xlsx ledger -> Gmail -> Slack)`。我应该保留主要部分。可以写 `libreoffice_calc + mock_websites`。如果必须选一个,但这里明确是混合。我就按原文提取。\n\ndata_sources:\n- \"/tmp/task_web_sid\"\n- \"/home/user/ar_collections_001.xlsx\"\n- \"Gmail mock 服务 (http://28.7.186.212:8158)\"\n- \"Slack mock 服务 (http://28.7.186.212:8198)\"\n\n现在组织 JSON。确保没有多余文字,纯 JSON。\n\n检查 JSON 格式:所有字符串用双引号,中文内容,无 trailing comma。\n\n让我再仔细检查一下代码中的细节:\n\n- `_norm_amount` 用于金额标准化,移除 `$`, `,`, 空格。\n- `fetch_mock` 使用 `/go?sid={sid}` 端点。\n- Gmail delta: `e.get('folder') == 'sent'` 且 id 不在 `ini_ids`。\n- Slack delta: 比较 `messages.collections` 列表中的 `messageId`。\n- C7 依赖 C6 找到的 `roundup` 变量。如果 C6 失败,C7 也会失败。\n\n这些细节都要在 explanation 中体现。\n\n最终确认 JSON 结构正确。 {\"task_id\":\"ar_collections_001\",\"domain\":\"libreoffice_calc + mock_websites\",\"summary\":\"验证用户是否将本地账本中指定发票状态改为Overdue,并通过Gmail发送两封催款邮件,同时在Slack #collections频道发布包含逾期总额和数量的汇总消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"/home/user/ar_collections_001.xlsx\",\"Gmail mock服务 (http://28.7.186.212:8158)\",\"Slack mock服务 (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"C1\",\"weight\":0.15,\"description\":\"检查本地Excel账本中INV-1031的状态是否被标记为Overdue\",\"check_logic\":\"使用openpyxl加载LEDGER_PATH指定的工作表'SAR Invoice Ledger',遍历所有行构建字典rows(invoice# -> status),检查rows.get('INV-1031', '').lower() == 'overdue'\",\"pass_condition\":\"INV-1031对应的状态字符串去除首尾空格并转小写后等于'overdue'\"},{\"name\":\"C2\",\"weight\":0.15,\"description\":\"检查本地Excel账本中INV-1037的状态是否被标记为Overdue\",\"check_logic\":\"检查rows.get('INV-1037', '').lower() == 'overdue'\",\"pass_condition\":\"INV-1037对应的状态字符串去除首尾空格并转小写后等于'overdue'\"},{\"name\":\"C3\",\"weight\":0.10,\"description\":\"检查账本中是否仅有INV-1031和INV-1037两行被标记为Overdue,没有其他行被意外修改\",\"check_logic\":\"遍历rows中所有状态转小写等于'overdue'的发票号构成集合overdue,检查overdue == {'INV-1031', 'INV-1037'}\",\"pass_condition\":\"逾期发票集合恰好等于{'INV-1031', 'INV-1037'},不多不少\"},{\"name\":\"C4\",\"weight\":0.15,\"description\":\"检查是否通过Gmail向ap@vandelay.com发送了关于INV-1031和$15,000的新催款邮件\",\"check_logic\":\"调用fetch_mock获取Gmail的initial_state与current_state,筛选folder为'sent'且id不在初始邮件集合中的new_sent邮件;在new_sent中查找收件人包含'ap@vandelay.com',且subject与body拼接后的文本同时包含'INV-1031'和经_norm_amount处理后的金额'15000'的邮件\",\"pass_condition\":\"存在至少一封新的sent邮件,收件人包含ap@vandelay.com,且主题或正文同时引用INV-1031和金额15000\"},{\"name\":\"C5\",\"weight\":0.15,\"description\":\"检查是否通过Gmail向billing@wernham-hogg.com发送了关于INV-1037和$22,400的新催款邮件\",\"check_logic\":\"与C4类似,在new_sent中查找收件人包含'billing@wernham-hogg.com',且主题或正文同时包含'INV-1037'和经_norm_amount处理后的金额'22400'的邮件\",\"pass_condition\":\"存在至少一封新的sent邮件,收件人包含billing@wernham-hogg.com,且主题或正文同时引用INV-1037和金额22400\"},{\"name\":\"C6\",\"weight\":0.15,\"description\":\"检查Slack #collections频道是否有新消息提到overdue和总逾期金额37400\",\"check_logic\":\"调用fetch_mock获取Slack的initial_state与current_state,提取#collections频道中messageId不在初始消息集合中的new_msgs;遍历new_msgs,检查消息内容转小写后包含'overdue'且经_norm_amount处理后包含'37400'\",\"pass_condition\":\"存在至少一条新的#collections消息,其内容同时包含'overdue'和金额37400\"},{\"name\":\"C7\",\"weight\":0.15,\"description\":\"检查C6中找到的汇总消息是否明确说明有2张逾期发票\",\"check_logic\":\"在C6命中的roundup消息内容中,使用正则\\\\b2\\\\b查找显式数字2,或检查内容转小写后同时包含'inv-1031'和'inv-1037'\",\"pass_condition\":\"roundup消息内容中显式出现数字2,或同时提及inv-1031与inv-1037\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终通过round(min(total, 1.0), 4)将总分钳制在1.0以内并四舍五入保留4位小数\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或内容为空:打印CRITICAL并直接返回0.0\",\"加载本地Excel账本失败:打印ERROR,对应行状态为空导致C1-C3失败\",\"fetch_mock请求Gmail或Slack失败:返回(None, None),对应模块无法计算delta而失败\",\"Gmail中无新的sent邮件:C4、C5失败\",\"Slack #collections中无新消息:C6、C7失败\",\"C6未找到roundup消息:C7因roundup为None而失败\",\"任一组件检查过程中抛出异常:捕获后打印ERROR,该组件不得分但不中断后续检查\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接返回0.0。接着加载本地Excel账本/home/user/ar_collections_001.xlsx,提取所有发票号与状态,依次检查C1(INV-1031为Overdue)、C2(INV-1037为Overdue)和C3(仅有这两行是Overdue)。随后通过sid请求mock Gmail服务,对比初始状态与当前状态,筛选出新的sent邮件,检查C4(发给ap@vandelay.com并引用INV-1031和15000)和C5(发给billing@wernham-hogg.com并引用INV-1037和22400)。再请求mock Slack服务,对比#collections频道消息,筛选出新消息,检查C6(内容包含overdue和37400)和C7(该消息中明确说明数量为2,或同时提及两张发票号)。所有通过的组件分值累加到total,最后以min(total, 1.0)钳制上限并四舍五入到4位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/_cua_gym_vm_bridge.sh b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/initial_setup.py b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..77cefc7868dc62f7cde5a7a24fcb9a4bcaf94dc1 --- /dev/null +++ b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/initial_setup.py @@ -0,0 +1,416 @@ +""" +Initial Setup: pmo_status_report_b104 +Task ID: beacea76-e300-578d-8dc9-5bf0f1a16d13 +Domain: mock_websites +Mocks: google_docs_mock, monday_mock, slack_mock, microsoft_teams_mock (single shared sid) + +Persona: You are an office worker acting as a project lead. Your tools for this task are: shared documents, the monday.com board, team communications, Microsoft Teams. + +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 'Weekly Status - June W3'; monday.com 'Product Roadmap' board with 3 items; Slack workspace with channels #general, #random; Microsoft Teams with Engineering/Design teams, channels, and 1:1 chats. GROUND TRUTH — the agent earns partial credit for each checkpoint: new weekly status doc (+0.2); report has Progress/Risks/Decisions (+0.25); Risks names the stuck item (User Research) (+0.2); slack_new_msg (+0.1); Teams post points to the report (+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 = { + "google_docs_mock": "http://28.7.186.212:8162", + "monday_mock": "http://28.7.186.212:8185", + "slack_mock": "http://28.7.186.212:8198", + "microsoft_teams_mock": "http://28.7.186.212:8182" +} +PRIMARY_URL = 'http://28.7.186.212:8162' + +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-old': { 'id': 'd-old', + 'title': 'Weekly Status - June W3', + 'content': '

last week

', + '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': ''}}, + 'monday_mock': { 'workspaces': [{'id': 'ws1', 'name': 'Main Workspace'}], + 'boards': [ { 'id': 'b1', + 'workspaceId': 'ws1', + 'name': 'Product Roadmap', + 'description': 'Q1 2024 Goals and Tasks', + 'columns': [ { 'id': 'c1', + 'title': 'Owner', + 'type': 'person', + 'width': 100}, + { 'id': 'c2', + 'title': 'Status', + 'type': 'status', + 'width': 140, + 'settings': { 'labels': [ { 'id': 's1', + 'label': 'Done', + 'color': '#00c875'}, + { 'id': 's2', + 'label': 'Working ' + 'on ' + 'it', + 'color': '#fdab3d'}, + { 'id': 's3', + 'label': 'Stuck', + 'color': '#e2445c'}, + { 'id': 's4', + 'label': 'Not ' + 'Started', + 'color': '#c4c4c4'}]}}, + { 'id': 'c3', + 'title': 'Due Date', + 'type': 'date', + 'width': 120}, + { 'id': 'c4', + 'title': 'Priority', + 'type': 'status', + 'width': 140, + 'settings': { 'labels': [ { 'id': 'p1', + 'label': 'High', + 'color': '#401694'}, + { 'id': 'p2', + 'label': 'Medium', + 'color': '#579bfc'}, + { 'id': 'p3', + 'label': 'Low', + 'color': '#79d5ea'}]}}, + { 'id': 'c5', + 'title': 'Timeline', + 'type': 'timeline', + 'width': 180}, + { 'id': 'c6', + 'title': 'Budget', + 'type': 'numbers', + 'width': 100, + 'settings': {'prefix': '$'}}], + 'groups': [ { 'id': 'g1', + 'title': 'Q1 Goals', + 'color': '#579bfc'}, + { 'id': 'g2', + 'title': 'Backlog', + 'color': '#a25ddc'}], + 'items': [ { 'id': 'i1', + 'groupId': 'g1', + 'name': 'Launch New Website', + 'columnValues': { 'c1': ['u1', 'u2'], + 'c2': 's2', + 'c3': '2024-03-15', + 'c4': 'p1', + 'c5': { 'start': '2024-03-01', + 'end': '2024-03-15'}, + 'c6': 5000}}, + { 'id': 'i2', + 'groupId': 'g1', + 'name': 'Mobile App Design', + 'columnValues': { 'c1': ['u3'], + 'c2': 's1', + 'c3': '2024-02-28', + 'c4': 'p2', + 'c5': { 'start': '2024-02-01', + 'end': '2024-02-28'}, + 'c6': 12000}}, + { 'id': 'i3', + 'groupId': 'g2', + 'name': 'User Research', + 'columnValues': { 'c1': ['u4'], + 'c2': 's3', + 'c3': '2024-04-10', + 'c4': 'p3', + 'c5': { 'start': '2024-04-01', + 'end': '2024-04-10'}, + 'c6': 2000}}], + 'updates': [], + 'activities': []}], + 'currentUser': { 'id': 'u1', + 'name': 'Admin User', + 'avatar': 'https://picsum.photos/100/100?random=u1'}}, + 'slack_mock': { 'currentUser': { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + 'workspace': { 'workspaceId': 'ws_1', + 'workspaceName': 'Acme Corp', + 'icon': ''}, + 'users': [ { 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_2', + 'fullName': 'Sarah Johnson', + 'displayName': 'Sarah', + 'email': 'sarah.johnson@company.com', + 'avatar': 'https://picsum.photos/200/200?random=2', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_3', + 'fullName': 'Mike Chen', + 'displayName': 'Mike', + 'email': 'mike.chen@company.com', + 'avatar': 'https://picsum.photos/200/200?random=3', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}, + { 'userId': 'user_4', + 'fullName': 'Lisa Park', + 'displayName': 'Lisa', + 'email': 'lisa.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=4', + 'title': '', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York'}], + 'channels': [ { 'channelId': 'general', + 'name': 'general', + 'description': 'general channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}, + { 'channelId': 'random', + 'name': 'random', + 'description': 'random channel', + 'topic': '', + 'isPrivate': False, + 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_4'], + 'createdBy': 'user_1', + 'createdAt': '2026-01-01T10:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0}], + 'messages': { 'general': [ { 'messageId': 'g1', + 'senderId': 'user_2', + 'content': 'is the weekly status out?', + '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': []}, + 'microsoft_teams_mock': { 'currentUser': { 'id': 'user-me', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://placehold.co/64x64/7c3aed/ffffff/png?text=M', + 'status': 'available', + 'statusMessage': ''}, + 'users': [ { 'id': 'user-me', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://placehold.co/64x64/7c3aed/ffffff/png?text=M', + 'status': 'available', + 'statusMessage': ''}, + { 'id': 'u1', + 'name': 'Alice Smith', + 'status': 'busy', + 'avatar': 'https://placehold.co/64x64/d97706/ffffff/png?text=U'}, + { 'id': 'u2', + 'name': 'Bob Jones', + 'status': 'away', + 'avatar': 'https://placehold.co/64x64/dc2626/ffffff/png?text=U'}, + { 'id': 'u3', + 'name': 'Charlie Day', + 'status': 'offline', + 'avatar': 'https://placehold.co/64x64/db2777/ffffff/png?text=U'}, + { 'id': 'u4', + 'name': 'Diana Prince', + 'status': 'available', + 'avatar': 'https://placehold.co/64x64/4338ca/ffffff/png?text=U'}], + 'teams': [ { 'id': 't1', + 'name': 'Engineering', + 'description': 'Engineering team collaboration', + 'channels': [ { 'id': 'c1', + 'name': 'General', + 'posts': [ { 'id': 'p1', + 'userId': 'u1', + 'subject': 'Welcome ' + 'to ' + 'the ' + 'team', + 'content': 'Hi ' + 'everyone! ' + 'Excited ' + 'to ' + 'be ' + 'here.', + 'timestamp': '2026-06-07T09:54:18.071Z', + 'replies': [ { 'id': 'r1', + 'userId': 'user-me', + 'content': 'Welcome ' + 'Alice!', + 'timestamp': '2026-06-07T11:40:58.071Z'}], + 'reactions': { '👍': 2}}]}, + { 'id': 'c2', + 'name': 'Frontend', + 'posts': []}, + { 'id': 'c3', + 'name': 'Deployments', + 'posts': []}]}, + { 'id': 't2', + 'name': 'Product Design', + 'description': 'Design team sync', + 'channels': [ { 'id': 'c4', + 'name': 'General', + 'posts': []}, + { 'id': 'c5', + 'name': 'Inspiration', + 'posts': []}]}], + 'chats': [ { 'id': 'chat1', + 'type': 'direct', + 'participants': ['user-me', 'u1'], + 'messages': [ { 'id': 'm1', + 'userId': 'u1', + 'content': 'Hey, do you have ' + 'a minute?', + 'timestamp': '2026-06-08T08:54:18.071Z'}, + { 'id': 'm2', + 'userId': 'user-me', + 'content': 'Sure, what is up?', + 'timestamp': '2026-06-08T08:55:58.071Z'}]}, + { 'id': 'chat2', + 'type': 'group', + 'name': 'Lunch Crew', + 'participants': ['user-me', 'u2', 'u3'], + 'messages': [ { 'id': 'm3', + 'userId': 'u2', + 'content': 'Tacos today?', + 'timestamp': '2026-06-08T07:54:18.071Z'}]}], + 'activity': [ { 'id': 'a1', + 'type': 'mention', + 'text': 'Alice mentioned you in Engineering > ' + 'General', + 'read': False, + 'timestamp': '2026-06-08T09:54:18.071Z', + 'link': '/teams/t1/c1'}, + { 'id': 'a2', + 'type': 'reaction', + 'text': 'Bob liked your message', + 'read': True, + 'timestamp': '2026-06-08T09:52:38.071Z', + 'link': '/chat/chat1'}], + 'calendar': [ { 'id': 'evt1', + 'title': 'Daily Standup', + 'start': 1780912800000, + 'end': 1780914600000, + 'attendees': ['u1', 'u2', 'u3']}], + 'files': [ { 'id': 'f1', + 'name': 'Q3_Roadmap.pdf', + 'type': 'pdf', + 'size': '2.4 MB', + 'date': '2023-10-24', + 'url': '/files/_default/Q3_Roadmap.pdf'}, + { 'id': 'f2', + 'name': 'Design_System_v2.fig', + 'type': 'fig', + 'size': '14 MB', + 'date': '2023-10-25', + 'url': '/files/_default/Design_System_v2.fig'}, + { 'id': 'f3', + 'name': 'Screenshot_Error.png', + 'type': 'png', + 'size': '1.1 MB', + 'date': '2023-10-26', + 'url': '/files/_default/Screenshot_Error.png'}], + 'calls': [], + 'activeCall': None}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward.py b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..380018ce023d2c4ef8fb2fff9e475d6cdd928e88 --- /dev/null +++ b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward.py @@ -0,0 +1,122 @@ +""" +Reward Script: pmo_status_report_b104 +Task ID: beacea76-e300-578d-8dc9-5bf0f1a16d13 +Domain: mock_websites +Mocks: google_docs_mock, monday_mock, slack_mock, microsoft_teams_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.2] new weekly status doc + - [0.25] report has Progress/Risks/Decisions + - [0.2] Risks names the stuck item (User Research) + - [0.1] slack_new_msg + - [0.25] Teams post points to the report +""" +import re +import sys + +import requests + +MOCK_URLS = { + "google_docs_mock": "http://28.7.186.212:8162", + "monday_mock": "http://28.7.186.212:8185", + "slack_mock": "http://28.7.186.212:8198", + "microsoft_teams_mock": "http://28.7.186.212:8182" +} +SEED = { + "slack_mock:general": [ + "g1" + ], + "slack_mock:random": [] +} + +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + +STATES = {} +for _name, _url in MOCK_URLS.items(): + try: + _r = requests.get(f'{_url}/go?sid={sid}', timeout=15) + _r.raise_for_status() + STATES[_name] = _r.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {_name}: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def cur(mock): + return (STATES.get(mock) or {}).get('current_state') or {} + + +def _lc(s): + return (s or '').lower() + + +total = 0.0 + +# c0: a new google doc titled about (new weekly status doc) +c0_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys()) +c0_docs = cur('google_docs_mock').get('documents') or {} +c0_new = [d for did, d in c0_docs.items() if did not in c0_init and any(t in _lc(d.get('title','')) for t in ['weekly status - june w4', 'weekly status'])] +if c0_new: + print('PASS: new weekly status doc (0.2)') + total += 0.2 +else: + print('FAIL: new weekly status doc') + +# c1: new google doc body (report has Progress/Risks/Decisions) +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 ['weekly status'])] +c1_txt = _lc(' '.join(d.get('content','') for d in c1_new)) +if c1_new and all(t in c1_txt for t in ['progress', 'risks', 'decisions']): + print('PASS: report has Progress/Risks/Decisions (0.25)') + total += 0.25 +else: + print('FAIL: report has Progress/Risks/Decisions') + +# c2: new google doc body (Risks names the stuck item (User Research)) +c2_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys()) +c2_docs = cur('google_docs_mock').get('documents') or {} +c2_new = [d for did, d in c2_docs.items() if did not in c2_init and any(t in _lc(d.get('title','')) for t in ['weekly status'])] +c2_txt = _lc(' '.join(d.get('content','') for d in c2_new)) +if c2_new and any(t in c2_txt for t in ['user research']): + print('PASS: Risks names the stuck item (User Research) (0.2)') + total += 0.2 +else: + print('FAIL: Risks names the stuck item (User Research)') + +# c3: new message by user_1 in #general +c3_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or [] +c3_seed = set(SEED.get('slack_mock:general', [])) +c3_new = [m for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1'] +c3_blob = _lc(' '.join((m.get('content') or '') for m in c3_new)) +if c3_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') + +# c4: new Teams post in channel 'c1' (Teams post points to the report) +c4_team = next((t for t in (cur('microsoft_teams_mock').get('teams') or []) if t.get('id') == 't1'), None) +c4_chan = next((ch for ch in ((c4_team or {}).get('channels') or []) if ch.get('id') == 'c1'), None) +c4_init_team = next((t for t in ((STATES['microsoft_teams_mock'].get('initial_state') or {}).get('teams') or []) if t.get('id') == 't1'), None) +c4_init_chan = next((ch for ch in ((c4_init_team or {}).get('channels') or []) if ch.get('id') == 'c1'), None) +c4_seed = {p.get('id') for p in ((c4_init_chan or {}).get('posts') or [])} +c4_new = [p for p in ((c4_chan or {}).get('posts') or []) if p.get('id') not in c4_seed and p.get('userId') == 'user-me'] +c4_txt = _lc(' '.join((p.get('subject','') + ' ' + p.get('content','')) for p in c4_new)) +if c4_new and any(t in c4_txt for t in ['status', 'weekly', 'report']): + print('PASS: Teams post points to the report (0.25)') + total += 0.25 +else: + print('FAIL: Teams post points to the report') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward_label.json b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..659ba05bf087e2b43c33be2b15996157fb559f89 --- /dev/null +++ b/legacy/beacea76-e300-578d-8dc9-5bf0f1a16d13/reward_label.json @@ -0,0 +1,67 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/beacea76-e300-578d-8dc9-5bf0f1a16d13/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:44", + "label": { + "task_id": "beacea76-e300-578d-8dc9-5bf0f1a16d13", + "domain": "mock_websites", + "summary": "验证用户是否新建了每周状态报告文档并包含指定章节,同时在Slack和Teams中完成相关通知", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_docs_mock", + "monday_mock", + "slack_mock", + "microsoft_teams_mock" + ], + "scoring_components": [ + { + "name": "Component 0", + "weight": 0.2, + "description": "新建每周状态文档", + "check_logic": "比较 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 ID 不在初始集合中且标题(转小写)包含 'weekly status - june w4' 或 'weekly status' 的新文档", + "pass_condition": "存在至少一个符合条件的新建 Google Doc" + }, + { + "name": "Component 1", + "weight": 0.25, + "description": "报告包含 Progress/Risks/Decisions 部分", + "check_logic": "在新建的标题包含 'weekly status' 的文档中,提取所有 content 拼接并转小写,检查是否同时包含 'progress'、'risks'、'decisions' 三个子串", + "pass_condition": "新建 weekly status 文档存在且内容同时包含 progress、risks、decisions" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "Risks 部分指明受阻项目 User Research", + "check_logic": "在新建的标题包含 'weekly status' 的文档中,提取所有 content 拼接并转小写,检查是否包含 'user research'", + "pass_condition": "新建 weekly status 文档存在且内容包含 user research" + }, + { + "name": "Component 3", + "weight": 0.1, + "description": "Slack #general 频道有新消息", + "check_logic": "检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中标记的初始消息 'g1',筛选 senderId 为 'user_1' 的新消息", + "pass_condition": "存在至少一条 user_1 发送的、不在初始种子中的新消息" + }, + { + "name": "Component 4", + "weight": 0.25, + "description": "Teams 帖子指向该报告", + "check_logic": "在 microsoft_teams_mock 的 team 't1' 的 channel 'c1' 中,比较 initial_state 和 current_state 的 posts,找出 userId 为 'user-me' 且不在初始帖子中的新 post,检查其 subject 和 content(转小写拼接)是否包含 'status'、'weekly' 或 'report'", + "pass_condition": "存在至少一条 user-me 发送的新帖子,且帖子标题或内容包含 status、weekly 或 report" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 0.0 退出", + "从任一 mock 服务拉取当前状态失败:打印 CRITICAL 并返回 0.0 退出", + "各组件条件不满足时仅不加分,不会导致提前退出" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_docs_mock、monday_mock、slack_mock、microsoft_teams_mock 四个 mock 服务请求当前状态。若任何一步失败则直接返回 0.0。接着按顺序检查 5 个评分组件:1) 检查 Google Docs 中是否新建了标题含 'weekly status' 的文档;2) 检查该文档内容是否同时包含 'progress'、'risks'、'decisions';3) 检查内容是否包含 'user research';4) 检查 Slack #general 中 user_1 是否发送了非种子新消息;5) 检查 Teams 频道 c1 中 user-me 是否发布了指向报告的新帖子。每个组件通过则累加对应权重,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Task ID: beacea76-e300-578d-8dc9-5bf0f1a16d13(从 docstring 和文件路径中提取)\n - Domain: mock_websites(从 docstring 中提取)\n - Mocks: google_docs_mock, monday_mock, slack_mock, microsoft_teams_mock\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从 MOCK_URLS 获取各个 mock 的 current_state:google_docs_mock, monday_mock, slack_mock, microsoft_teams_mock\n\n3. 评分组件:\n - c0: 0.2 - new weekly status doc(Google Docs 中新建了标题包含 'weekly status - june w4' 或 'weekly status' 的文档)\n - c1: 0.25 - report has Progress/Risks/Decisions(新建 weekly status 文档内容中包含 progress, risks, decisions)\n - c2: 0.2 - Risks names the stuck item (User Research)(新建 weekly status 文档内容中包含 'user research')\n - c3: 0.1 - slack_new_msg(Slack #general 频道中 user_1 发送了新消息)\n - c4: 0.25 - Teams post points to the report(Microsoft Teams 频道 c1 中 user-me 发布了新帖子,标题或内容包含 'status', 'weekly', 'report' 之一)\n\n4. 失败模式:\n - 读取 sid 失败或为空:打印 CRITICAL,REWARD: 0.0,退出\n - 获取任何 mock 状态失败:打印 CRITICAL,REWARD: 0.0,退出\n - 各组件检查失败时只是不加分,不会提前退出\n\n5. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加汇总,然后钳制到 1.0\n\n6. is_placeholder:\n - false,因为脚本有详细的检查逻辑\n\n7. confidence:\n - 1.0,因为代码逻辑清晰完整\n\n现在构建 JSON:\n\ntask_id: \"beacea76-e300-578d-8dc9-5bf0f1a16d13\"\ndomain: \"mock_websites\"\nsummary: \"验证用户是否创建了新的每周状态报告文档,包含进度、风险和决策部分,并在Slack和Teams中进行了相应的通知和分享\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"google_docs_mock\", \"monday_mock\", \"slack_mock\", \"microsoft_teams_mock\"]\n\nscoring_components:\n- name: \"Component 0\"\n weight: 0.2\n description: \"新建每周状态文档\"\n check_logic: \"比较 google_docs_mock 的 initial_state 和 current_state 中的 documents,找出 ID 不在初始集合中且标题(转小写)包含 'weekly status - june w4' 或 'weekly status' 的新文档\"\n pass_condition: \"存在至少一个符合条件的新建 Google Doc\"\n\n- name: \"Component 1\"\n weight: 0.25\n description: \"报告包含 Progress/Risks/Decisions 部分\"\n check_logic: \"在新建的标题包含 'weekly status' 的文档中,提取所有 content 拼接并转小写,检查是否同时包含 'progress'、'risks'、'decisions' 三个子串\"\n pass_condition: \"新建 weekly status 文档存在且内容同时包含 progress、risks、decisions\"\n\n- name: \"Component 2\"\n weight: 0.2\n description: \"Risks 部分指明受阻项目 User Research\"\n check_logic: \"在新建的标题包含 'weekly status' 的文档中,提取所有 content 拼接并转小写,检查是否包含 'user research'\"\n pass_condition: \"新建 weekly status 文档存在且内容包含 user research\"\n\n- name: \"Component 3\"\n weight: 0.1\n description: \"Slack #general 频道有新消息\"\n check_logic: \"检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中标记的初始消息 'g1',筛选 senderId 为 'user_1' 的新消息\"\n pass_condition: \"存在至少一条 user_1 发送的、不在初始种子中的新消息\"\n\n- name: \"Component 4\"\n weight: 0.25\n description: \"Teams 帖子指向该报告\"\n check_logic: \"在 microsoft_teams_mock 的 team 't1' 的 channel 'c1' 中,比较 initial_state 和 current_state 的 posts,找出 userId 为 'user-me' 且不在初始帖子中的新 post,检查其 subject 和 content(转小写拼接)是否包含 'status'、'weekly' 或 'report'\"\n pass_condition: \"存在至少一条 user-me 发送的新帖子,且帖子标题或内容包含 status、weekly 或 report\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 0.0 退出\",\n \"从任一 mock 服务拉取当前状态失败:打印 CRITICAL 并返回 0.0 退出\",\n \"各组件条件不满足时仅不加分,不会导致提前退出\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_docs_mock、monday_mock、slack_mock、microsoft_teams_mock 四个 mock 服务请求当前状态。若任何一步失败则直接返回 0.0。接着按顺序检查 5 个评分组件:1) 检查 Google Docs 中是否新建了标题含 'weekly status' 的文档;2) 检查该文档内容是否同时包含 'progress'、'risks'、'decisions';3) 检查内容是否包含 'user research';4) 检查 Slack #general 中 user_1 是否发送了非种子新消息;5) 检查 Teams 频道 c1 中 user-me 是否发布了指向报告的新帖子。每个组件通过则累加对应权重,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。\"\n\nconfidence: 1.0\n\n确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。 {\"task_id\":\"beacea76-e300-578d-8dc9-5bf0f1a16d13\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否新建了每周状态报告文档并包含指定章节,同时在Slack和Teams中完成相关通知\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_docs_mock\",\"monday_mock\",\"slack_mock\",\"microsoft_teams_mock\"],\"scoring_components\":[{\"name\":\"Component 0\",\"weight\":0.2,\"description\":\"新建每周状态文档\",\"check_logic\":\"比较 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出 ID 不在初始集合中且标题(转小写)包含 'weekly status - june w4' 或 'weekly status' 的新文档\",\"pass_condition\":\"存在至少一个符合条件的新建 Google Doc\"},{\"name\":\"Component 1\",\"weight\":0.25,\"description\":\"报告包含 Progress/Risks/Decisions 部分\",\"check_logic\":\"在新建的标题包含 'weekly status' 的文档中,提取所有 content 拼接并转小写,检查是否同时包含 'progress'、'risks'、'decisions' 三个子串\",\"pass_condition\":\"新建 weekly status 文档存在且内容同时包含 progress、risks、decisions\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"Risks 部分指明受阻项目 User Research\",\"check_logic\":\"在新建的标题包含 'weekly status' 的文档中,提取所有 content 拼接并转小写,检查是否包含 'user research'\",\"pass_condition\":\"新建 weekly status 文档存在且内容包含 user research\"},{\"name\":\"Component 3\",\"weight\":0.1,\"description\":\"Slack #general 频道有新消息\",\"check_logic\":\"检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中标记的初始消息 'g1',筛选 senderId 为 'user_1' 的新消息\",\"pass_condition\":\"存在至少一条 user_1 发送的、不在初始种子中的新消息\"},{\"name\":\"Component 4\",\"weight\":0.25,\"description\":\"Teams 帖子指向该报告\",\"check_logic\":\"在 microsoft_teams_mock 的 team 't1' 的 channel 'c1' 中,比较 initial_state 和 current_state 的 posts,找出 userId 为 'user-me' 且不在初始帖子中的新 post,检查其 subject 和 content(转小写拼接)是否包含 'status'、'weekly' 或 'report'\",\"pass_condition\":\"存在至少一条 user-me 发送的新帖子,且帖子标题或内容包含 status、weekly 或 report\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 0.0 退出\",\"从任一 mock 服务拉取当前状态失败:打印 CRITICAL 并返回 0.0 退出\",\"各组件条件不满足时仅不加分,不会导致提前退出\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_docs_mock、monday_mock、slack_mock、microsoft_teams_mock 四个 mock 服务请求当前状态。若任何一步失败则直接返回 0.0。接着按顺序检查 5 个评分组件:1) 检查 Google Docs 中是否新建了标题含 'weekly status' 的文档;2) 检查该文档内容是否同时包含 'progress'、'risks'、'decisions';3) 检查内容是否包含 'user research';4) 检查 Slack #general 中 user_1 是否发送了非种子新消息;5) 检查 Teams 频道 c1 中 user-me 是否发布了指向报告的新帖子。每个组件通过则累加对应权重,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。\",\"confidence\":1.0}" +} diff --git a/legacy/csm_onboarding_kickoff_002/_cua_gym_vm_bridge.sh b/legacy/csm_onboarding_kickoff_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/csm_onboarding_kickoff_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/csm_onboarding_kickoff_002/initial_setup.py b/legacy/csm_onboarding_kickoff_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..96b5bc31b516b6f047fc43a2626462038abc0d23 --- /dev/null +++ b/legacy/csm_onboarding_kickoff_002/initial_setup.py @@ -0,0 +1,548 @@ +# --- 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.186.212"): + 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 kicks off onboarding for a brand-new customer (Lumira Biotech) +across Gmail, Notion, and Trello. +Task ID: csm_onboarding_kickoff_002 +Domain: mock_websites +Mocks: gmail_mock, notion_mock, trello_mock + +Persona: Jordan Rivera (CSM), Northwind Cloud, jordan.rivera@northwindcloud.com. +Today = 2026-06-24. + +Pre-task state ONLY. MUST NOT contain task-completed elements: + - Gmail: NO sent/draft email to maya.cho@lumirabiotech.com. drafts = []. + Inbox DOES contain a welcome/handoff email FROM Maya Cho so her + address is discoverable, plus a near-duplicate distractor from + 'Maya Chu' at an unrelated company. + - Notion: parent page 'Customer Onboarding' exists; NO Lumira Biotech + onboarding child page yet. + - Trello: board 'Customer Onboarding' with lists New / In Progress / Live. + Card 'Lumira Biotech' lives in 'New' with dueDate null. A + near-duplicate distractor card 'Lumira Bioscience' lives in a + different list. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Egress proxy: VM reaches the public mocks only via the cluster proxy. +# Set proxy env vars so every requests call routes through it directly +# (a "direct-first" attempt hangs on the unreachable IPv6 route). --- +PROXY = os.environ.get('CUA_MOCK_PROXY', None) +for _k in ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'): + os.environ[_k] = PROXY + +# --- Mock registry --- +MOCKS = { + 'gmail_mock': 'http://28.7.186.212:8158', + 'notion_mock': 'http://28.7.186.212:8186', + 'trello_mock': 'http://28.7.186.212:8202', +} + +# --- Shared session id --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid={sid}') + +# --- Network helper --- +def http_post(url, payload): + return requests.post(url, json=payload, timeout=40) + + +def http_get(url): + return requests.get(url, timeout=40) + + +# ========================================================================= +# GMAIL STATE — CSM mailbox with discoverable contact + distractor +# ========================================================================= +def build_gmail_state(): + return { + 'user': { + 'userId': 'u1', + 'username': 'Jordan Rivera', + 'email': 'jordan.rivera@northwindcloud.com', + 'avatar': '', + }, + 'emails': [ + # --- TARGET: welcome/handoff FROM the new customer's main contact --- + { + 'id': 'email_1', 'threadId': 'thread_lumira', + 'from': {'name': 'Maya Cho', 'email': 'maya.cho@lumirabiotech.com'}, + 'to': [{'name': 'Jordan Rivera', 'email': 'jordan.rivera@northwindcloud.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Excited to get started with Northwind Cloud', + 'body': ("Hi Jordan,

We just finished signing and our team at " + "Lumira Biotech is thrilled to be getting started. I'll be your " + "main point of contact on our side throughout onboarding.

" + "Looking forward to meeting you and kicking things off.

" + "Best,
Maya Cho
VP of Operations, Lumira Biotech"), + 'timestamp': '2026-06-23T15:20:00Z', + 'read': True, 'starred': False, 'important': True, + 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox', + 'attachments': [], + }, + # --- DISTRACTOR: near-duplicate name, different (unrelated) company --- + { + 'id': 'email_2', 'threadId': 'thread_chu', + 'from': {'name': 'Maya Chu', 'email': 'maya.chu@lumiratech.io'}, + 'to': [{'name': 'Jordan Rivera', 'email': 'jordan.rivera@northwindcloud.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Re: API sandbox question', + 'body': ("Hi Jordan,

Thanks for the quick reply on the sandbox " + "rate limits — all sorted now.

Cheers,
" + "Maya Chu
LumiraTech"), + 'timestamp': '2026-06-22T11:05:00Z', + 'read': True, 'starred': False, 'important': False, + 'labels': [], 'category': 'primary', 'folder': 'inbox', + 'attachments': [], + }, + # --- Unrelated inbox noise --- + { + 'id': 'email_3', 'threadId': 'thread_internal', + 'from': {'name': 'Dana Lee', 'email': 'dana.lee@northwindcloud.com'}, + 'to': [{'name': 'Jordan Rivera', 'email': 'jordan.rivera@northwindcloud.com'}], + 'cc': [], 'bcc': [], + 'subject': 'CS team standup moved to 10am', + 'body': ("Hi all, heads-up that our daily standup is moving to 10:00am. " + "Thanks, Dana"), + 'timestamp': '2026-06-22T08:30:00Z', + 'read': True, 'starred': False, 'important': False, + 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox', + 'attachments': [], + }, + { + 'id': 'email_4', 'threadId': 'thread_promo', + 'from': {'name': 'SaaSConf 2026', 'email': 'hello@saasconf.example.com'}, + 'to': [{'name': 'Jordan Rivera', 'email': 'jordan.rivera@northwindcloud.com'}], + 'cc': [], 'bcc': [], + 'subject': 'Early-bird tickets closing soon', + 'body': ("Don't miss out on early-bird pricing for SaaSConf 2026. " + "Register now to save 30%."), + 'timestamp': '2026-06-20T17:45:00Z', + 'read': False, 'starred': False, 'important': False, + 'labels': [], 'category': 'promotions', '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': [], + } + + +# ========================================================================= +# NOTION STATE — parent 'Customer Onboarding' page, no Lumira child yet +# ========================================================================= +def build_notion_state(): + onboarding_id = 'page-onboarding' + # A small bit of existing content on the parent page so it is not blank. + intro_block_id = 'blk-onboarding-intro' + + pages = { + onboarding_id: { + 'id': onboarding_id, + 'title': 'Customer Onboarding', + 'icon': '🚀', + 'cover': None, + 'parentId': None, + 'blockIds': [intro_block_id], + 'favorite': True, + 'createdDate': '2026-01-10T09:00:00.000Z', + 'lastEditedDate': '2026-06-01T09:00:00.000Z', + 'properties': {}, + }, + # A pre-existing, unrelated child page so the space looks lived-in. + 'page-playbook': { + 'id': 'page-playbook', + 'title': 'Onboarding Playbook (Template)', + 'icon': '📘', + 'cover': None, + 'parentId': onboarding_id, + 'blockIds': [], + 'favorite': False, + 'createdDate': '2026-02-01T09:00:00.000Z', + 'lastEditedDate': '2026-02-01T09:00:00.000Z', + 'properties': {}, + }, + } + + blocks = { + intro_block_id: { + 'id': intro_block_id, + 'type': 'text', + 'content': ('Customer onboarding workspace. Create one checklist page per new ' + 'customer to track them from kickoff to go-live.'), + 'properties': {}, + 'createdDate': '2026-01-10T09:00:00.000Z', + 'lastEditedDate': '2026-01-10T09:00:00.000Z', + }, + } + + 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'], + }, + 'pages': pages, + 'blocks': blocks, + 'trash': [], + 'comments': {}, + 'settings': {'appearance': 'light', 'startWeekMonday': False, 'fontSize': 'default'}, + 'notifications': [], + 'pageOrder': [onboarding_id], + 'focusBlockId': None, + } + + +# ========================================================================= +# TRELLO STATE — 'Customer Onboarding' board; Lumira Biotech card in 'New' +# ========================================================================= +def build_trello_state(): + user_1 = {'id': 'u1', 'name': 'Jordan Rivera', 'username': 'jordanrivera', + 'initials': 'JR', 'email': 'jordan.rivera@northwindcloud.com', 'avatarUrl': ''} + user_2 = {'id': 'u2', 'name': 'Dana Lee', 'username': 'danalee', + 'initials': 'DL', 'email': 'dana.lee@northwindcloud.com', 'avatarUrl': ''} + + board = { + 'id': 'board-onboarding', + 'title': 'Customer Onboarding', + 'description': 'Track new customers from signed to go-live.', + 'background': '#0079BF', + 'listIds': ['list-new', 'list-inprogress', 'list-live'], + 'starred': True, + 'visibility': 'workspace', + 'archivedListIds': [], + 'archivedCardIds': [], + 'labels': [ + {'id': 'lbl-onb', 'name': 'Onboarding', 'color': 'green'}, + {'id': 'lbl-prio', 'name': 'Priority', 'color': 'red'}, + ], + 'memberIds': ['u1', 'u2'], + 'createdAt': '2026-01-05T10:00:00.000Z', + } + + lists = { + 'list-new': { + 'id': 'list-new', 'title': 'New', 'boardId': 'board-onboarding', + # TARGET card 'Lumira Biotech' lives here; distractor lives elsewhere. + 'cardIds': ['card-lumira-biotech', 'card-acme'], + 'archived': False, + }, + 'list-inprogress': { + 'id': 'list-inprogress', 'title': 'In Progress', 'boardId': 'board-onboarding', + # DISTRACTOR card 'Lumira Bioscience' lives here (different list). + 'cardIds': ['card-lumira-bioscience', 'card-orbit'], + 'archived': False, + }, + 'list-live': { + 'id': 'list-live', 'title': 'Live', 'boardId': 'board-onboarding', + 'cardIds': ['card-helio'], + 'archived': False, + }, + } + + def card(cid, title, list_id, due=None, desc=''): + return { + 'id': cid, 'title': title, 'description': desc, + 'listId': list_id, 'boardId': 'board-onboarding', + 'labelIds': [], 'memberIds': [], 'dueDate': due, 'startDate': None, + 'completed': False, 'cover': None, 'checklists': [], 'comments': [], + 'attachments': [], 'archived': False, 'watching': False, + 'position': 0, 'createdAt': '2026-06-22T10:00:00.000Z', + } + + cards = { + # TARGET: brand-new customer, sits in 'New' with NO due date. + 'card-lumira-biotech': card( + 'card-lumira-biotech', 'Lumira Biotech', 'list-new', due=None, + desc='New signed customer — onboarding kickoff pending.'), + # DISTRACTOR in 'New' + 'card-acme': card( + 'card-acme', 'Acme Robotics', 'list-new', due=None, + desc='Prospect signed, awaiting kickoff scheduling.'), + # DISTRACTOR: near-duplicate name in a DIFFERENT list — must stay put. + 'card-lumira-bioscience': card( + 'card-lumira-bioscience', 'Lumira Bioscience', 'list-inprogress', + due='2026-07-15T17:00:00.000Z', + desc='Existing customer (different company) — onboarding underway.'), + 'card-orbit': card( + 'card-orbit', 'Orbit Analytics', 'list-inprogress', + due='2026-07-10T17:00:00.000Z', + desc='Mid-onboarding; data import in progress.'), + 'card-helio': card( + 'card-helio', 'Helio Health', 'list-live', due=None, + desc='Live since last month.'), + } + + return { + 'currentUser': 'u1', + 'users': {'u1': user_1, 'u2': user_2}, + 'boards': {'board-onboarding': board}, + 'lists': lists, + 'cards': cards, + 'boardOrder': ['board-onboarding'], + } + + +# ========================================================================= +# INJECT +# ========================================================================= +builders = { + 'gmail_mock': build_gmail_state, + 'notion_mock': build_notion_state, + 'trello_mock': build_trello_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["gmail_mock"]}/?sid={sid}"', delay_sec=2.5) +launch_gui(f'google-chrome "{MOCKS["notion_mock"]}/?sid={sid}"', delay_sec=2.0) +launch_gui(f'google-chrome "{MOCKS["trello_mock"]}/?sid={sid}"', delay_sec=2.0) +wait_mocks_loaded() +print('GUI_READY: launched Chrome tabs for gmail, notion, trello with DISPLAY=:0') diff --git a/legacy/csm_onboarding_kickoff_002/reward.py b/legacy/csm_onboarding_kickoff_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..02f9317f412b9bf369a61c748577f151cf32fe71 --- /dev/null +++ b/legacy/csm_onboarding_kickoff_002/reward.py @@ -0,0 +1,352 @@ +# --- 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.186.212"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +""" +Reward Script: CSM onboarding kickoff for Lumira Biotech (welcome email + Notion checklist + Trello card move) +Task ID: csm_onboarding_kickoff_002 +Domain: mock_websites (multi-mock: gmail_mock, notion_mock, trello_mock) + +Scoring (only task-introduced changes are scored; all checks FAIL on initial_env, PASS on golden_env): + Gmail (0.35): + G1 (0.20) PROGRAMMATIC: a NEW email in folder 'sent' addressed in `to` to maya.cho@lumirabiotech.com + with a non-empty subject (and NOT the distractor maya.chu@lumiratech.io). + G2 (0.15) PROGRAMMATIC: the welcome body introduces the CSM (Jordan Rivera) AND confirms + onboarding/kickoff is starting. + Notion (0.30): + N1 (0.15) PROGRAMMATIC: a NEW page whose parentId is the 'Customer Onboarding' page and whose + title references Lumira Biotech onboarding. + N2 (0.15) PROGRAMMATIC: that new page contains >= 5 checklist/to-do (or bullet) blocks. + Trello (0.35): + T1 (0.20) PROGRAMMATIC: the 'Lumira Biotech' card moved out of 'New' into 'In Progress' + (listId changed, 'New'.cardIds lost it, 'In Progress'.cardIds gained it). + T2 (0.15) PROGRAMMATIC: that card's dueDate is set to the project deadline, 2026-12-25. + +Programmatic = 1.0 (100%), LLM judge = 0.0. +""" +import json +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 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 = { + 'gmail': 'http://28.7.186.212:8158', + 'notion': 'http://28.7.186.212:8186', + 'trello': 'http://28.7.186.212:8202', +} + +# --- §2.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 + return None + + +PROXY = resolve_proxy(f"{MOCKS['gmail']}/go?sid=conn-probe") +PROXIES = None + + +def fetch(url): + data = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + + +# --- Fetch all three mocks' state --- +try: + gmail_init, gmail_cur = fetch(MOCKS['gmail']) + notion_init, notion_cur = fetch(MOCKS['notion']) + trello_init, trello_cur = fetch(MOCKS['trello']) +except Exception as e: + print(f'CRITICAL: Cannot fetch mock state: {e}') + print('REWARD: 0.0') + sys.exit(0) + +TARGET_EMAIL = 'maya.cho@lumirabiotech.com' +DISTRACTOR_EMAIL = 'maya.chu@lumiratech.io' +PROJECT_DEADLINE = '2026-12-25' + + +def normalize_text(value): + text = str(value or '').casefold() + text = re.sub(r'[^a-z0-9@._+-]+', ' ', text) + return re.sub(r'\s+', ' ', text).strip() + + +def contains_any_phrase(value, phrases): + haystack = normalize_text(value) + return any(normalize_text(phrase) in haystack for phrase in phrases) + + +def contains_all_terms(value, terms): + haystack = normalize_text(value) + return all(normalize_text(term) in haystack for term in terms) + + +def due_date_matches(value, expected_date): + if not value: + return False + due = str(value).strip() + if due.startswith(expected_date): + return True + year, month, day = expected_date.split('-') + common_formats = { + f'{month}/{day}/{year}', + f'{month}-{day}-{year}', + f'{year}/{month}/{day}', + } + return any(due.startswith(fmt) for fmt in common_formats) + + +def verify_task(): + total_score = 0.0 + + # ------------------------------------------------------------------ + # Component G1 (0.20) — PROGRAMMATIC: new SENT email to the correct contact + # ------------------------------------------------------------------ + sent_welcome = None + try: + init_ids = {e.get('id') for e in gmail_init.get('emails', [])} + new_emails = [e for e in gmail_cur.get('emails', []) if e.get('id') not in init_ids] + matches = [] + for e in new_emails: + if e.get('folder') != 'sent': + continue + to_addrs = [str(t.get('email', '')).lower().strip() for t in (e.get('to') or [])] + if TARGET_EMAIL in to_addrs and e.get('subject') and str(e.get('subject')).strip(): + matches.append(e) + if matches: + sent_welcome = matches[0] + print(f"PASS: G1 — new sent email to {TARGET_EMAIL} " + f"(subject={sent_welcome.get('subject')!r}) (0.20 pts)") + total_score += 0.20 + else: + print(f"FAIL: G1 — no new sent email to {TARGET_EMAIL} with a non-empty subject " + f"(new emails found: {[(e.get('id'), e.get('folder'), [t.get('email') for t in (e.get('to') or [])]) for e in new_emails]})") + except Exception as e: + print(f'ERROR: G1 — {e}') + + # ------------------------------------------------------------------ + # Component G2 (0.15) — PROGRAMMATIC: welcome body introduces the CSM AND confirms kickoff. + # The ground truth requires the body to (a) introduce the CSM Jordan Rivera and + # (b) confirm onboarding/kickoff is starting. Both are concrete, checkable content + # requirements (a deterministic content check, NOT a tone judgement) so they are + # verified programmatically for a stable, reproducible score. + # NOTE: a deterministic content check is used here (rather than an LLM judge) because + # the requirements are enumerable and to keep the reward fully reproducible. + # Gated on G1 (only evaluate an actually-sent welcome email to the right person). + # ------------------------------------------------------------------ + try: + if sent_welcome is not None: + body = str(sent_welcome.get('body', '')) + subject = str(sent_welcome.get('subject', '')) + blob = f'{subject}\n{body}' + # (a) introduces the CSM — accept common name formats. + introduces_csm = contains_any_phrase(blob, ['jordan', 'jordan rivera', 'rivera']) + # (b) confirms onboarding / kickoff is starting + kickoff_terms = [ + 'onboarding', 'on boarding', 'on-boarding', 'onboard', 'kickoff', + 'kick off', 'kicking off', 'kick-off', 'kick things off', + 'getting started', 'get started', 'start onboarding', + 'starting onboarding', 'begin onboarding', 'begin the onboarding', + 'onboarding start', 'onboarding kickoff', 'launch onboarding', + 'onboarding launch', 'implementation kickoff', 'customer kickoff', + ] + confirms_kickoff = contains_any_phrase(blob, kickoff_terms) + if introduces_csm and confirms_kickoff: + print(f"PASS: G2 — body introduces CSM (Jordan) and confirms onboarding/kickoff (0.15 pts)") + total_score += 0.15 + else: + print(f"FAIL: G2 — introduces_csm={introduces_csm}, confirms_kickoff={confirms_kickoff}") + else: + print('FAIL: G2 — no welcome email to evaluate (G1 did not pass)') + except Exception as e: + print(f'ERROR: G2 — {e}') + + # ------------------------------------------------------------------ + # Notion: locate the 'Customer Onboarding' parent page id from initial state + # (precondition gate — found in BOTH envs, so not scored on its own). + # ------------------------------------------------------------------ + onboarding_pid = None + try: + for pid, p in (notion_init.get('pages') or {}).items(): + if normalize_text(p.get('title', '')) == 'customer onboarding': + onboarding_pid = pid + break + except Exception as e: + print(f'ERROR: locating Customer Onboarding parent page — {e}') + + # ------------------------------------------------------------------ + # Component N1 (0.15) — PROGRAMMATIC: NEW child page under Customer Onboarding + # referencing Lumira Biotech. + # ------------------------------------------------------------------ + lumira_page = None + try: + init_pids = set((notion_init.get('pages') or {}).keys()) + cur_pages = notion_cur.get('pages') or {} + candidates = [] + for pid, p in cur_pages.items(): + if pid in init_pids: + continue # only NEW pages + if onboarding_pid and p.get('parentId') != onboarding_pid: + continue + title = p.get('title', '') + if contains_all_terms(title, ['lumira', 'biotech']): + candidates.append((pid, p)) + if candidates: + lumira_page = candidates[0][1] + print(f"PASS: N1 — new page under 'Customer Onboarding' referencing Lumira Biotech " + f"(title={lumira_page.get('title')!r}) (0.15 pts)") + total_score += 0.15 + else: + print(f"FAIL: N1 — no NEW page with parentId={onboarding_pid!r} whose title references " + f"Lumira Biotech") + except Exception as e: + print(f'ERROR: N1 — {e}') + + # ------------------------------------------------------------------ + # Component N2 (0.15) — PROGRAMMATIC: that page has >= 5 checklist/to-do/bullet blocks. + # Gated on N1 (must be the new Lumira page). + # ------------------------------------------------------------------ + try: + if lumira_page is not None: + blocks = notion_cur.get('blocks') or {} + checklist_types = {'todo', 'to-do', 'bullet-list', 'numbered-list', 'checkbox'} + count = 0 + for bid in (lumira_page.get('blockIds') or []): + b = blocks.get(bid) + if not b: + continue + if str(b.get('type', '')).lower() in checklist_types: + count += 1 + if count >= 5: + print(f"PASS: N2 — Lumira page has {count} checklist/to-do/bullet blocks (>=5) (0.15 pts)") + total_score += 0.15 + else: + print(f"FAIL: N2 — Lumira page has only {count} checklist/to-do/bullet blocks (need >=5)") + else: + print('FAIL: N2 — no Lumira onboarding page to inspect (N1 did not pass)') + except Exception as e: + print(f'ERROR: N2 — {e}') + + # ------------------------------------------------------------------ + # Trello: locate the 'Lumira Biotech' card and the relevant board's lists. + # ------------------------------------------------------------------ + init_cards = trello_init.get('cards') or {} + init_lists = trello_init.get('lists') or {} + cur_cards = trello_cur.get('cards') or {} + cur_lists = trello_cur.get('lists') or {} + lumira_card = None + try: + for cid, c in cur_cards.items(): + if contains_all_terms(c.get('title', ''), ['lumira', 'biotech']): + lumira_card = c + break + except Exception as e: + print(f'ERROR: locating Lumira Biotech card — {e}') + + # Identify the 'In Progress' and 'New' list ids on the card's board. + inprogress_lid = None + new_lid = None + try: + board_id = lumira_card.get('boardId') if lumira_card else None + for lid, l in cur_lists.items(): + if board_id and l.get('boardId') != board_id: + continue + title = normalize_text(l.get('title', '')) + if title == 'in progress': + inprogress_lid = lid + elif title == 'new': + new_lid = lid + except Exception as e: + print(f'ERROR: locating Trello lists — {e}') + + # ------------------------------------------------------------------ + # Component T1 (0.20) — PROGRAMMATIC: card moved from 'New' to 'In Progress'. + # ------------------------------------------------------------------ + try: + if lumira_card is not None and inprogress_lid and new_lid: + card_id = lumira_card.get('id') + init_card = init_cards.get(card_id, {}) + initially_in_new = ( + init_card.get('listId') == new_lid + and card_id in (init_lists.get(new_lid, {}).get('cardIds') or []) + ) + in_inprogress = ( + lumira_card.get('listId') == inprogress_lid + and card_id in (cur_lists.get(inprogress_lid, {}).get('cardIds') or []) + ) + not_in_new = card_id not in (cur_lists.get(new_lid, {}).get('cardIds') or []) + list_changed = init_card.get('listId') != lumira_card.get('listId') + if initially_in_new and list_changed and in_inprogress and not_in_new: + print(f"PASS: T1 — 'Lumira Biotech' card moved to 'In Progress' " + f"(listId={lumira_card.get('listId')}) and removed from 'New' (0.20 pts)") + total_score += 0.20 + else: + print(f"FAIL: T1 — card not properly moved " + f"(listId={lumira_card.get('listId')}, initially_in_new={initially_in_new}, " + f"list_changed={list_changed}, in_inprogress={in_inprogress}, not_in_new={not_in_new})") + else: + print(f"FAIL: T1 — could not resolve card/lists " + f"(card={lumira_card is not None}, inprogress_lid={inprogress_lid}, new_lid={new_lid})") + except Exception as e: + print(f'ERROR: T1 — {e}') + + # ------------------------------------------------------------------ + # Component T2 (0.15) — PROGRAMMATIC: dueDate set to the project deadline, 2026-12-25. + # ------------------------------------------------------------------ + try: + if lumira_card is not None: + due = lumira_card.get('dueDate') + if due_date_matches(due, PROJECT_DEADLINE): + print(f"PASS: T2 — dueDate set to {PROJECT_DEADLINE} (value={due}) (0.15 pts)") + total_score += 0.15 + else: + print(f"FAIL: T2 — dueDate is {due!r}, expected {PROJECT_DEADLINE}") + else: + print('FAIL: T2 — no Lumira Biotech card to inspect') + except Exception as e: + print(f'ERROR: T2 — {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/legacy/csm_onboarding_kickoff_002/reward_label.json b/legacy/csm_onboarding_kickoff_002/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..703721141a6d825ce454d190b9fa2bb836fe548c --- /dev/null +++ b/legacy/csm_onboarding_kickoff_002/reward_label.json @@ -0,0 +1,76 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_onboarding_kickoff_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:22:21", + "label": { + "task_id": "csm_onboarding_kickoff_002", + "domain": "mock_websites", + "summary": "验证 Lumira Biotech 的 CSM 入职启动任务:通过 Gmail 发送欢迎邮件、在 Notion 的 Customer Onboarding 下新建含清单的页面、在 Trello 将 Lumira Biotech 卡片从 New 移至 In Progress 并设置截止日期 2026-12-25", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "gmail_mock", + "notion_mock", + "trello_mock" + ], + "scoring_components": [ + { + "name": "G1", + "weight": 0.2, + "description": "Gmail 中发送给正确联系人的新邮件", + "check_logic": "对比 gmail_init 与 gmail_cur 的 emails,筛选 id 不在初始集合中、folder 为 'sent'、收件人 to 中包含 TARGET_EMAIL (maya.cho@lumirabiotech.com) 且 subject 非空的新邮件;排除 DISTRACTOR_EMAIL", + "pass_condition": "存在至少一封满足条件的新 sent 邮件" + }, + { + "name": "G2", + "weight": 0.15, + "description": "欢迎邮件正文介绍 CSM 并确认启动入职", + "check_logic": "以 G1 通过的邮件为评估对象,将其 subject 与 body 拼接为 blob,通过 contains_any_phrase 检查是否包含 'jordan'/'jordan rivera'/'rivera'(introduces_csm),以及是否包含 onboarding/kickoff 相关短语列表中的任意一项(confirms_kickoff)", + "pass_condition": "introduces_csm 与 confirms_kickoff 同时为 True" + }, + { + "name": "N1", + "weight": 0.15, + "description": "Notion 中在 Customer Onboarding 下新建引用 Lumira Biotech 的页面", + "check_logic": "先从 notion_init 中定位标题为 'Customer Onboarding' 的页面 id;再在 notion_cur.pages 中查找 id 为新增、parentId 匹配该 id、且标题通过 contains_all_terms 同时包含 'lumira' 与 'biotech' 的页面", + "pass_condition": "存在至少一个满足条件的新页面" + }, + { + "name": "N2", + "weight": 0.15, + "description": "新建页面包含至少 5 个清单/待办/列表块", + "check_logic": "以 N1 通过的页面为对象,遍历其 blockIds,在 notion_cur.blocks 中查找对应 block,统计 type(转小写后)属于 {'todo','to-do','bullet-list','numbered-list','checkbox'} 的数量", + "pass_condition": "统计数量 >= 5" + }, + { + "name": "T1", + "weight": 0.2, + "description": "Trello 中 Lumira Biotech 卡片从 New 移至 In Progress", + "check_logic": "在 trello_cur.cards 中找到标题含 'lumira' 与 'biotech' 的卡片;在其 board 上定位标题为 'new' 与 'in progress' 的列表 id;验证初始状态该卡片 listId 为 new_lid 且 cardId 在 init_lists[new_lid].cardIds 中,当前状态 listId 为 inprogress_lid 且 cardId 在 cur_lists[inprogress_lid].cardIds 中,同时初始与当前 listId 不同且当前已不在 new_lid 的 cardIds 中", + "pass_condition": "initially_in_new、list_changed、in_inprogress、not_in_new 全部为 True" + }, + { + "name": "T2", + "weight": 0.15, + "description": "Trello 卡片截止日期设为项目截止日期", + "check_logic": "获取 lumira_card 的 dueDate,通过 due_date_matches 检查是否以 2026-12-25 开头,或匹配 MM/DD/YYYY、MM-DD-YYYY、YYYY/MM/DD 等常见格式开头", + "pass_condition": "dueDate 匹配 PROJECT_DEADLINE (2026-12-25)" + } + ], + "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 服务状态失败:打印 CRITICAL 并返回 0.0 退出", + "G1 失败导致 G2 被跳过(无邮件可评估)", + "N1 失败导致 N2 被跳过(无页面可检查)", + "T1/T2 中若找不到 Lumira Biotech 卡片或相关列表,则对应组件失败", + "各组件内部异常被捕获,打印 ERROR 且该组件不得分,但不中断后续评分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0;随后通过 HTTP 分别拉取 gmail_mock、notion_mock、trello_mock 的 initial_state 与 current_state,拉取失败也直接返回 0.0。评分按顺序执行六个组件:G1 检查 Gmail 当前状态相比初始状态是否存在发给 maya.cho@lumirabiotech.com 的新 sent 邮件且主题非空;若 G1 通过,G2 进一步检查该邮件的主题与正文是否同时提到 CSM Jordan Rivera 并确认 onboarding/kickoff。Notion 部分先从初始状态锁定 'Customer Onboarding' 页面 id,N1 检查当前状态是否出现以该页面为 parentId 且标题包含 Lumira Biotech 的新页面;若 N1 通过,N2 统计该新页面的 blockIds 中 checklist/to-do/bullet/numbered-list/checkbox 类型块的数量是否不少于 5 个。Trello 部分先定位标题含 Lumira Biotech 的当前卡片及其 board 上的 New 与 In Progress 列表,T1 验证该卡片初始位于 New 列表、当前位于 In Progress 列表且 listId 确实发生变更;T2 验证该卡片的 dueDate 是否为项目截止日期 2026-12-25。各组件得分累加,最终通过 min(total_score, 1.0) 钳制并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: csm_onboarding_kickoff_002\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock: gmail_mock, notion_mock, trello_mock)\"\n3. **summary**: 一句话概括:验证用户是否完成了 Lumira Biotech 的 CSM 入职启动任务,包括发送欢迎邮件、在 Notion 创建检查清单、在 Trello 移动卡片并设置截止日期。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `gmail_mock` (http://28.7.186.212:8138)\n - `notion_mock` (http://28.7.186.212:8166)\n - `trello_mock` (http://28.7.186.212:8182)\n6. **scoring_components**:\n - G1 (0.20): 检查 Gmail 当前状态相比初始状态是否有新的 sent 邮件,收件人是 maya.cho@lumirabiotech.com,主题非空。\n - G2 (0.15): 检查 G1 通过的邮件内容(主题+正文)是否包含 Jordan Rivera 相关名字,以及是否包含 onboarding/kickoff 相关词汇。Gated on G1。\n - N1 (0.15): 检查 Notion 当前状态相比初始状态是否有新页面,parentId 是 'Customer Onboarding' 页面,标题包含 Lumira Biotech。\n - N2 (0.15): 检查 N1 找到的新页面是否有 >=5 个 checklist/to-do/bullet/numbered-list/checkbox 类型的 blocks。Gated on N1。\n - T1 (0.20): 检查 Trello 中 'Lumira Biotech' 卡片是否从 'New' 列表移动到了 'In Progress' 列表(初始状态在 New,当前状态在 In Progress,且 listId 改变)。\n - T2 (0.15): 检查 Trello 中 'Lumira Biotech' 卡片的 dueDate 是否设置为 2026-12-25(支持多种格式)。\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 状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - G1 失败会导致 G2 被跳过(gated)\n - N1 失败会导致 N2 被跳过(gated)\n - T1/T2 如果找不到卡片或列表会失败\n - 各组件异常会被捕获并打印 ERROR,但不退出,只是不得分\n10. **scoring_logic_explanation**: 按执行顺序:\n - 读取 sid 文件,失败则 0 分退出。\n - 通过 HTTP 获取 gmail、notion、trello 三个 mock 服务的 initial_state 和 current_state,失败则 0 分退出。\n - Gmail 部分:对比初始和当前邮件,找 sent 文件夹中发给 TARGET_EMAIL 且主题非空的新邮件(G1)。若找到,检查该邮件主题+正文是否同时包含 CSM 名字(Jordan Rivera)和 onboarding/kickoff 相关短语(G2)。\n - Notion 部分:先从初始状态找到 'Customer Onboarding' 页面 id。在当前状态的新页面中找 parentId 匹配且标题含 'Lumira' 和 'Biotech' 的页面(N1)。若找到,统计该页面 blockIds 中类型为 todo/to-do/bullet-list/numbered-list/checkbox 的块数量是否 >=5(N2)。\n - Trello 部分:在当前卡片中找标题含 'Lumira Biotech' 的卡片。确定其所在 board 的 'New' 和 'In Progress' 列表 id。检查该卡片初始 listId 是否为 New、当前是否为 In Progress、且 cardIds 列表同步正确(T1)。检查卡片 dueDate 是否匹配 2026-12-25(T2)。\n - 所有组件得分累加,最终 min(total, 1.0) 并四舍五入到 4 位小数。\n11. **confidence**: 1.0,因为代码逻辑非常清晰完整。\n\n让我再仔细检查一下各个字段:\n\n- task_id: \"csm_onboarding_kickoff_002\"\n- domain: \"mock_websites\"\n- summary: 验证 Lumira Biotech 的 CSM 入职启动任务,包括发送欢迎邮件、在 Notion 创建检查清单页、在 Trello 将卡片移至进行中并设置截止日期。\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"gmail_mock\", \"notion_mock\", \"trello_mock\"] (具体地址也可以写上,但通常 mock 服务名就够了,不过用户示例里有 slack_mock 等,我可以写具体 URL 或服务名。看用户示例:\"slack_mock、github_mock\",我写服务名加文件路径比较好)\n- scoring_components:\n - name: \"G1\", weight: 0.20, description: \"Gmail 中发送给正确联系人的新邮件\", check_logic: \"对比 initial 和 current 状态,筛选 folder 为 'sent' 且 id 为新、收件人包含 maya.cho@lumirabiotech.com、subject 非空的邮件\", pass_condition: \"存在至少一封满足条件的新 sent 邮件\"\n - name: \"G2\", weight: 0.15, description: \"欢迎邮件正文介绍 CSM 并确认启动入职\", check_logic: \"将 G1 通过邮件的 subject 和 body 拼接,使用 normalize_text 和 contains_any_phrase 检查是否包含 'jordan'/'jordan rivera'/'rivera',以及 onboarding/kickoff 相关短语列表中的任意一个\", pass_condition: \"同时满足 introduces_csm 和 confirms_kickoff 两个条件\"\n - name: \"N1\", weight: 0.15, description: \"Notion 中在 Customer Onboarding 下新建引用 Lumira Biotech 的页面\", check_logic: \"从 notion_init 找到标题为 'Customer Onboarding' 的页面 id;在 notion_cur 的 pages 中找 id 为新的、parentId 匹配、且标题通过 contains_all_terms 同时包含 'lumira' 和 'biotech' 的页面\", pass_condition: \"存在至少一个满足条件的新页面\"\n - name: \"N2\", weight: 0.15, description: \"新建页面包含至少 5 个清单/待办/列表块\", check_logic: \"遍历 N1 页面的 blockIds,在 notion_cur.blocks 中查找对应 block,统计 type(转小写后)属于 {'todo','to-do','bullet-list','numbered-list','checkbox'} 的数量\", pass_condition: \"统计数量 >= 5\"\n - name: \"T1\", weight: 0.20, description: \"Trello 中 Lumira Biotech 卡片从 New 移至 In Progress\", check_logic: \"找到标题含 Lumira Biotech 的当前卡片;确定其 board 上标题为 'new' 和 'in progress' 的列表 id;检查初始状态该卡片 listId 为 new_lid 且 cardId 在 New 列表的 cardIds 中;当前状态 listId 为 inprogress_lid 且 cardId 在 In Progress 列表的 cardIds 中;且初始与当前 listId 不同\", pass_condition: \"initially_in_new、list_changed、in_inprogress、not_in_new 全部为 True\"\n - name: \"T2\", weight: 0.15, description: \"Trello 卡片截止日期设为项目截止日期\", check_logic: \"获取 lumira_card 的 dueDate,使用 due_date_matches 函数检查是否以 2026-12-25 开头,或匹配 MM/DD/YYYY、MM-DD-YYYY、YYYY/MM/DD 等常见格式开头\", pass_condition: \"dueDate 匹配 PROJECT_DEADLINE (2026-12-25)\"\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 服务状态失败:打印 CRITICAL 并返回 0.0 退出\"\n - \"G1 失败导致 G2 被跳过(无邮件可评估)\"\n - \"N1 失败导致 N2 被跳过(无页面可检查)\"\n - \"T1/T2 中若找不到 Lumira Biotech 卡片或相关列表,则对应组件失败\"\n - \"各组件内部异常被捕获,打印 ERROR 且该组件不得分,但不中断后续评分\"\n- scoring_logic_explanation: 需要详细中文解释,按执行顺序。\n- confidence: 1.0\n\n确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我再检查一下 weight 总和:0.20+0.15+0.30+0.35 = 1.0。N1+N2=0.30, T1+T2=0.35。正确。\n\nJSON 字符串中的双引号需要转义。我直接输出 JSON。\n\n再确认一下 data_sources,代码中明确使用了:\n- `/tmp/task_web_sid`\n- `http://28.7.186.212:8138` (gmail)\n- `http://28.7.186.212:8166` (notion)\n- `http://28.7.186.212:8182` (trello)\n\n我可以写 [\"gmail_mock\", \"notion_mock\", \"trello_mock\", \"/tmp/task_web_sid\"] 或者包含 URL。用户示例里有 \"slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid\",所以我写 mock 服务名和文件路径即可。\n\n再确认一下 domain,docstring 写的是 \"mock_websites (multi-mock: gmail_mock, notion_mock, trello_mock)\",domain 应该是 \"mock_websites\"。\n\n再确认 task_id: \"csm_onboarding_kickoff_002\"。\n\n确认 is_placeholder: false。\n\n确认所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。所以 description、check_logic、pass_condition 等用中文,但代码中的字段名如 `folder`、`to`、`subject`、`parentId`、`listId`、`cardIds`、`dueDate` 等保留原样。\n\n让我组织一下 JSON 内容。 {\"task_id\":\"csm_onboarding_kickoff_002\",\"domain\":\"mock_websites\",\"summary\":\"验证 Lumira Biotech 的 CSM 入职启动任务:通过 Gmail 发送欢迎邮件、在 Notion 的 Customer Onboarding 下新建含清单的页面、在 Trello 将 Lumira Biotech 卡片从 New 移至 In Progress 并设置截止日期 2026-12-25\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"gmail_mock\",\"notion_mock\",\"trello_mock\"],\"scoring_components\":[{\"name\":\"G1\",\"weight\":0.2,\"description\":\"Gmail 中发送给正确联系人的新邮件\",\"check_logic\":\"对比 gmail_init 与 gmail_cur 的 emails,筛选 id 不在初始集合中、folder 为 'sent'、收件人 to 中包含 TARGET_EMAIL (maya.cho@lumirabiotech.com) 且 subject 非空的新邮件;排除 DISTRACTOR_EMAIL\",\"pass_condition\":\"存在至少一封满足条件的新 sent 邮件\"},{\"name\":\"G2\",\"weight\":0.15,\"description\":\"欢迎邮件正文介绍 CSM 并确认启动入职\",\"check_logic\":\"以 G1 通过的邮件为评估对象,将其 subject 与 body 拼接为 blob,通过 contains_any_phrase 检查是否包含 'jordan'/'jordan rivera'/'rivera'(introduces_csm),以及是否包含 onboarding/kickoff 相关短语列表中的任意一项(confirms_kickoff)\",\"pass_condition\":\"introduces_csm 与 confirms_kickoff 同时为 True\"},{\"name\":\"N1\",\"weight\":0.15,\"description\":\"Notion 中在 Customer Onboarding 下新建引用 Lumira Biotech 的页面\",\"check_logic\":\"先从 notion_init 中定位标题为 'Customer Onboarding' 的页面 id;再在 notion_cur.pages 中查找 id 为新增、parentId 匹配该 id、且标题通过 contains_all_terms 同时包含 'lumira' 与 'biotech' 的页面\",\"pass_condition\":\"存在至少一个满足条件的新页面\"},{\"name\":\"N2\",\"weight\":0.15,\"description\":\"新建页面包含至少 5 个清单/待办/列表块\",\"check_logic\":\"以 N1 通过的页面为对象,遍历其 blockIds,在 notion_cur.blocks 中查找对应 block,统计 type(转小写后)属于 {'todo','to-do','bullet-list','numbered-list','checkbox'} 的数量\",\"pass_condition\":\"统计数量 >= 5\"},{\"name\":\"T1\",\"weight\":0.2,\"description\":\"Trello 中 Lumira Biotech 卡片从 New 移至 In Progress\",\"check_logic\":\"在 trello_cur.cards 中找到标题含 'lumira' 与 'biotech' 的卡片;在其 board 上定位标题为 'new' 与 'in progress' 的列表 id;验证初始状态该卡片 listId 为 new_lid 且 cardId 在 init_lists[new_lid].cardIds 中,当前状态 listId 为 inprogress_lid 且 cardId 在 cur_lists[inprogress_lid].cardIds 中,同时初始与当前 listId 不同且当前已不在 new_lid 的 cardIds 中\",\"pass_condition\":\"initially_in_new、list_changed、in_inprogress、not_in_new 全部为 True\"},{\"name\":\"T2\",\"weight\":0.15,\"description\":\"Trello 卡片截止日期设为项目截止日期\",\"check_logic\":\"获取 lumira_card 的 dueDate,通过 due_date_matches 检查是否以 2026-12-25 开头,或匹配 MM/DD/YYYY、MM-DD-YYYY、YYYY/MM/DD 等常见格式开头\",\"pass_condition\":\"dueDate 匹配 PROJECT_DEADLINE (2026-12-25)\"}],\"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 服务状态失败:打印 CRITICAL 并返回 0.0 退出\",\"G1 失败导致 G2 被跳过(无邮件可评估)\",\"N1 失败导致 N2 被跳过(无页面可检查)\",\"T1/T2 中若找不到 Lumira Biotech 卡片或相关列表,则对应组件失败\",\"各组件内部异常被捕获,打印 ERROR 且该组件不得分,但不中断后续评分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0;随后通过 HTTP 分别拉取 gmail_mock、notion_mock、trello_mock 的 initial_state 与 current_state,拉取失败也直接返回 0.0。评分按顺序执行六个组件:G1 检查 Gmail 当前状态相比初始状态是否存在发给 maya.cho@lumirabiotech.com 的新 sent 邮件且主题非空;若 G1 通过,G2 进一步检查该邮件的主题与正文是否同时提到 CSM Jordan Rivera 并确认 onboarding/kickoff。Notion 部分先从初始状态锁定 'Customer Onboarding' 页面 id,N1 检查当前状态是否出现以该页面为 parentId 且标题包含 Lumira Biotech 的新页面;若 N1 通过,N2 统计该新页面的 blockIds 中 checklist/to-do/bullet/numbered-list/checkbox 类型块的数量是否不少于 5 个。Trello 部分先定位标题含 Lumira Biotech 的当前卡片及其 board 上的 New 与 In Progress 列表,T1 验证该卡片初始位于 New 列表、当前位于 In Progress 列表且 listId 确实发生变更;T2 验证该卡片的 dueDate 是否为项目截止日期 2026-12-25。各组件得分累加,最终通过 min(total_score, 1.0) 钳制并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/csops_slack_to_jira_001/_cua_gym_vm_bridge.sh b/legacy/csops_slack_to_jira_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/csops_slack_to_jira_001/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/csops_slack_to_jira_001/initial_setup.py b/legacy/csops_slack_to_jira_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..cd23e7d8cd5d10e98721e58ea045edcd2664183c --- /dev/null +++ b/legacy/csops_slack_to_jira_001/initial_setup.py @@ -0,0 +1,538 @@ +# --- 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.186.212"): + 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: Slack support escalation untracked; Jira SUP project ready (no CSV-500 bug yet) +Task ID: csops_slack_to_jira_001 +Domain: mock_websites +Mocks: slack_mock, jira_mock +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Config --- +SLACK_URL = 'http://28.7.186.212:8198' +JIRA_URL = 'http://28.7.186.212:8173' + +sid = str(uuid.uuid4()) + +# --- Egress proxy helper (MANDATORY §1.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 + raise RuntimeError('No working route to mock servers; direct and proxy attempts failed') + + +PROXY = resolve_proxy(f'{SLACK_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +def get_json(url, attempts=4): + """GET with retry + JSON parse guard against transient empty/non-JSON responses.""" + last = None + for _ in range(attempts): + try: + r = requests.get(url, timeout=15, proxies=PROXIES) + if r.status_code == 200 and r.text.strip(): + return r.json() + last = f'status={r.status_code} body={r.text[:120]!r}' + except Exception as e: + last = str(e) + time.sleep(1.5) + raise RuntimeError(f'get_json failed for {url}: {last}') + + +# --- Persist sid --- +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid={sid}') + + +# ============================================================ +# SLACK STATE +# ============================================================ +def build_slack_state(): + def user(uid, full, disp, email, title, rnd): + return { + 'userId': uid, 'fullName': full, 'displayName': disp, 'email': email, + 'avatar': f'https://picsum.photos/200/200?random={rnd}', 'title': title, + 'status': 'online', 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York', + } + + users = [ + user('user_1', 'John Smith', 'John', 'john.smith@acme.com', 'Support Engineering Lead', 1), + user('user_2', 'Sarah Johnson', 'Sarah', 'sarah.johnson@acme.com', 'Engineering Manager', 2), + user('user_3', 'Maria Lopez', 'Maria', 'maria.lopez@acme.com', 'Support Agent', 3), + user('user_4', 'David Kim', 'David', 'david.kim@acme.com', 'Account Manager', 4), + user('user_5', 'Tom Reyes', 'Tom', 'tom.reyes@acme.com', 'Support Agent', 5), + user('user_6', 'Priya Nair', 'Priya', 'priya.nair@acme.com', 'Customer Success', 6), + ] + current_user = dict(users[0]) + member_ids = [u['userId'] for u in users] + + channels = [ + {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', + 'topic': 'Welcome to Acme Corp', 'isPrivate': False, 'isStarred': False, + 'members': member_ids, 'createdBy': 'user_1', 'createdAt': '2025-09-01T09:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'support-escalations', 'name': 'support-escalations', + 'description': 'Customer escalations needing engineering attention', + 'topic': 'Escalate P1/P2 customer issues here', 'isPrivate': False, 'isStarred': True, + 'members': member_ids, 'createdBy': 'user_3', 'createdAt': '2025-10-15T08:30:00Z', + 'pinnedMessages': [], 'unreadCount': 2}, + {'channelId': 'random', 'name': 'random', 'description': 'Watercooler chat', + 'topic': '', 'isPrivate': False, 'isStarred': False, + 'members': member_ids, 'createdBy': 'user_2', 'createdAt': '2025-09-01T09:05:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + ] + + esc_content = ( + "Escalation from customer Northwind Logistics. Customer-stated urgency: high. " + "Their bulk CSV contact import returns a 500 error every time the file has more " + "than 5,000 rows. Started right after we shipped release 3.4. Fully reproducible." + ) + + def msg(mid, sender, content, ts, thread_id=None): + return { + 'messageId': mid, 'senderId': sender, 'content': content, 'timestamp': ts, + 'threadId': thread_id, 'reactions': [], 'attachments': [], 'isEdited': False, + } + + support_msgs = [ + # Unrelated billing chatter (earlier) + msg('msg_b1', 'user_4', + "Quick one for finance — is the Globex invoice for May supposed to include the " + "overage line item? Customer is asking.", '2026-06-22T15:10:00Z'), + # The escalation parent (has a thread) + msg('msg_esc', 'user_3', esc_content, '2026-06-23T09:42:00Z', thread_id='thread_esc'), + # Thread reply 1 (Maria repro) + msg('msg_esc_r1', 'user_3', + "Repro: Contacts > Import > upload a 6k-row CSV > error toast 'Server error 500', " + "nothing imports.", '2026-06-23T09:48:00Z', thread_id='thread_esc'), + # Thread reply 2 (Tom confirm) + msg('msg_esc_r2', 'user_5', + "Confirmed on my side with a 5,200-row file. Imports under 5k rows still work.", + '2026-06-23T10:05:00Z', thread_id='thread_esc'), + # Unrelated 'thanks' chatter (later, top-level) + msg('msg_t1', 'user_6', + "thanks! the workaround for the SSO redirect loop worked perfectly for that account.", + '2026-06-23T11:20:00Z'), + ] + + threads = { + 'thread_esc': { + 'threadId': 'thread_esc', + 'parentMessageId': 'msg_esc', + 'channelId': 'support-escalations', + 'dmId': None, + 'replies': ['msg_esc_r1', 'msg_esc_r2'], + 'followers': ['user_3', 'user_5'], + } + } + + return { + 'currentUser': current_user, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'users': users, + 'channels': channels, + 'messages': { + 'general': [ + msg('msg_g1', 'user_2', "Reminder: release 3.4 went out last week. Please flag any " + "regressions in #support-escalations.", '2026-06-18T16:00:00Z'), + ], + 'support-escalations': support_msgs, + 'random': [ + msg('msg_r1', 'user_6', "Anyone up for coffee at 3?", '2026-06-23T14:00:00Z'), + ], + }, + 'threads': threads, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', + 'showAvatars': True, 'use24Hour': False}, + 'invitations': [], + 'notifications': [], + } + + +# ============================================================ +# JIRA STATE (fetch default base, augment with SUP project) +# ============================================================ +def build_jira_state(): + # Fetch the server default state as the base so KAN/SCRUM/sprints/workflows exist. + base = {} + try: + d = get_json(f'{JIRA_URL}/go?sid=jira-default-probe') + base = d.get('current_state') or d.get('initial_state') or {} + except Exception as e: + print(f'WARN: could not fetch jira default base ({e}); building minimal base') + base = {} + + base.setdefault('users', []) + base.setdefault('projects', []) + base.setdefault('issues', []) + base.setdefault('sprints', []) + base.setdefault('comments', []) + base.setdefault('notifications', []) + base.setdefault('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']}, + ] + }]) + if not base.get('currentUser'): + base['currentUser'] = {'id': 'u1', 'name': 'Admin User', + 'email': 'admin@acme.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'} + + # Ensure default users exist (u1 Admin, u2 Jane Doe, u3 John, u4 Sarah) + existing_user_ids = {u.get('id') for u in base['users']} + defaults = [ + {'id': 'u1', 'name': 'Admin User', 'email': 'admin@acme.com'}, + {'id': 'u2', 'name': 'Jane Doe', 'email': 'jane.doe@acme.com'}, + {'id': 'u3', 'name': 'John Carter', 'email': 'john.carter@acme.com'}, + {'id': 'u4', 'name': 'Sarah Bell', 'email': 'sarah.bell@acme.com'}, + ] + for u in defaults: + if u['id'] not in existing_user_ids: + u['avatar'] = f"https://picsum.photos/100/100?random={u['id']}" + base['users'].append(u) + existing_user_ids.add(u['id']) + + # Add the data-import/platform engineer Raj Patel (u_eng) + if 'u_eng' not in existing_user_ids: + base['users'].append({ + 'id': 'u_eng', 'name': 'Raj Patel', 'email': 'raj.patel@acme.com', + 'avatar': 'https://picsum.photos/100/100?random=ueng', + }) + + # Add Support Engineering project (SUP) if missing + proj_ids = {p.get('id') for p in base['projects']} + if 'p_sup' not in proj_ids: + base['projects'].append({ + 'id': 'p_sup', 'key': 'SUP', 'name': 'Support Engineering', + 'leadId': 'u_eng', 'category': 'Software', + 'icon': 'https://picsum.photos/64/64?random=psup', + }) + + # Add an active sprint for SUP + sprint_ids = {s.get('id') for s in base['sprints']} + if 's_sup' not in sprint_ids: + base['sprints'].append({ + 'id': 's_sup', 'projectId': 'p_sup', 'name': 'SUP Sprint 7', + 'goal': 'Burn down customer escalations and reduce P1 backlog', + 'startDate': '2026-06-15T12:00:00.000Z', 'endDate': '2026-06-29T12:00:00.000Z', + 'state': 'active', + }) + + # Add 8 existing, UNRELATED SUP issues (SUP-1..SUP-8). None about CSV import 500. + ts = '2026-06-16T10:00:00.000Z' + sup_issues = [ + ('i_sup_1', 'SUP-1', 'Investigate intermittent timeout on SSO login', 'Task', + 'In Progress', 'High', 'u_eng', 3), + ('i_sup_2', 'SUP-2', 'Add retry logic to webhook delivery on 5xx', 'Story', + 'To Do', 'Medium', 'u2', 5), + ('i_sup_3', 'SUP-3', 'Customer reports dashboard load exceeding 3 seconds', 'Bug', + 'In Progress', 'High', 'u_eng', 5), + ('i_sup_4', 'SUP-4', 'Document the on-call escalation runbook', 'Task', + 'Done', 'Low', 'u2', 2), + ('i_sup_5', 'SUP-5', 'PDF export missing footer on landscape pages', 'Bug', + 'To Do', 'Medium', 'u3', 3), + ('i_sup_6', 'SUP-6', 'Improve error messaging on failed payment retry', 'Story', + 'In Review', 'Medium', 'u4', 3), + ('i_sup_7', 'SUP-7', 'Enforce rate limiting for free-tier API accounts', 'Task', + 'To Do', 'Low', 'u_eng', 2), + ('i_sup_8', 'SUP-8', 'Search returns stale results after bulk update', 'Bug', + 'In Progress', 'High', 'u2', 5), + ] + existing_issue_keys = {i.get('key') for i in base['issues']} + for iid, key, summary, itype, status, prio, assignee, sp in sup_issues: + if key in existing_issue_keys: + continue + base['issues'].append({ + 'id': iid, 'key': key, 'projectId': 'p_sup', 'summary': summary, + 'description': '', 'type': itype, 'status': status, 'priority': prio, + 'storyPoints': sp, 'reporterId': 'u1', 'assigneeId': assignee, + 'sprintId': 's_sup' if status != 'Done' else None, 'epicId': None, + 'labels': [], 'subtasks': [], 'linkedIssueIds': [], + 'createdAt': ts, 'updatedAt': ts, + }) + + return base + + +# ============================================================ +# Inject state into both mocks +# ============================================================ +def inject(url, state, 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 = get_json(f'{url}/go?sid={sid}') + assert go.get('initial_state') is not None, f'{name} initial_state is None after injection' + print(f'{name}: state injected and verified') + + +inject(SLACK_URL, build_slack_state(), 'slack') +inject(JIRA_URL, build_jira_state(), 'jira') + + +# ============================================================ +# Launch browser (GUI-ready) +# ============================================================ +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 app: Slack (where the escalation lives) +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=2.0) +# Secondary app: Jira (where the bug must be filed) +launch_gui(f'google-chrome "{JIRA_URL}/?sid={sid}"', delay_sec=2.0) +wait_mocks_loaded() +print(f'GUI_READY: launched Slack and Jira with sid={sid}') diff --git a/legacy/csops_slack_to_jira_001/reward.py b/legacy/csops_slack_to_jira_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d5282e3abc215939fab461d6fa245ba7052031 --- /dev/null +++ b/legacy/csops_slack_to_jira_001/reward.py @@ -0,0 +1,487 @@ +# --- 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.186.212"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +""" +Reward Script: Capture a Slack customer escalation as a Jira bug and close the loop in the thread. +Task ID: csops_slack_to_jira_001 +Domain: mock_websites (multi-mock: slack_mock + jira_mock) + +Scoring rubric (all task-introduced changes; each fails on initial_env, passes on golden_env): + JIRA (0.60): + A1 (0.15) A NEW issue exists in the SUP project with type 'Bug' + A2 (0.15) That new bug's summary identifies the bulk CSV import 500 error + A3 (0.10) That new bug's priority is 'High' + A4 (0.10) That new bug is assigned to the data-import engineer Raj Patel (assigneeId 'u_eng') + A5 (0.10) That new bug's description records Northwind, high urgency, release 3.4, and the >5,000-row trigger + SLACK (0.40): + B1 (0.20) A NEW reply was posted in the SAME escalation thread (thread_esc / Northwind message) + B2 (0.20) That new reply contains the newly-created Jira issue key (e.g. 'SUP-9') + +All checks are programmatic with normalized text and regex matching. No LLM judge needed. +""" +import os +import re +import sys + +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) + +SLACK_URL = 'http://28.7.186.212:8198' +JIRA_URL = 'http://28.7.186.212:8173' + +# --- 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'{JIRA_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +def fetch(url): + """Fetch /go state for a mock. Returns (initial, current) or (None, None) on failure.""" + try: + data = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json() + return data.get('initial_state') or {}, data.get('current_state') or {} + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {url}/go?sid={sid}: {e}') + return None, None + + +# --- Fetch both mocks --- +jira_init, jira_cur = fetch(JIRA_URL) +slack_init, slack_cur = fetch(SLACK_URL) + +if jira_cur is None or slack_cur is None: + print('REWARD: 0.0') + sys.exit(0) + + +def norm_text(value): + """Normalize user-entered text for resilient keyword checks.""" + text = str(value or '').lower() + text = text.replace('>', '>') + for hyphen in ('\u2010', '\u2011', '\u2012', '\u2013', '\u2014', '\u2212'): + text = text.replace(hyphen, '-') + return re.sub(r'[^a-z0-9+#>.<-]+', ' ', text) + + +def has_csv_signal(text): + t = norm_text(text) + return bool(re.search(r'\bcsv\b', t) or 'comma separated' in t) + + +def has_import_signal(text): + t = norm_text(text) + return bool(re.search( + r'\b(import|imports|imported|importing|upload|uploads|uploaded|uploading|ingest|ingestion)\b', + t, + )) + + +def has_500_error_signal(text): + t = norm_text(text) + return bool(re.search(r'\b500\b', t) or 'internal server error' in t or 'server error' in t) + + +def has_csv500_summary(text): + return has_csv_signal(text) and has_import_signal(text) and has_500_error_signal(text) + + +def has_customer_signal(text): + t = norm_text(text) + return 'northwind' in t + + +def has_urgency_signal(text): + t = norm_text(text) + return bool( + re.search(r'\bhigh\b', t) + or re.search(r'\bp\s*1\b', t) + or re.search(r'\b(urgent|critical|severe)\b', t) + ) + + +def has_release_34_signal(text): + t = norm_text(text) + return bool(re.search(r'\b(?:release|version|ver|v)?\s*3\s*[.-]\s*4\b', t)) + + +def has_row_threshold_signal(text): + t = str(text or '').lower().replace(',', ' ') + t = t.replace('>', '>') + for hyphen in ('\u2010', '\u2011', '\u2012', '\u2013', '\u2014', '\u2212'): + t = t.replace(hyphen, '-') + compact = re.sub(r'\s+', ' ', t) + threshold = r'(?:5\s*000|5000|5\s*k)' + row_unit = r'(?:rows?|records?|lines?)' + comparator = r'(?:>|>=|more than|over|above|greater than|exceeds?|exceeding|larger than|beyond)' + if re.search(comparator + r'\s*(?:about\s*)?' + threshold, compact): + return True + if re.search(threshold + r'\s*\+\s*(?:' + row_unit + r')?', compact): + return True + if re.search(threshold + r'\s*(?:-| )?\s*' + row_unit, compact) and re.search( + r'\b(trigger|threshold|limit|fail|fails|failing|error|breaks?|repro|reproducible)\b', + norm_text(compact), + ): + return True + # Accept concrete repro counts above 5,000 when the row unit is explicit. + return bool(re.search( + r'\b(?:5\s*[1-9]\d{2}|[6-9]\s*000|[6-9]\s*k)\s*(?:-| )?\s*' + row_unit, + compact, + )) + + +def is_sup_issue(issue, state): + project_id = issue.get('projectId') + project = next((p for p in state.get('projects', []) or [] if p.get('id') == project_id), {}) + key = norm_text(issue.get('key')).replace(' ', '') + return ( + project_id == 'p_sup' + or (project.get('key') or '').lower() == 'sup' + or 'support engineering' in norm_text(project.get('name')) + or key.startswith('sup-') + or bool(re.match(r'^sup\d+$', key)) + ) + + +def is_bug_type(issue): + return norm_text(issue.get('type')).strip() == 'bug' + + +def is_high_priority(issue): + return norm_text(issue.get('priority')).strip() == 'high' + + +def raj_user_ids(state): + ids = {'u_eng'} + for user in state.get('users', []) or []: + name = norm_text(user.get('name')) + email = norm_text(user.get('email')) + if ('raj' in name and 'patel' in name) or 'raj.patel' in email: + uid = user.get('id') + if uid: + ids.add(uid) + return ids + + +def is_assigned_to_raj(issue, state): + assignee = issue.get('assigneeId') + if assignee in raj_user_ids(state): + return True + assignee_text = norm_text(assignee) + return 'raj' in assignee_text and 'patel' in assignee_text + + +def description_has_required_facts(issue): + desc = issue.get('description') or '' + return { + 'customer': has_customer_signal(desc), + 'urgency': has_urgency_signal(desc), + 'release': has_release_34_signal(desc), + 'threshold': has_row_threshold_signal(desc), + } + + +def issue_signal_score(issue, state): + text = f"{issue.get('summary') or ''}\n{issue.get('description') or ''}" + facts = description_has_required_facts(issue) + return sum([ + has_csv500_summary(issue.get('summary')), + has_csv_signal(text), + has_import_signal(text), + has_500_error_signal(text), + has_customer_signal(text), + has_urgency_signal(text), + has_release_34_signal(text), + has_row_threshold_signal(text), + is_high_priority(issue), + is_assigned_to_raj(issue, state), + all(facts.values()), + ]) + + +def new_current_issues(initial_state, current_state): + init_ids = {i.get('id') for i in initial_state.get('issues', []) or [] if i.get('id')} + init_keys = {norm_text(i.get('key')).replace(' ', '') for i in initial_state.get('issues', []) or [] if i.get('key')} + issues = [] + for issue in current_state.get('issues', []) or []: + issue_id = issue.get('id') + issue_key = norm_text(issue.get('key')).replace(' ', '') + if (issue_id and issue_id not in init_ids) or (issue_key and issue_key not in init_keys): + issues.append(issue) + return issues + + +def best_issue(issues, state): + if not issues: + return None + return sorted(issues, key=lambda issue: issue_signal_score(issue, state), reverse=True)[0] + + +def all_slack_messages(state, channel_id=None): + messages = [] + for bucket, bucket_messages in (state.get('messages', {}) or {}).items(): + if channel_id is not None and bucket != channel_id: + continue + for message in bucket_messages or []: + messages.append(message) + return messages + + +def support_channel_id(state): + for channel in state.get('channels', []) or []: + if (channel.get('name') or '').lstrip('#').lower() == 'support-escalations': + return channel.get('channelId') + return 'support-escalations' + + +def user_name_by_id(state): + return { + u.get('userId'): norm_text(f"{u.get('fullName') or ''} {u.get('displayName') or ''}") + for u in state.get('users', []) or [] + } + + +def find_source_thread_id(state): + channel_id = support_channel_id(state) + names = user_name_by_id(state) + candidates = [] + for message in all_slack_messages(state, channel_id): + content = message.get('content') or '' + score = sum([ + has_customer_signal(content), + has_urgency_signal(content), + has_csv_signal(content), + has_import_signal(content), + has_500_error_signal(content), + has_release_34_signal(content), + bool(message.get('threadId')), + 'maria' in names.get(message.get('senderId'), ''), + ]) + if score >= 5: + candidates.append((score, message)) + if not candidates: + return 'thread_esc' + candidates.sort(key=lambda item: item[0], reverse=True) + return candidates[0][1].get('threadId') or 'thread_esc' + + +def new_reply_contents_in_thread(initial_state, current_state, thread_id): + init_message_ids = {m.get('messageId') for m in all_slack_messages(initial_state) if m.get('messageId')} + init_thread = (initial_state.get('threads', {}) or {}).get(thread_id, {}) or {} + cur_thread = (current_state.get('threads', {}) or {}).get(thread_id, {}) or {} + init_reply_ids = set(init_thread.get('replies', []) or []) + cur_reply_ids = set(cur_thread.get('replies', []) or []) + new_thread_reply_ids = cur_reply_ids - init_reply_ids + + contents = [] + seen = set() + for message in all_slack_messages(current_state): + message_id = message.get('messageId') + is_new_message = message_id and message_id not in init_message_ids + is_thread_reply = message.get('threadId') == thread_id or message_id in new_thread_reply_ids + if is_new_message and is_thread_reply and message_id not in seen: + contents.append(message.get('content') or '') + seen.add(message_id) + return contents + + +def issue_key_matches(content, key): + match = re.match(r'\s*([A-Za-z]+)\W*0*([0-9]+)\s*$', str(key or '')) + if not match: + return False + project, number = match.groups() + text = str(content or '').lower() + for hyphen in ('\u2010', '\u2011', '\u2012', '\u2013', '\u2014', '\u2212'): + text = text.replace(hyphen, '-') + pattern = ( + r'\b' + re.escape(project.lower()) + + r'\s*(?:[-#:\s]+|issue\s+|ticket\s+|bug\s+)?0*' + + re.escape(number) + r'\b' + ) + return bool(re.search(pattern, text)) + + +def verify_task(): + total_score = 0.0 + + # ===================== JIRA (0.60) ===================== + # Identify the best NEW SUP Bug introduced by the task. The issue key and + # timestamps are dynamic, so detection is based on initial/current deltas + # plus robust matches for the known customer-escalation signals. + target_issue = None + summary_matches = [] + new_sup_bugs = [] + target_key = None + try: + new_issues = new_current_issues(jira_init, jira_cur) + new_sup_bugs = [ + i for i in new_issues + if is_sup_issue(i, jira_cur) and is_bug_type(i) + ] + summary_matches = [i for i in new_sup_bugs if has_csv500_summary(i.get('summary'))] + target_issue = best_issue(summary_matches or new_sup_bugs, jira_cur) + if target_issue: + target_key = target_issue.get('key') + except Exception as e: + print(f'ERROR: Jira new-bug identification — {e}') + + # Component A1: a NEW issue in SUP project with type Bug (0.15) + try: + if new_sup_bugs: + print(f'PASS: A1 — new SUP Bug created: {[b.get("key") for b in new_sup_bugs]} (0.15 pts)') + total_score += 0.15 + else: + print('FAIL: A1 — no NEW Bug issue found in SUP project') + except Exception as e: + print(f'ERROR: A1 — {e}') + + # Component A2: summary identifies the bulk CSV import 500 error (0.15) + try: + if summary_matches: + print( + f'PASS: A2 — new bug summary identifies CSV import 500 error: ' + f'"{summary_matches[0].get("summary")}" (0.15 pts)' + ) + total_score += 0.15 + else: + summary = target_issue.get('summary') if target_issue else None + print( + 'FAIL: A2 — no new SUP Bug summary flexibly mentions CSV, ' + f'import/upload, AND 500/server error. Best summary: {summary}' + ) + except Exception as e: + print(f'ERROR: A2 — {e}') + + # Component A3: priority is 'High' (0.10) + try: + if target_issue is not None and is_high_priority(target_issue): + print(f'PASS: A3 — new bug priority is High (0.10 pts)') + total_score += 0.10 + else: + pr = target_issue.get('priority') if target_issue else None + print(f'FAIL: A3 — expected priority High on the new bug, found: {pr}') + except Exception as e: + print(f'ERROR: A3 — {e}') + + # Component A4: assigned to data-import engineer Raj Patel (assigneeId 'u_eng') (0.10) + try: + if target_issue is not None and is_assigned_to_raj(target_issue, jira_cur): + print(f'PASS: A4 — new bug assigned to Raj Patel (u_eng) (0.10 pts)') + total_score += 0.10 + else: + asn = target_issue.get('assigneeId') if target_issue else None + print(f'FAIL: A4 — expected assigneeId u_eng on the new bug, found: {asn}') + except Exception as e: + print(f'ERROR: A4 — {e}') + + # Component A5: description records customer Northwind, high urgency, release 3.4, and >5,000-row trigger (0.10) + try: + if target_issue is not None: + facts = description_has_required_facts(target_issue) + if all(facts.values()): + print('PASS: A5 — description records Northwind, high urgency, release 3.4, and >5,000-row trigger (0.10 pts)') + total_score += 0.10 + else: + print(f'FAIL: A5 — description missing facts ' + f'(northwind={facts["customer"]}, urgency={facts["urgency"]}, ' + f'3.4={facts["release"]}, >5000={facts["threshold"]})') + else: + print('FAIL: A5 — no new bug to inspect description') + except Exception as e: + print(f'ERROR: A5 — {e}') + + # ===================== SLACK (0.40) ===================== + # Identify NEW replies in the SAME Slack escalation source thread. The + # source thread is detected from the initial Northwind/CSV/500/high/release + # message rather than relying only on the seeded thread id. + new_reply_contents = [] + source_thread_id = 'thread_esc' + try: + source_thread_id = find_source_thread_id(slack_init) + new_reply_contents = new_reply_contents_in_thread(slack_init, slack_cur, source_thread_id) + except Exception as e: + print(f'ERROR: Slack new-reply identification — {e}') + + # Component B1: a NEW reply was posted in the same escalation thread (0.20) + try: + if new_reply_contents: + print( + f'PASS: B1 — {len(new_reply_contents)} new reply(ies) in ' + f'escalation thread {source_thread_id} (0.20 pts)' + ) + total_score += 0.20 + else: + print(f'FAIL: B1 — no new reply found in the Northwind escalation thread ({source_thread_id})') + except Exception as e: + print(f'ERROR: B1 — {e}') + + # Component B2: that new reply contains the newly-created Jira issue key (0.20) + try: + matched = False + if new_reply_contents: + for content in new_reply_contents: + if target_key and issue_key_matches(content, target_key): + matched = True + print(f'PASS: B2 — new reply references the new Jira issue key "{target_key}" (0.20 pts)') + break + if matched: + total_score += 0.20 + else: + want = target_key or 'the newly-created matching Jira issue key' + print(f'FAIL: B2 — no new reply contains the Jira issue key ({want}). ' + f'Replies: {new_reply_contents}') + else: + print('FAIL: B2 — no new reply to inspect for Jira key') + except Exception as e: + print(f'ERROR: B2 — {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/legacy/csops_slack_to_jira_001/reward_label.json b/legacy/csops_slack_to_jira_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..7125c5501e1734fbf59b4d19531d97056c9b4b54 --- /dev/null +++ b/legacy/csops_slack_to_jira_001/reward_label.json @@ -0,0 +1,83 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csops_slack_to_jira_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:26:58", + "label": { + "task_id": "csops_slack_to_jira_001", + "domain": "mock_websites", + "summary": "验证用户是否在 Jira SUP 项目中正确创建了关于 CSV 导入 500 错误的 Bug 并填写所需字段,同时在 Slack escalation 线程中回复并引用该 Jira issue key。", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8173 (jira_mock)", + "http://28.7.186.212:8198 (slack_mock)" + ], + "scoring_components": [ + { + "name": "A1", + "weight": 0.15, + "description": "在 SUP 项目中创建了新的 Bug 类型 issue", + "check_logic": "通过 new_current_issues 对比 jira_init 与 jira_cur 找出新增 issues,再筛选满足 is_sup_issue 且 is_bug_type 的 issue;若所得 new_sup_bugs 列表非空则通过", + "pass_condition": "存在至少一个新增的 SUP 项目 Bug 类型 issue" + }, + { + "name": "A2", + "weight": 0.15, + "description": "新 Bug 的 summary 识别出批量 CSV 导入 500 错误", + "check_logic": "在 new_sup_bugs 中筛选 summary 同时包含 csv、import/upload、500/server error 信号的 issue(has_csv500_summary);若 summary_matches 非空则通过", + "pass_condition": "新 SUP Bug 的 summary 同时包含 CSV、导入/上传和 500/服务器错误关键词" + }, + { + "name": "A3", + "weight": 0.1, + "description": "新 Bug 的优先级为 High", + "check_logic": "对 target_issue(优先从 summary_matches 选取,否则从 new_sup_bugs 中按 issue_signal_score 取最佳)检查 priority 字段归一化后是否等于 'high'", + "pass_condition": "target_issue 的 priority 为 High" + }, + { + "name": "A4", + "weight": 0.1, + "description": "新 Bug 分配给数据导入工程师 Raj Patel", + "check_logic": "检查 target_issue 的 assigneeId 是否在 raj_user_ids 集合中(包含 'u_eng' 或用户名/邮箱匹配 raj patel)", + "pass_condition": "target_issue 的 assigneeId 为 'u_eng' 或对应 Raj Patel" + }, + { + "name": "A5", + "weight": 0.1, + "description": "新 Bug 的描述记录客户 Northwind、高紧急度、release 3.4 和超过 5000 行触发条件", + "check_logic": "对 target_issue 的 description 分别调用 has_customer_signal、has_urgency_signal、has_release_34_signal、has_row_threshold_signal,四个信号必须全部为真", + "pass_condition": "description 同时包含 Northwind、high urgency、release 3.4、>5,000-row trigger 四个事实" + }, + { + "name": "B1", + "weight": 0.2, + "description": "在同一 escalation 线程中发布了新的回复", + "check_logic": "通过 find_source_thread_id 在 slack_init 中依据 Northwind/CSV/500/high/release 3.4/Maria 等信号定位源线程,再对比 initial/current 状态提取该线程的新增回复内容列表;若 new_reply_contents 非空则通过", + "pass_condition": "在 Northwind escalation 线程中至少有一条新增回复" + }, + { + "name": "B2", + "weight": 0.2, + "description": "新回复中包含新创建的 Jira issue key", + "check_logic": "遍历 new_reply_contents,使用 issue_key_matches 检查是否有回复内容通过正则匹配 target_key(如 SUP-9)的引用模式", + "pass_condition": "至少一条新回复引用了新创建的 Jira issue key" + } + ], + "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 后 sys.exit(0)", + "无法从 JIRA mock 或 Slack mock 获取 current_state(返回 None)时,输出 REWARD: 0.0 后 sys.exit(0)", + "未找到新的 SUP Bug 时,A1-A5 组件均无法得分", + "A2 中 summary 缺少 CSV、import 或 500 任一信号则不得分", + "A5 中 description 缺少 Northwind、urgency、release 3.4、>5000 rows 任一事实则不得分", + "未在 escalation 线程找到新回复时,B1-B2 均无法得分", + "B2 中回复内容未匹配 target_key 格式则不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后通过 HTTP GET 请求拉取 JIRA 和 Slack mock 的 initial_state 与 current_state,任一拉取失败也返回 0.0。在 JIRA 侧,脚本对比初始与当前状态提取新增 issues,筛选出 SUP 项目且类型为 Bug 的新 issue(A1,0.15);进一步检查这些新 Bug 的 summary 是否同时包含 CSV、import/upload、500/server error 关键词(A2,0.15),并在候选 issue 中按 issue_signal_score 选取最佳 target_issue,依次验证其 priority 是否为 High(A3,0.10)、assignee 是否为 Raj Patel/u_eng(A4,0.10)、description 是否同时包含 Northwind、high urgency、release 3.4 和 >5,000-row trigger(A5,0.10)。在 Slack 侧,脚本在 slack_init 中通过多信号匹配定位 Northwind escalation 源线程,对比 initial/current 提取该线程的新增回复(B1,0.20),再检查新回复中是否有内容通过正则引用了新创建的 Jira issue key(B2,0.20)。最后将各组件得分累加,经 min(score, 1.0) 钳制上限并四舍五入到 4 位小数后输出最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: `csops_slack_to_jira_001`(从 docstring 中明确提取)\n - Domain: `mock_websites`(从 docstring 中明确提取,multi-mock: slack_mock + jira_mock)\n\n2. **数据源**:\n - `/tmp/task_web_sid`:读取 sid\n - `http://28.7.186.212:8153`:JIRA mock\n - `http://28.7.186.212:8178`:Slack mock\n\n3. **评分组件**:\n - JIRA 部分(总分 0.60):\n - A1 (0.15):新的 SUP 项目 Bug 类型 issue\n - A2 (0.15):summary 包含 CSV import 500 error 信号\n - A3 (0.10):priority 是 High\n - A4 (0.10):assignee 是 Raj Patel (u_eng)\n - A5 (0.10):description 包含 Northwind, high urgency, release 3.4, >5,000-row trigger\n - SLACK 部分(总分 0.40):\n - B1 (0.20):在相同的 escalation thread 中有新的 reply\n - B2 (0.20):新 reply 包含新创建的 Jira issue key\n\n4. **评分聚合**:\n - 各组件分数相加\n - 最终 `final_score = round(min(total_score, 1.0), 4)`\n - 所以是相加后钳制到 1.0\n\n5. **失败模式**:\n - 读取 `/tmp/task_web_sid` 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 获取 jira_cur 或 slack_cur 为 None:打印 REWARD: 0.0,sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出(除了开头的关键失败)\n\n6. **is_placeholder**:\n - 不是占位脚本,它真正检查了 mock 状态。\n\n7. **confidence**:1.0,因为代码完整且逻辑清晰。\n\n现在构建 JSON:\n\n- task_id: \"csops_slack_to_jira_001\"\n- domain: \"mock_websites\"\n- summary: \"验证用户是否在 Jira 的 SUP 项目中创建了关于 CSV 导入 500 错误的新 Bug 并正确设置字段,同时在 Slack 的 escalation 线程中回复并引用该 Jira issue key。\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"http://28.7.186.212:8153 (jira_mock)\", \"http://28.7.186.212:8178 (slack_mock)\"]\n- scoring_components: 需要列出 7 个组件(A1-A5, B1-B2)\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0 并四舍五入到 4 位小数\"\n- failure_modes: [\"读取 /tmp/task_web_sid 失败或为空时打印 CRITICAL 并返回 0.0 退出\", \"无法从 JIRA 或 Slack mock 获取 current_state 时返回 0.0 退出\", \"未找到新的 SUP Bug 时 A1-A5 均不得分\", \"未在 escalation 线程找到新回复时 B1-B2 均不得分\"]\n- scoring_logic_explanation: 详细按执行顺序说明\n- confidence: 1.0\n\n让我再仔细检查一下每个组件的 check_logic:\n\n**A1**:\n- `new_issues = new_current_issues(jira_init, jira_cur)` 找出新 issues\n- `new_sup_bugs = [i for i in new_issues if is_sup_issue(i, jira_cur) and is_bug_type(i)]`\n- 如果 `new_sup_bugs` 非空,+0.15\n- `is_sup_issue` 检查 projectId == 'p_sup' 或 project.key == 'sup' 或 project.name 包含 'support engineering' 或 key 以 'sup-' 开头或匹配 `^sup\\d+$`\n- `is_bug_type` 检查 type 归一化后 == 'bug'\n\n**A2**:\n- `summary_matches = [i for i in new_sup_bugs if has_csv500_summary(i.get('summary'))]`\n- `has_csv500_summary` 要求同时包含 csv 信号、import 信号、500 error 信号\n- 如果 `summary_matches` 非空,+0.15\n- 否则如果 `target_issue`(best_issue)存在但 summary 不匹配,则失败\n\n**A3**:\n- `target_issue` 不为 None 且 `is_high_priority(target_issue)` 为真\n- `is_high_priority` 检查 priority 归一化后 == 'high'\n- +0.10\n\n**A4**:\n- `target_issue` 不为 None 且 `is_assigned_to_raj(target_issue, jira_cur)` 为真\n- 检查 assigneeId 在 `raj_user_ids` 中(包含 'u_eng' 或名字匹配 raj patel 的用户 id)\n- +0.10\n\n**A5**:\n- `target_issue` 不为 None\n- `description_has_required_facts(target_issue)` 返回字典,包含 customer, urgency, release, threshold\n- `all(facts.values())` 为真时 +0.10\n- 分别检查:\n - customer: `has_customer_signal` -> 'northwind'\n - urgency: `has_urgency_signal` -> 'high', 'p1', 'urgent', 'critical', 'severe'\n - release: `has_release_34_signal` -> 3.4 相关\n - threshold: `has_row_threshold_signal` -> >5,000 rows 相关\n\n**B1**:\n- `source_thread_id = find_source_thread_id(slack_init)` 从初始状态找 escalation thread\n- `new_reply_contents = new_reply_contents_in_thread(slack_init, slack_cur, source_thread_id)`\n- 如果 `new_reply_contents` 非空,+0.20\n\n**B2**:\n- 遍历 `new_reply_contents`\n- `target_key` 存在且 `issue_key_matches(content, target_key)` 为真\n- `issue_key_matches` 用正则匹配 Jira key 格式(如 SUP-9)在内容中的引用\n- 如果匹配,+0.20\n\n注意:target_issue 的选择逻辑:\n- 优先从 `summary_matches` 中选,如果没有则从 `new_sup_bugs` 中选,用 `best_issue` 按 `issue_signal_score` 排序选最高分。\n\n我需要确保 JSON 格式完全符合要求:\n- 不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n\n让我构建 scoring_components 数组:\n\n1. name: \"A1\", weight: 0.15, description: \"在 SUP 项目中创建了新的 Bug 类型 issue\", check_logic: \"通过 new_current_issues 对比 initial_state 与 current_state 找出新增 issues,再筛选 is_sup_issue 且 is_bug_type 的 issue;若 new_sup_bugs 列表非空则通过\", pass_condition: \"存在至少一个新增的 SUP 项目 Bug 类型 issue\"\n2. name: \"A2\", weight: 0.15, description: \"新 Bug 的 summary 识别出批量 CSV 导入 500 错误\", check_logic: \"在 new_sup_bugs 中筛选 summary 同时包含 csv、import/upload、500/server error 信号的 issue(has_csv500_summary);若 summary_matches 非空则通过\", pass_condition: \"新 SUP Bug 的 summary 同时包含 CSV、导入/上传和 500/服务器错误关键词\"\n3. name: \"A3\", weight: 0.10, description: \"新 Bug 的优先级为 High\", check_logic: \"对 target_issue(summary_matches 或 new_sup_bugs 中信号分最高的 issue)检查 priority 字段归一化后是否为 'high'\", pass_condition: \"target_issue 的 priority 为 High\"\n4. name: \"A4\", weight: 0.10, description: \"新 Bug 分配给数据导入工程师 Raj Patel\", check_logic: \"检查 target_issue 的 assigneeId 是否在 raj_user_ids 集合中(包含 'u_eng' 或用户名/邮箱匹配 raj patel)\", pass_condition: \"target_issue 的 assigneeId 为 'u_eng' 或对应 Raj Patel\"\n5. name: \"A5\", weight: 0.10, description: \"新 Bug 的描述记录客户 Northwind、高紧急度、release 3.4 和超过 5000 行触发条件\", check_logic: \"对 target_issue 的 description 分别调用 has_customer_signal、has_urgency_signal、has_release_34_signal、has_row_threshold_signal,四个信号必须全部为真\", pass_condition: \"description 同时包含 Northwind、high urgency、release 3.4、>5,000-row trigger 四个事实\"\n6. name: \"B1\", weight: 0.20, description: \"在同一 escalation 线程中发布了新的回复\", check_logic: \"通过 find_source_thread_id 在 slack_init 中定位源线程,再对比 initial/current 状态提取该线程的新回复内容列表;若 new_reply_contents 非空则通过\", pass_condition: \"在 Northwind escalation 线程中至少有一条新增回复\"\n7. name: \"B2\", weight: 0.20, description: \"新回复中包含新创建的 Jira issue key\", check_logic: \"遍历 new_reply_contents,使用 issue_key_matches 检查是否有回复内容匹配 target_key(如 SUP-9)的正则模式\", pass_condition: \"至少一条新回复引用了新创建的 Jira issue key\"\n\nscore_aggregation: \"各组件分数累加,最终通过 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入保留 4 位小数\"\n\nfailure_modes:\n- \"读取 /tmp/task_web_sid 失败或 sid 为空时,打印 CRITICAL 并输出 REWARD: 0.0 后 sys.exit(0)\"\n- \"无法从 JIRA mock 或 Slack mock 获取 current_state(返回 None)时,输出 REWARD: 0.0 后 sys.exit(0)\"\n- \"未找到新的 SUP Bug 时,A1-A5 组件均无法得分\"\n- \"未找到 escalation 线程或线程中无新回复时,B1-B2 均无法得分\"\n- \"A2 中 summary 缺少 CSV、import 或 500 任一信号则不得分\"\n- \"A5 中 description 缺少 Northwind、urgency、release 3.4、>5000 rows 任一事实则不得分\"\n- \"B2 中回复内容未匹配 target_key 格式则不得分\"\n\nscoring_logic_explanation: 需要按执行顺序详细说明。\n\n让我组织语言:\n1. 读取 /tmp/task_web_sid 获取 sid,失败则返回 0.0。\n2. 通过 HTTP GET 请求访问 JIRA 和 Slack mock 的 /go 端点,获取 initial_state 和 current_state,任一失败则返回 0.0。\n3. JIRA 评分:对比 initial 与 current 状态,提取新增 issues;筛选出 SUP 项目且类型为 Bug 的新 issue(A1);进一步检查其 summary 是否同时包含 CSV、import/upload、500/server error 关键词(A2);在候选 issue 中选取信号分最高的作为 target_issue,依次检查其 priority 是否为 High(A3)、assignee 是否为 Raj Patel/u_eng(A4)、description 是否同时包含 Northwind、high urgency、release 3.4 和 >5,000-row trigger(A5)。\n4. Slack 评分:在 slack_init 中通过关键词匹配(Northwind、CSV、500、high、release 3.4、Maria 等)定位 escalation 源线程;对比 initial/current 提取该线程的新增回复内容(B1);检查这些新回复中是否有内容通过正则匹配引用了新创建的 Jira issue key(B2)。\n5. 汇总:将 A1-A5 和 B1-B2 的得分累加,用 min(score, 1.0) 钳制上限,四舍五入到 4 位小数作为最终 REWARD。\n\nconfidence: 1.0\n\n检查是否有遗漏:\n- 代码中 PROXY 相关逻辑只是网络连接辅助,不影响评分逻辑,不需要在 JSON 中详述。\n- `issue_signal_score` 用于 `best_issue` 选择 target_issue,但评分时不直接使用该分数,只是辅助定位最可能的 issue。\n- 所有检查都是程序化、基于正则和关键词的,没有 LLM judge。\n\nJSON 格式检查:\n- 不能有 Markdown 代码块\n- 第一个字符必须是 {,最后一个必须是 }\n- 所有 value 字符串是中文(task_id, domain, 字段名、代码标识符保留原样)\n\n让我再确认一下 data_sources 的写法。代码中:\n- `/tmp/task_web_sid`\n- `http://28.7.186.212:8153` (JIRA_URL)\n- `http://28.7.186.212:8178` (SLACK_URL)\n\n可以写成:\n[\"/tmp/task_web_sid\", \"http://28.7.186.212:8153 (jira_mock)\", \"http://28.7.186.212:8178 (slack_mock)\"]\n\n或者更简洁:\n[\"/tmp/task_web_sid\", \"jira_mock\", \"slack_mock\"]\n\n但代码中明确使用了 URL,所以保留 URL 更好。\n\n现在确认 JSON 的键值对都正确。\n\n一个细节:domain 从 docstring 中提取是 \"mock_websites (multi-mock: slack_mock + jira_mock)\",但通常 domain 应该是 \"mock_websites\"。用户示例中有 \"mock_websites / software_engineer / libreoffice_calc\",所以填 \"mock_websites\" 即可。\n\nsummary 一句话概括。\n\nis_placeholder: false\n\ntotal_max_score: 1.0\n\n一切看起来都正确。 {\"task_id\":\"csops_slack_to_jira_001\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否在 Jira SUP 项目中正确创建了关于 CSV 导入 500 错误的 Bug 并填写所需字段,同时在 Slack escalation 线程中回复并引用该 Jira issue key。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"http://28.7.186.212:8153 (jira_mock)\",\"http://28.7.186.212:8178 (slack_mock)\"],\"scoring_components\":[{\"name\":\"A1\",\"weight\":0.15,\"description\":\"在 SUP 项目中创建了新的 Bug 类型 issue\",\"check_logic\":\"通过 new_current_issues 对比 jira_init 与 jira_cur 找出新增 issues,再筛选满足 is_sup_issue 且 is_bug_type 的 issue;若所得 new_sup_bugs 列表非空则通过\",\"pass_condition\":\"存在至少一个新增的 SUP 项目 Bug 类型 issue\"},{\"name\":\"A2\",\"weight\":0.15,\"description\":\"新 Bug 的 summary 识别出批量 CSV 导入 500 错误\",\"check_logic\":\"在 new_sup_bugs 中筛选 summary 同时包含 csv、import/upload、500/server error 信号的 issue(has_csv500_summary);若 summary_matches 非空则通过\",\"pass_condition\":\"新 SUP Bug 的 summary 同时包含 CSV、导入/上传和 500/服务器错误关键词\"},{\"name\":\"A3\",\"weight\":0.10,\"description\":\"新 Bug 的优先级为 High\",\"check_logic\":\"对 target_issue(优先从 summary_matches 选取,否则从 new_sup_bugs 中按 issue_signal_score 取最佳)检查 priority 字段归一化后是否等于 'high'\",\"pass_condition\":\"target_issue 的 priority 为 High\"},{\"name\":\"A4\",\"weight\":0.10,\"description\":\"新 Bug 分配给数据导入工程师 Raj Patel\",\"check_logic\":\"检查 target_issue 的 assigneeId 是否在 raj_user_ids 集合中(包含 'u_eng' 或用户名/邮箱匹配 raj patel)\",\"pass_condition\":\"target_issue 的 assigneeId 为 'u_eng' 或对应 Raj Patel\"},{\"name\":\"A5\",\"weight\":0.10,\"description\":\"新 Bug 的描述记录客户 Northwind、高紧急度、release 3.4 和超过 5000 行触发条件\",\"check_logic\":\"对 target_issue 的 description 分别调用 has_customer_signal、has_urgency_signal、has_release_34_signal、has_row_threshold_signal,四个信号必须全部为真\",\"pass_condition\":\"description 同时包含 Northwind、high urgency、release 3.4、>5,000-row trigger 四个事实\"},{\"name\":\"B1\",\"weight\":0.20,\"description\":\"在同一 escalation 线程中发布了新的回复\",\"check_logic\":\"通过 find_source_thread_id 在 slack_init 中依据 Northwind/CSV/500/high/release 3.4/Maria 等信号定位源线程,再对比 initial/current 状态提取该线程的新增回复内容列表;若 new_reply_contents 非空则通过\",\"pass_condition\":\"在 Northwind escalation 线程中至少有一条新增回复\"},{\"name\":\"B2\",\"weight\":0.20,\"description\":\"新回复中包含新创建的 Jira issue key\",\"check_logic\":\"遍历 new_reply_contents,使用 issue_key_matches 检查是否有回复内容通过正则匹配 target_key(如 SUP-9)的引用模式\",\"pass_condition\":\"至少一条新回复引用了新创建的 Jira issue key\"}],\"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 后 sys.exit(0)\",\"无法从 JIRA mock 或 Slack mock 获取 current_state(返回 None)时,输出 REWARD: 0.0 后 sys.exit(0)\",\"未找到新的 SUP Bug 时,A1-A5 组件均无法得分\",\"A2 中 summary 缺少 CSV、import 或 500 任一信号则不得分\",\"A5 中 description 缺少 Northwind、urgency、release 3.4、>5000 rows 任一事实则不得分\",\"未在 escalation 线程找到新回复时,B1-B2 均无法得分\",\"B2 中回复内容未匹配 target_key 格式则不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后通过 HTTP GET 请求拉取 JIRA 和 Slack mock 的 initial_state 与 current_state,任一拉取失败也返回 0.0。在 JIRA 侧,脚本对比初始与当前状态提取新增 issues,筛选出 SUP 项目且类型为 Bug 的新 issue(A1,0.15);进一步检查这些新 Bug 的 summary 是否同时包含 CSV、import/upload、500/server error 关键词(A2,0.15),并在候选 issue 中按 issue_signal_score 选取最佳 target_issue,依次验证其 priority 是否为 High(A3,0.10)、assignee 是否为 Raj Patel/u_eng(A4,0.10)、description 是否同时包含 Northwind、high urgency、release 3.4 和 >5,000-row trigger(A5,0.10)。在 Slack 侧,脚本在 slack_init 中通过多信号匹配定位 Northwind escalation 源线程,对比 initial/current 提取该线程的新增回复(B1,0.20),再检查新回复中是否有内容通过正则引用了新创建的 Jira issue key(B2,0.20)。最后将各组件得分累加,经 min(score, 1.0) 钳制上限并四舍五入到 4 位小数后输出最终 REWARD。\",\"confidence\":1.0}" +} diff --git a/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/_cua_gym_vm_bridge.sh b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/initial_setup.py b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3e0359c2a7c12d0933380f7614a965e569e0a822 --- /dev/null +++ b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/initial_setup.py @@ -0,0 +1,340 @@ +""" +Initial Setup: em_blocked_risklog_b94 +Task ID: f2b2e394-d114-5b0b-9a29-82bd05d69f97 +Domain: mock_websites +Mocks: jira_mock, google_sheets_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a software engineer. Your tools for this task are: the Jira project board, shared spreadsheets, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): Jira Kanban project with issues KAN-1(Done), KAN-2(Blocked), KAN-3(In Progress), KAN-4(In Progress), KAN-5(To Do); a Google Sheet with seeded tabular data; Slack workspace with channels #general, #engineering, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: risk log row has KAN-2 (the blocked issue) (+0.35); risk log row has its summary (+0.25); slack_new_msg (+0.2); reports exactly one blocker (+0.2). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "jira_mock": "http://28.7.186.212:8173", + "google_sheets_mock": "http://28.7.186.212:8165", + "slack_mock": "http://28.7.186.212:8198" +} +PRIMARY_URL = 'http://28.7.186.212:8173' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'Generated sid: {sid}') + +# Full initial state for every mock involved (all required top-level keys present). +STATES = { 'jira_mock': { 'currentUser': { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + 'users': [ { 'id': 'u1', + 'name': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u1'}, + { 'id': 'u2', + 'name': 'Jane Doe', + 'email': 'jane@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u2'}, + { 'id': 'u3', + 'name': 'John Smith', + 'email': 'john@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u3'}, + { 'id': 'u4', + 'name': 'Sarah Lee', + 'email': 'sarah@example.com', + 'avatar': 'https://picsum.photos/100/100?random=u4'}], + 'projects': [ { 'id': 'p1', + 'key': 'KAN', + 'name': 'Kanban Project', + 'leadId': 'u1', + 'category': 'Software', + 'icon': 'https://picsum.photos/64/64?random=p1'}], + 'sprints': [ { 'id': 's1', + 'projectId': 'p1', + 'name': 'Sprint 1', + 'goal': 'Stabilize core', + 'startDate': '2026-06-01T12:00:00.000Z', + 'endDate': '2026-06-15T12:00:00.000Z', + 'state': 'active'}], + 'issues': [ { 'id': 'i1', + 'key': 'KAN-1', + 'projectId': 'p1', + 'summary': 'Set up CI project', + 'description': '', + 'type': 'Task', + 'status': 'Done', + 'priority': 'Low', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u1', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}, + { 'id': 'i2', + 'key': 'KAN-2', + 'projectId': 'p1', + 'summary': 'OAuth callback fails on Safari', + 'description': '', + 'type': 'Bug', + 'status': 'Blocked', + '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': 'i3', + 'key': 'KAN-3', + 'projectId': 'p1', + 'summary': 'Dashboard widget 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'}, + { 'id': 'i4', + 'key': 'KAN-4', + 'projectId': 'p1', + 'summary': 'Add export to CSV', + 'description': '', + 'type': 'Story', + 'status': 'In Progress', + 'priority': 'Medium', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u4', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}, + { 'id': 'i5', + 'key': 'KAN-5', + 'projectId': 'p1', + 'summary': 'Write API docs', + 'description': '', + 'type': 'Task', + 'status': 'To Do', + 'priority': 'Low', + 'storyPoints': 3, + 'reporterId': 'u1', + 'assigneeId': 'u3', + 'sprintId': 's1', + 'epicId': None, + 'labels': [], + 'subtasks': [], + 'linkedIssueIds': [], + 'createdAt': '2026-06-02T12:00:00.000Z', + 'updatedAt': '2026-06-02T12:00:00.000Z'}], + 'comments': [], + 'workflows': [ { 'id': 'w1', + 'name': 'Software Workflow', + 'transitions': [ { 'from': 'To Do', + 'to': ['In Progress']}, + { 'from': 'In Progress', + 'to': [ 'In Review', + 'To Do', + 'Done']}, + { 'from': 'In Review', + 'to': ['Done', 'In Progress']}, + { 'from': 'Done', + 'to': ['In Progress', 'To Do']}]}], + 'notifications': []}, + 'google_sheets_mock': { 'id': 'workbook_1', + 'title': 'Sprint Risk Log', + 'activeSheetId': 'sheet_1', + 'selectedCell': 'A1', + 'selectionRange': None, + 'clipboard': None, + 'isDragging': False, + 'undoStack': [], + 'redoStack': [], + 'namedRanges': [], + 'conditionalFormats': [], + 'charts': [], + 'showGridlines': True, + 'showFormulas': False, + 'zoom': 100, + 'sheets': [ { 'id': 'sheet_1', + 'name': 'Sprint Risk Log', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'data': { 'A1': { 'value': 'Issue Key', + 'formula': 'Issue Key', + 'style': {'bold': True}}, + 'B1': { 'value': 'Summary', + 'formula': 'Summary', + 'style': {'bold': True}}}}]}, + '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': 'how many blockers are we ' + 'carrying into the ' + 'standup?', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}], + 'random': []}, + 'threads': {}, + 'dms': [], + 'bookmarkedMessages': [], + 'callHistory': [], + 'settings': { 'theme': 'light', + 'notifications': 'all', + 'displayDensity': 'comfortable', + 'showAvatars': True, + 'use24Hour': False}, + 'invitations': [], + 'notifications': []}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward.py b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..7b22cbbdf936d2417821081506d9f759ac8368fd --- /dev/null +++ b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward.py @@ -0,0 +1,105 @@ +""" +Reward Script: em_blocked_risklog_b94 +Task ID: f2b2e394-d114-5b0b-9a29-82bd05d69f97 +Domain: mock_websites +Mocks: jira_mock, google_sheets_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.35] risk log row has KAN-2 (the blocked issue) + - [0.25] risk log row has its summary + - [0.2] slack_new_msg + - [0.2] reports exactly one blocker +""" +import re +import sys + +import requests + +MOCK_URLS = { + "jira_mock": "http://28.7.186.212:8173", + "google_sheets_mock": "http://28.7.186.212:8165", + "slack_mock": "http://28.7.186.212:8198" +} +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: sheet cell A2 value contains 'KAN-2' +c0_sheets = cur('google_sheets_mock').get('sheets') or [] +c0_data = (c0_sheets[0].get('data') if c0_sheets else {}) or {} +c0_cd = c0_data.get('A2') or {} +if 'KAN-2' in str(c0_cd.get('value','')) or 'KAN-2' in str(c0_cd.get('computed','')): + print('PASS: risk log row has KAN-2 (the blocked issue) (0.35)') + total += 0.35 +else: + print('FAIL: risk log row has KAN-2 (the blocked issue)') + +# c1: sheet cell B2 value contains 'OAuth' +c1_sheets = cur('google_sheets_mock').get('sheets') or [] +c1_data = (c1_sheets[0].get('data') if c1_sheets else {}) or {} +c1_cd = c1_data.get('B2') or {} +if 'OAuth' in str(c1_cd.get('value','')) or 'OAuth' in str(c1_cd.get('computed','')): + print('PASS: risk log row has its summary (0.25)') + total += 0.25 +else: + print('FAIL: risk log row has its summary') + +# c2: new message by user_1 in #engineering +c2_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c2_seed = set(SEED.get('slack_mock:engineering', [])) +c2_new = [m for m in c2_msgs if m.get('messageId') not in c2_seed and m.get('senderId') == 'user_1'] +c2_blob = _lc(' '.join((m.get('content') or '') for m in c2_new)) +if c2_new: + print('PASS: new message by user_1 in #engineering (0.2)') + total += 0.2 +else: + print('FAIL: no new user_1 message in #engineering') + +# c3: slack #engineering contains (reports exactly one blocker) +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 ['1', 'one']): + print('PASS: reports exactly one blocker (0.2)') + total += 0.2 +else: + print('FAIL: reports exactly one blocker') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward_label.json b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..8eb707bd8ab73031391c297dbb2093ea0c58ce1a --- /dev/null +++ b/legacy/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/f2b2e394-d114-5b0b-9a29-82bd05d69f97/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:26:00", + "label": { + "task_id": "f2b2e394-d114-5b0b-9a29-82bd05d69f97", + "domain": "mock_websites", + "summary": "验证在 Google Sheets 风险日志中记录被阻塞的 Jira 问题 KAN-2 及其摘要,并在 Slack #engineering 频道由 user_1 发送新消息报告恰好一个阻塞项", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "jira_mock", + "google_sheets_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 0: risk log row has KAN-2", + "weight": 0.35, + "description": "风险日志行包含被阻塞的问题 KAN-2", + "check_logic": "检查 google_sheets_mock 的 current_state.sheets[0].data.A2 中 value 或 computed 字段的字符串表示是否包含 'KAN-2'", + "pass_condition": "A2 单元格的 value 或 computed 包含 'KAN-2'" + }, + { + "name": "Component 1: risk log row has its summary", + "weight": 0.25, + "description": "风险日志行包含该问题的摘要", + "check_logic": "检查 google_sheets_mock 的 current_state.sheets[0].data.B2 中 value 或 computed 字段的字符串表示是否包含 'OAuth'", + "pass_condition": "B2 单元格的 value 或 computed 包含 'OAuth'" + }, + { + "name": "Component 2: slack_new_msg", + "weight": 0.2, + "description": "在 Slack #engineering 频道有 user_1 发送的新消息", + "check_logic": "检查 slack_mock 的 current_state.messages.engineering 中是否存在 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId 等于 'user_1' 的消息", + "pass_condition": "#engineering 频道存在至少一条 user_1 发送的非种子新消息" + }, + { + "name": "Component 3: reports exactly one blocker", + "weight": 0.2, + "description": "Slack 消息中报告恰好一个阻塞项", + "check_logic": "提取 #engineering 频道中 user_1 发送的所有非种子新消息内容,转为小写后拼接为字符串,检查是否包含 '1' 或 'one'", + "pass_condition": "user_1 的新消息内容(小写)中包含 '1' 或 'one'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,总分通过 min(total, 1.0) 钳制到 1.0 上限后四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或内容为空时打印 CRITICAL 并返回 0.0 退出", + "从任一 mock 服务(jira_mock、google_sheets_mock、slack_mock)拉取当前状态失败时打印 CRITICAL 并返回 0.0 退出", + "Google Sheets A2 不包含 'KAN-2' 导致 Component 0 不得分", + "Google Sheets B2 不包含 'OAuth' 导致 Component 1 不得分", + "Slack #engineering 没有 user_1 的新消息导致 Component 2 不得分", + "Slack #engineering 中 user_1 的新消息内容不包含 '1' 或 'one' 导致 Component 3 不得分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 jira_mock、google_sheets_mock、slack_mock 发送 HTTP GET 请求拉取当前状态,任一环节失败即返回 0.0。评分分四项进行:1) 检查 Google Sheets 第一个工作表的 A2 单元格 value 或 computed 是否包含 'KAN-2',通过加 0.35 分;2) 检查 B2 单元格 value 或 computed 是否包含 'OAuth',通过加 0.25 分;3) 检查 Slack #engineering 频道是否存在 messageId 不在种子列表且 senderId 为 'user_1' 的新消息,通过加 0.2 分;4) 将 user_1 在 #engineering 的所有非种子新消息内容转为小写并拼接,检查是否包含 '1' 或 'one',通过加 0.2 分。最后将各组件得分累加,用 min(total, 1.0) 限制上限并四舍五入到 4 位小数输出最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. 文件头 docstring:\n - Reward Script: em_blocked_risklog_b94\n - Task ID: f2b2e394-d114-5b0b-9a29-82bd05d69f97\n - Domain: mock_websites\n - Mocks: jira_mock, google_sheets_mock, slack_mock\n - Scoring: total = 1.0\n - [0.35] risk log row has KAN-2 (the blocked issue)\n - [0.25] risk log row has its summary\n - [0.2] slack_new_msg\n - [0.2] reports exactly one blocker\n\n2. 数据源:\n - /tmp/task_web_sid 文件读取 sid\n - MOCK_URLS: jira_mock, google_sheets_mock, slack_mock\n - SEED: slack_mock:general, slack_mock:engineering, slack_mock:random\n\n3. 评分组件:\n - c0: google_sheets_mock 的 sheets[0].data.A2 的 value 或 computed 包含 'KAN-2',权重 0.35\n - c1: google_sheets_mock 的 sheets[0].data.B2 的 value 或 computed 包含 'OAuth',权重 0.25\n - c2: slack_mock 的 messages.engineering 中,messageId 不在 seed 中且 senderId == 'user_1' 的新消息存在,权重 0.2\n - c3: slack_mock 的 messages.engineering 中,messageId 不在 seed 中且 senderId == 'user_1' 的消息内容(小写)包含 '1' 或 'one',权重 0.2\n\n4. 失败模式:\n - 读取 sid 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取 mock 状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出\n\n5. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加汇总,然后钳制到 1.0\n\n6. is_placeholder: false,因为脚本有实际检查逻辑。\n\n7. confidence: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON:\n\n- task_id: \"f2b2e394-d114-5b0b-9a29-82bd05d69f97\"\n- domain: \"mock_websites\"\n- summary: \"验证在 Google Sheets 风险日志中记录被阻塞的 Jira 问题 KAN-2 及其摘要,并在 Slack #engineering 频道由 user_1 发送新消息报告恰好一个阻塞项\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"jira_mock\", \"google_sheets_mock\", \"slack_mock\"]\n- scoring_components:\n - name: \"Component 0\" 或 \"risk log row has KAN-2\"\n weight: 0.35\n description: \"风险日志行包含被阻塞的问题 KAN-2\"\n check_logic: \"检查 google_sheets_mock 的 current_state.sheets[0].data.A2 的 value 或 computed 字段的字符串表示中是否包含 'KAN-2'\"\n pass_condition: \"A2 单元格的 value 或 computed 包含 'KAN-2'\"\n - name: \"Component 1\" 或 \"risk log row has its summary\"\n weight: 0.25\n description: \"风险日志行包含该问题的摘要\"\n check_logic: \"检查 google_sheets_mock 的 current_state.sheets[0].data.B2 的 value 或 computed 字段的字符串表示中是否包含 'OAuth'\"\n pass_condition: \"B2 单元格的 value 或 computed 包含 'OAuth'\"\n - name: \"Component 2\" 或 \"slack_new_msg\"\n weight: 0.2\n description: \"在 Slack #engineering 频道有 user_1 发送的新消息\"\n check_logic: \"检查 slack_mock 的 current_state.messages.engineering 列表中,是否存在 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId 等于 'user_1' 的消息\"\n pass_condition: \"#engineering 频道存在至少一条 user_1 发送的非种子新消息\"\n - name: \"Component 3\" 或 \"reports exactly one blocker\"\n weight: 0.2\n description: \"Slack 消息中报告恰好一个阻塞项\"\n check_logic: \"提取 #engineering 频道中 user_1 发送的所有非种子新消息内容,转为小写后拼接成字符串,检查是否包含 '1' 或 'one'\"\n pass_condition: \"user_1 的新消息内容(小写)中包含 '1' 或 'one'\"\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 服务(jira_mock、google_sheets_mock、slack_mock)拉取当前状态失败时打印 CRITICAL 并返回 0.0 退出\",\n \"Google Sheets A2 不包含 'KAN-2' 导致 Component 0 不得分\",\n \"Google Sheets B2 不包含 'OAuth' 导致 Component 1 不得分\",\n \"Slack #engineering 没有 user_1 的新消息导致 Component 2 不得分\",\n \"Slack #engineering 中 user_1 的新消息内容不包含 '1' 或 'one' 导致 Component 3 不得分\"\n ]\n- scoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 jira_mock、google_sheets_mock、slack_mock 发送 HTTP GET 请求拉取当前状态。接着分四项检查:1) 检查 Google Sheets 第一个工作表的 A2 单元格是否包含 'KAN-2',通过加 0.35 分;2) 检查 B2 单元格是否包含 'OAuth',通过加 0.25 分;3) 检查 Slack #engineering 频道是否有 user_1 发送的新消息(排除种子消息),通过加 0.2 分;4) 检查 user_1 在 #engineering 的新消息内容(小写)是否包含 '1' 或 'one',通过加 0.2 分。最后将总分累加,用 min(total, 1.0) 限制上限并四舍五入到 4 位小数输出。\"\n- confidence: 1.0\n\n检查字段名和格式要求:\n- 只输出 JSON 对象,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n\n让我再仔细看看 docstring 中的 task_id 和 domain:\n- Task ID: f2b2e394-d114-5b0b-9a29-82bd05d69f97\n- Domain: mock_websites\n\nsummary 用中文。\n\nscoring_components 的 name 可以用描述性名称。\n\n确认 c3 的逻辑:它检查的是 c3_blob 中是否包含 '1' 或 'one'。注意 c3 和 c2 的区别:c2 检查是否有新消息,c3 检查内容。但 c3 的代码中,如果 c3_new 为空,c3_blob 就是空字符串,自然不会包含 '1' 或 'one'。\n\n确认 jira_mock 虽然在 MOCK_URLS 和 docstring 中被列出,但在评分逻辑中并没有直接检查 jira_mock 的状态。不过数据拉取时会获取它,失败会导致退出。\n\ndata_sources 应该包含 jira_mock,因为脚本确实拉取了它的状态(虽然评分没用到)。\n\nfailure_modes 应该包含 sid 读取失败和 mock 拉取失败。\n\nJSON 格式要合法,注意转义。\n\n让我构建最终的 JSON。 {\"task_id\":\"f2b2e394-d114-5b0b-9a29-82bd05d69f97\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Google Sheets 风险日志中记录被阻塞的 Jira 问题 KAN-2 及其摘要,并在 Slack #engineering 频道由 user_1 发送新消息报告恰好一个阻塞项\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"jira_mock\",\"google_sheets_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 0: risk log row has KAN-2\",\"weight\":0.35,\"description\":\"风险日志行包含被阻塞的问题 KAN-2\",\"check_logic\":\"检查 google_sheets_mock 的 current_state.sheets[0].data.A2 中 value 或 computed 字段的字符串表示是否包含 'KAN-2'\",\"pass_condition\":\"A2 单元格的 value 或 computed 包含 'KAN-2'\"},{\"name\":\"Component 1: risk log row has its summary\",\"weight\":0.25,\"description\":\"风险日志行包含该问题的摘要\",\"check_logic\":\"检查 google_sheets_mock 的 current_state.sheets[0].data.B2 中 value 或 computed 字段的字符串表示是否包含 'OAuth'\",\"pass_condition\":\"B2 单元格的 value 或 computed 包含 'OAuth'\"},{\"name\":\"Component 2: slack_new_msg\",\"weight\":0.2,\"description\":\"在 Slack #engineering 频道有 user_1 发送的新消息\",\"check_logic\":\"检查 slack_mock 的 current_state.messages.engineering 中是否存在 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId 等于 'user_1' 的消息\",\"pass_condition\":\"#engineering 频道存在至少一条 user_1 发送的非种子新消息\"},{\"name\":\"Component 3: reports exactly one blocker\",\"weight\":0.2,\"description\":\"Slack 消息中报告恰好一个阻塞项\",\"check_logic\":\"提取 #engineering 频道中 user_1 发送的所有非种子新消息内容,转为小写后拼接为字符串,检查是否包含 '1' 或 'one'\",\"pass_condition\":\"user_1 的新消息内容(小写)中包含 '1' 或 'one'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,总分通过 min(total, 1.0) 钳制到 1.0 上限后四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空时打印 CRITICAL 并返回 0.0 退出\",\"从任一 mock 服务(jira_mock、google_sheets_mock、slack_mock)拉取当前状态失败时打印 CRITICAL 并返回 0.0 退出\",\"Google Sheets A2 不包含 'KAN-2' 导致 Component 0 不得分\",\"Google Sheets B2 不包含 'OAuth' 导致 Component 1 不得分\",\"Slack #engineering 没有 user_1 的新消息导致 Component 2 不得分\",\"Slack #engineering 中 user_1 的新消息内容不包含 '1' 或 'one' 导致 Component 3 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 jira_mock、google_sheets_mock、slack_mock 发送 HTTP GET 请求拉取当前状态,任一环节失败即返回 0.0。评分分四项进行:1) 检查 Google Sheets 第一个工作表的 A2 单元格 value 或 computed 是否包含 'KAN-2',通过加 0.35 分;2) 检查 B2 单元格 value 或 computed 是否包含 'OAuth',通过加 0.25 分;3) 检查 Slack #engineering 频道是否存在 messageId 不在种子列表且 senderId 为 'user_1' 的新消息,通过加 0.2 分;4) 将 user_1 在 #engineering 的所有非种子新消息内容转为小写并拼接,检查是否包含 '1' 或 'one',通过加 0.2 分。最后将各组件得分累加,用 min(total, 1.0) 限制上限并四舍五入到 4 位小数输出最终 REWARD。\",\"confidence\":1.0}" +} diff --git a/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/_cua_gym_vm_bridge.sh b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/initial_setup.py b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..15285ce963b6bd87d5ae0b6f787b186c355cedb3 --- /dev/null +++ b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/initial_setup.py @@ -0,0 +1,2559 @@ +""" +Initial Setup: em_stale_mr_nudge_b95 +Task ID: f331e349-9a63-51ae-b592-8b21f8fc65ac +Domain: mock_websites +Mocks: gitlab_mock, slack_mock, lattice_mock (single shared sid) + +Persona: You are an office worker acting as a DevOps engineer. Your tools for this task are: the GitLab projects, team communications, Lattice performance management. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): GitLab with 6 issues, 2 MRs across projects; Slack workspace with channels #general, #engineering, #random; Lattice with 12 goals and feedback history. GROUND TRUTH — the agent earns partial credit for each checkpoint: slack_new_msg (+0.25); nudge names the stale MR (Resolve login issues) (+0.3); does NOT cite the already-merged MR (+0.15); Lattice feedback to user_3 about review latency (+0.3). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0. +""" +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +MOCK_URLS = { + "gitlab_mock": "http://28.7.186.212:8157", + "slack_mock": "http://28.7.186.212:8198", + "lattice_mock": "http://28.7.186.212:8175" +} +PRIMARY_URL = 'http://28.7.186.212:8157' + +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 = { 'gitlab_mock': { 'currentUser': { 'id': 1, + 'name': 'Admin User', + 'username': 'admin', + 'avatarUrl': 'https://picsum.photos/100/100?random=user1'}, + 'projects': [ { 'id': 1, + 'name': 'frontend-monorepo', + 'description': 'Main frontend repository for the ' + 'enterprise application.', + 'visibility': 'private', + 'stars': 12, + 'forks': 4, + 'updatedAt': '2026-06-08T09:54:15.658Z', + 'branches': [ 'main', + 'develop', + 'fix/login-mobile', + 'feat/dark-mode', + 'fix/header-style'], + 'files': [ { 'name': 'src', + 'type': 'folder', + 'children': [ { 'name': 'components', + 'type': 'folder', + 'children': [ { 'name': 'Button.jsx', + 'type': 'file', + 'content': 'export ' + 'const ' + 'Button ' + '= ' + '() ' + '=> ' + ';'}, + { 'name': 'Header.jsx', + 'type': 'file', + 'content': 'export ' + 'const ' + 'Header ' + '= ' + '() ' + '=> ' + '
Logo
;'}]}, + { 'name': 'App.jsx', + 'type': 'file', + 'content': 'import ' + '{ ' + 'Button ' + '} from ' + "'./components/Button';\n" + '\n' + 'export ' + 'default ' + 'function ' + 'App() ' + '{\n' + ' ' + 'return ' + '
;\n' + '}'}, + { 'name': 'index.css', + 'type': 'file', + 'content': 'body { ' + 'background: ' + '#fff; ' + '}'}]}, + { 'name': 'package.json', + 'type': 'file', + 'content': '{\n' + ' "name": "frontend",\n' + ' "version": "1.0.0"\n' + '}'}, + { 'name': 'README.md', + 'type': 'file', + 'content': '# Frontend Monorepo\n' + '\n' + 'This is the main ' + 'repository.\n' + '\n' + '## Getting Started\n' + '\n' + '1. `npm install`\n' + '2. `npm start`\n' + '\n' + '## Features\n' + '- React\n' + '- Vite\n' + '- Tailwind'}]}, + { 'id': 2, + 'name': 'backend-api', + 'description': 'Go-based microservices API gateway.', + 'visibility': 'internal', + 'stars': 8, + 'forks': 1, + 'updatedAt': '2026-06-07T09:54:15.658Z', + 'branches': ['main', 'dev', 'feat/auth-service'], + 'files': [ { 'name': 'main.go', + 'type': 'file', + 'content': 'package main\n' + '\n' + 'func main() {\n' + ' println("Hello World")\n' + '}'}, + { 'name': 'go.mod', + 'type': 'file', + 'content': 'module backend-api\n' + '\n' + 'go 1.20'}]}], + 'pipelines': [ { 'id': 101, + 'projectId': 1, + 'status': 'success', + 'branch': 'main', + 'commit': 'a1b2c3d', + 'message': 'fix: update dependency versions', + 'duration': '4m 12s', + 'createdAt': '2026-06-08T08:54:15.658Z', + 'stages': [ { 'id': 1, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 1, + 'name': 'build-app', + 'status': 'success', + 'duration': '1m'}]}, + { 'id': 2, + 'name': 'test', + 'status': 'success', + 'jobs': [ { 'id': 2, + 'name': 'unit-tests', + 'status': 'success', + 'duration': '2m'}, + { 'id': 3, + 'name': 'lint', + 'status': 'success', + 'duration': '30s'}]}, + { 'id': 3, + 'name': 'deploy', + 'status': 'success', + 'jobs': [ { 'id': 4, + 'name': 'deploy-staging', + 'status': 'success', + 'duration': '42s'}]}]}, + { 'id': 102, + 'projectId': 1, + 'status': 'failed', + 'branch': 'feature/login-page', + 'commit': 'e5f6g7h', + 'message': 'feat: add login form', + 'duration': '2m 10s', + 'createdAt': '2026-06-08T07:54:15.658Z', + 'stages': [ { 'id': 4, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 5, + 'name': 'build-app', + 'status': 'success', + 'duration': '1m'}]}, + { 'id': 5, + 'name': 'test', + 'status': 'failed', + 'jobs': [ { 'id': 6, + 'name': 'unit-tests', + 'status': 'failed', + 'duration': '1m 10s', + 'logs': 'Error: Test ' + 'failed in ' + 'Login.test.js\n' + 'Expected ' + 'true to be ' + 'false.'}]}]}, + { 'id': 103, + 'projectId': 1, + 'status': 'running', + 'branch': 'fix/header-style', + 'commit': 'i8j9k0l', + 'message': 'style: fix header padding', + 'duration': '45s', + 'createdAt': '2026-06-08T09:54:15.658Z', + 'stages': [ { 'id': 6, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 7, + 'name': 'build-app', + 'status': 'success', + 'duration': '40s'}]}, + { 'id': 7, + 'name': 'test', + 'status': 'running', + 'jobs': [ { 'id': 8, + 'name': 'unit-tests', + 'status': 'running', + 'duration': '5s'}]}, + { 'id': 8, + 'name': 'deploy', + 'status': 'pending', + 'jobs': [ { 'id': 9, + 'name': 'deploy-staging', + 'status': 'pending', + 'duration': '0s'}]}]}, + { 'id': 201, + 'projectId': 2, + 'status': 'success', + 'branch': 'main', + 'commit': 'z9y8x7w', + 'message': 'init: project structure', + 'duration': '1m 05s', + 'createdAt': '2026-06-07T09:54:15.658Z', + 'stages': [ { 'id': 21, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 21, + 'name': 'go-build', + 'status': 'success', + 'duration': '45s'}]}, + { 'id': 22, + 'name': 'test', + 'status': 'success', + 'jobs': [ { 'id': 22, + 'name': 'go-test', + 'status': 'success', + 'duration': '20s'}]}]}, + { 'id': 202, + 'projectId': 2, + 'status': 'failed', + 'branch': 'feat/auth-service', + 'commit': 'b2c3d4e', + 'message': 'feat: add auth middleware', + 'duration': '45s', + 'createdAt': '2026-06-08T08:54:15.658Z', + 'stages': [ { 'id': 23, + 'name': 'build', + 'status': 'success', + 'jobs': [ { 'id': 23, + 'name': 'go-build', + 'status': 'success', + 'duration': '40s'}]}, + { 'id': 24, + 'name': 'test', + 'status': 'failed', + 'jobs': [ { 'id': 24, + 'name': 'go-test', + 'status': 'failed', + 'duration': '5s', + 'logs': 'FAIL: ' + 'TestAuthMiddleware\n' + 'Expected ' + '401, got ' + '200'}]}]}, + { 'id': 203, + 'projectId': 2, + 'status': 'running', + 'branch': 'main', + 'commit': 'f5g6h7i', + 'message': 'chore: update dependencies', + 'duration': '10s', + 'createdAt': '2026-06-08T09:54:15.658Z', + 'stages': [ { 'id': 25, + 'name': 'build', + 'status': 'running', + 'jobs': [ { 'id': 25, + 'name': 'go-build', + 'status': 'running', + 'duration': '10s'}]}, + { 'id': 26, + 'name': 'test', + 'status': 'pending', + 'jobs': [ { 'id': 26, + 'name': 'go-test', + 'status': 'pending', + 'duration': '0s'}]}]}], + 'issues': [ { 'id': 1, + 'projectId': 1, + 'title': 'Login button not working on mobile', + 'description': 'The login button is unresponsive on iOS ' + 'devices.', + 'status': 'open', + 'labels': ['bug', 'high-priority'], + 'assignee': 'Admin User'}, + { 'id': 2, + 'projectId': 1, + 'title': 'Update documentation', + 'description': 'Readme needs to be updated with new build ' + 'steps.', + 'status': 'closed', + 'labels': ['docs'], + 'assignee': 'Admin User'}, + { 'id': 3, + 'projectId': 1, + 'title': 'Refactor user context', + 'description': 'Move user state to global context.', + 'status': 'in_progress', + 'labels': ['refactor'], + 'assignee': None}, + { 'id': 4, + 'projectId': 2, + 'title': 'Implement JWT Auth', + 'description': 'Add JWT token generation and validation.', + 'status': 'open', + 'labels': ['feature', 'security'], + 'assignee': 'Admin User'}, + { 'id': 5, + 'projectId': 2, + 'title': 'Fix database connection timeout', + 'description': 'Connection drops after 5 minutes of ' + 'inactivity.', + 'status': 'in_progress', + 'labels': ['bug'], + 'assignee': None}, + { 'id': 6, + 'projectId': 2, + 'title': 'Setup CI pipeline', + 'description': 'Configure XitLab CI for Go project.', + 'status': 'closed', + 'labels': ['devops'], + 'assignee': 'Admin User'}], + 'mergeRequests': [ { 'id': 1, + 'projectId': 1, + 'title': 'Resolve login issues', + 'sourceBranch': 'fix/login-mobile', + 'targetBranch': 'main', + 'status': 'open', + 'author': 'Admin User', + 'createdAt': '2026-06-08T09:54:15.658Z', + 'reviewers': []}, + { 'id': 2, + 'projectId': 1, + 'title': 'Add dark mode', + 'sourceBranch': 'feat/dark-mode', + 'targetBranch': 'main', + 'status': 'merged', + 'author': 'Admin User', + 'createdAt': '2026-06-07T09:54:15.658Z', + 'reviewers': []}], + 'registry': [ { 'id': 1, + 'projectId': 1, + 'name': 'frontend-monorepo/app', + 'tags': ['latest', 'v1.0.1', 'v1.0.0'], + 'size': '45MB', + 'updatedAt': '2026-06-08T09:54:15.658Z'}, + { 'id': 2, + 'projectId': 2, + 'name': 'backend-api/server', + 'tags': ['latest', 'v0.1.0'], + 'size': '12MB', + 'updatedAt': '2026-06-08T08:54:15.658Z'}], + 'snippets': [ { 'id': 1, + 'title': 'Useful Regex for Email', + 'code': 'const emailRegex = ' + '/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;', + 'language': 'javascript', + 'author': 'Admin User'}], + 'wiki': [ { 'id': 1, + 'projectId': 1, + 'title': 'Home', + 'content': '# Welcome to the Wiki\n' + '\n' + 'This is the home page of the project wiki.'}, + { 'id': 2, + 'projectId': 1, + 'title': 'Deployment Guide', + 'content': '# Deployment\n\n1. Build\n2. Test\n3. Push'}], + 'vulnerabilities': [ { 'id': 1, + 'projectId': 1, + 'severity': 'critical', + 'name': 'SQL Injection in Login', + 'status': 'detected'}, + { 'id': 2, + 'projectId': 1, + 'severity': 'medium', + 'name': 'Outdated Dependency: lodash', + 'status': 'resolved'}, + { 'id': 3, + 'projectId': 1, + 'severity': 'low', + 'name': 'Missing X-Frame-Options Header', + 'status': 'detected'}], + 'milestones': [ { 'id': 1, + 'projectId': 1, + 'title': 'v1.0 Launch', + 'dueDate': '2024-12-31', + 'progress': 75}], + 'releases': [ { 'id': 1, + 'projectId': 1, + 'tagName': 'v1.0.0', + 'name': 'Initial Release', + 'description': 'First major release with all core ' + 'features.', + 'createdAt': '2026-05-29T09:54:15.658Z', + 'author': 'Admin User'}]}, + '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': 'our MR queue is getting ' + 'stale, can we triage?', + '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': []}, + 'lattice_mock': { 'currentUser': { 'id': 'user_1', + 'firstName': 'Sarah', + 'lastName': 'Chen', + 'email': 'sarah.chen@evergreen.com', + 'avatar': None, + 'title': 'Senior Product Manager', + 'department': 'Product', + 'team': 'Platform Team', + 'location': 'San Francisco, CA', + 'startDate': '2021-03-15', + 'managerId': 'user_2', + 'directReportIds': ['user_14'], + 'role': 'ic', + 'status': 'active', + 'birthday': '1990-06-12', + 'workAnniversary': '2021-03-15'}, + 'users': [ { 'id': 'user_1', + 'firstName': 'Sarah', + 'lastName': 'Chen', + 'email': 'sarah.chen@evergreen.com', + 'avatar': None, + 'title': 'Senior Product Manager', + 'department': 'Product', + 'team': 'Platform Team', + 'location': 'San Francisco, CA', + 'startDate': '2021-03-15', + 'managerId': 'user_2', + 'directReportIds': ['user_14'], + 'role': 'ic', + 'status': 'active', + 'birthday': '1990-06-12', + 'workAnniversary': '2021-03-15'}, + { 'id': 'user_2', + 'firstName': 'Marcus', + 'lastName': 'Johnson', + 'email': 'marcus.johnson@evergreen.com', + 'avatar': None, + 'title': 'VP of Product', + 'department': 'Product', + 'team': 'Leadership', + 'location': 'San Francisco, CA', + 'startDate': '2019-08-01', + 'managerId': 'user_10', + 'directReportIds': [ 'user_1', + 'user_3', + 'user_12', + 'user_22'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1984-11-22', + 'workAnniversary': '2019-08-01'}, + { 'id': 'user_3', + 'firstName': 'Emily', + 'lastName': 'Rodriguez', + 'email': 'emily.rodriguez@evergreen.com', + 'avatar': None, + 'title': 'Product Designer', + 'department': 'Design', + 'team': 'Design Systems', + 'location': 'New York, NY', + 'startDate': '2022-01-10', + 'managerId': 'user_2', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1993-03-07', + 'workAnniversary': '2022-01-10'}, + { 'id': 'user_4', + 'firstName': 'James', + 'lastName': 'Kim', + 'email': 'james.kim@evergreen.com', + 'avatar': None, + 'title': 'Software Engineer', + 'department': 'Engineering', + 'team': 'Backend', + 'location': 'Austin, TX', + 'startDate': '2023-06-05', + 'managerId': 'user_6', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1996-09-15', + 'workAnniversary': '2023-06-05'}, + { 'id': 'user_5', + 'firstName': 'Priya', + 'lastName': 'Patel', + 'email': 'priya.patel@evergreen.com', + 'avatar': None, + 'title': 'Marketing Manager', + 'department': 'Marketing', + 'team': 'Growth', + 'location': 'Chicago, IL', + 'startDate': '2020-11-12', + 'managerId': 'user_7', + 'directReportIds': ['user_18'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1988-04-30', + 'workAnniversary': '2020-11-12'}, + { 'id': 'user_6', + 'firstName': 'David', + 'lastName': 'Thompson', + 'email': 'david.thompson@evergreen.com', + 'avatar': None, + 'title': 'Engineering Manager', + 'department': 'Engineering', + 'team': 'Backend', + 'location': 'Seattle, WA', + 'startDate': '2018-03-20', + 'managerId': 'user_10', + 'directReportIds': ['user_4', 'user_11', 'user_15'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1982-07-18', + 'workAnniversary': '2018-03-20'}, + { 'id': 'user_7', + 'firstName': 'Lisa', + 'lastName': 'Wang', + 'email': 'lisa.wang@evergreen.com', + 'avatar': None, + 'title': 'Director of Marketing', + 'department': 'Marketing', + 'team': 'Marketing Leadership', + 'location': 'San Francisco, CA', + 'startDate': '2017-09-01', + 'managerId': 'user_10', + 'directReportIds': ['user_5', 'user_18'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1980-12-03', + 'workAnniversary': '2017-09-01'}, + { 'id': 'user_8', + 'firstName': 'Alex', + 'lastName': 'Okafor', + 'email': 'alex.okafor@evergreen.com', + 'avatar': None, + 'title': 'Account Executive', + 'department': 'Sales', + 'team': 'Enterprise Sales', + 'location': 'Boston, MA', + 'startDate': '2024-01-08', + 'managerId': 'user_9', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1997-02-14', + 'workAnniversary': '2024-01-08'}, + { 'id': 'user_9', + 'firstName': 'Rachel', + 'lastName': 'Martinez', + 'email': 'rachel.martinez@evergreen.com', + 'avatar': None, + 'title': 'Sales Director', + 'department': 'Sales', + 'team': 'Sales Leadership', + 'location': 'New York, NY', + 'startDate': '2019-04-15', + 'managerId': 'user_10', + 'directReportIds': ['user_8', 'user_19'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1986-08-25', + 'workAnniversary': '2019-04-15'}, + { 'id': 'user_10', + 'firstName': 'Michael', + 'lastName': 'Torres', + 'email': 'michael.torres@evergreen.com', + 'avatar': None, + 'title': 'CEO', + 'department': 'Executive', + 'team': 'Leadership', + 'location': 'San Francisco, CA', + 'startDate': '2015-01-01', + 'managerId': None, + 'directReportIds': [ 'user_2', + 'user_6', + 'user_7', + 'user_9', + 'user_13', + 'user_20'], + 'role': 'admin', + 'status': 'active', + 'birthday': '1975-05-10', + 'workAnniversary': '2015-01-01'}, + { 'id': 'user_11', + 'firstName': 'Aisha', + 'lastName': 'Rahman', + 'email': 'aisha.rahman@evergreen.com', + 'avatar': None, + 'title': 'Senior Software Engineer', + 'department': 'Engineering', + 'team': 'Frontend', + 'location': 'San Francisco, CA', + 'startDate': '2020-06-01', + 'managerId': 'user_6', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1991-09-20', + 'workAnniversary': '2020-06-01'}, + { 'id': 'user_12', + 'firstName': 'Tom', + 'lastName': 'Nguyen', + 'email': 'tom.nguyen@evergreen.com', + 'avatar': None, + 'title': 'Data Analyst', + 'department': 'Product', + 'team': 'Analytics', + 'location': 'Austin, TX', + 'startDate': '2022-08-15', + 'managerId': 'user_2', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1994-01-28', + 'workAnniversary': '2022-08-15'}, + { 'id': 'user_13', + 'firstName': 'Olivia', + 'lastName': 'Bennett', + 'email': 'olivia.bennett@evergreen.com', + 'avatar': None, + 'title': 'Head of People Operations', + 'department': 'People Operations', + 'team': 'People', + 'location': 'San Francisco, CA', + 'startDate': '2019-02-11', + 'managerId': 'user_10', + 'directReportIds': ['user_16', 'user_17'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1985-05-18', + 'workAnniversary': '2019-02-11'}, + { 'id': 'user_14', + 'firstName': 'Jordan', + 'lastName': 'Lee', + 'email': 'jordan.lee@evergreen.com', + 'avatar': None, + 'title': 'Associate Product Manager', + 'department': 'Product', + 'team': 'Platform Team', + 'location': 'San Francisco, CA', + 'startDate': '2024-03-04', + 'managerId': 'user_1', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1998-11-02', + 'workAnniversary': '2024-03-04'}, + { 'id': 'user_15', + 'firstName': 'Carlos', + 'lastName': 'Reyes', + 'email': 'carlos.reyes@evergreen.com', + 'avatar': None, + 'title': 'DevOps Engineer', + 'department': 'Engineering', + 'team': 'Infrastructure', + 'location': 'Denver, CO', + 'startDate': '2021-10-18', + 'managerId': 'user_6', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1992-03-14', + 'workAnniversary': '2021-10-18'}, + { 'id': 'user_16', + 'firstName': 'Megan', + 'lastName': 'Foster', + 'email': 'megan.foster@evergreen.com', + 'avatar': None, + 'title': 'Recruiting Coordinator', + 'department': 'People Operations', + 'team': 'Talent Acquisition', + 'location': 'New York, NY', + 'startDate': '2023-01-23', + 'managerId': 'user_13', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1995-07-09', + 'workAnniversary': '2023-01-23'}, + { 'id': 'user_17', + 'firstName': 'Derek', + 'lastName': 'Chang', + 'email': 'derek.chang@evergreen.com', + 'avatar': None, + 'title': 'People Partner', + 'department': 'People Operations', + 'team': 'People', + 'location': 'San Francisco, CA', + 'startDate': '2020-09-07', + 'managerId': 'user_13', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1989-12-01', + 'workAnniversary': '2020-09-07'}, + { 'id': 'user_18', + 'firstName': 'Sofia', + 'lastName': 'Alvarez', + 'email': 'sofia.alvarez@evergreen.com', + 'avatar': None, + 'title': 'Content Marketing Specialist', + 'department': 'Marketing', + 'team': 'Growth', + 'location': 'Miami, FL', + 'startDate': '2023-09-11', + 'managerId': 'user_5', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1996-08-22', + 'workAnniversary': '2023-09-11'}, + { 'id': 'user_19', + 'firstName': 'Nathan', + 'lastName': 'Brooks', + 'email': 'nathan.brooks@evergreen.com', + 'avatar': None, + 'title': 'Sales Development Rep', + 'department': 'Sales', + 'team': 'Sales Development', + 'location': 'Boston, MA', + 'startDate': '2024-06-17', + 'managerId': 'user_9', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1999-04-05', + 'workAnniversary': '2024-06-17'}, + { 'id': 'user_20', + 'firstName': 'Karen', + 'lastName': 'Mitchell', + 'email': 'karen.mitchell@evergreen.com', + 'avatar': None, + 'title': 'CFO', + 'department': 'Finance', + 'team': 'Finance Leadership', + 'location': 'San Francisco, CA', + 'startDate': '2017-04-01', + 'managerId': 'user_10', + 'directReportIds': ['user_21'], + 'role': 'manager', + 'status': 'active', + 'birthday': '1978-10-30', + 'workAnniversary': '2017-04-01'}, + { 'id': 'user_21', + 'firstName': 'Brian', + 'lastName': 'Park', + 'email': 'brian.park@evergreen.com', + 'avatar': None, + 'title': 'Financial Analyst', + 'department': 'Finance', + 'team': 'FP&A', + 'location': 'San Francisco, CA', + 'startDate': '2022-05-09', + 'managerId': 'user_20', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1993-06-17', + 'workAnniversary': '2022-05-09'}, + { 'id': 'user_22', + 'firstName': 'Tanya', + 'lastName': 'Williams', + 'email': 'tanya.williams@evergreen.com', + 'avatar': None, + 'title': 'UX Researcher', + 'department': 'Design', + 'team': 'Design Systems', + 'location': 'Portland, OR', + 'startDate': '2023-03-27', + 'managerId': 'user_2', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1994-02-15', + 'workAnniversary': '2023-03-27'}, + { 'id': 'user_23', + 'firstName': 'Kevin', + 'lastName': 'Zhao', + 'email': 'kevin.zhao@evergreen.com', + 'avatar': None, + 'title': 'QA Engineer', + 'department': 'Engineering', + 'team': 'Quality', + 'location': 'Seattle, WA', + 'startDate': '2022-11-14', + 'managerId': 'user_6', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1991-12-08', + 'workAnniversary': '2022-11-14'}, + { 'id': 'user_24', + 'firstName': 'Hannah', + 'lastName': 'Davis', + 'email': 'hannah.davis@evergreen.com', + 'avatar': None, + 'title': 'Customer Success Manager', + 'department': 'Sales', + 'team': 'Customer Success', + 'location': 'Chicago, IL', + 'startDate': '2021-07-19', + 'managerId': 'user_9', + 'directReportIds': [], + 'role': 'ic', + 'status': 'active', + 'birthday': '1990-03-11', + 'workAnniversary': '2021-07-19'}], + 'goals': [ { 'id': 'goal_1', + 'title': 'Launch v2.0 of the platform', + 'description': 'Complete the redesign and ship the v2.0 ' + 'platform release to all customers by end ' + 'of Q2 with improved performance and UX.', + 'ownerId': 'user_1', + 'status': 'on_track', + 'progress': 65, + 'dueDate': '2025-06-30', + 'parentGoalId': 'goal_3', + 'category': 'individual', + 'keyResults': [ { 'id': 'kr_1_1', + 'title': 'Complete UI redesign for ' + 'all 5 core pages', + 'startValue': 0, + 'currentValue': 3, + 'targetValue': 5, + 'unit': 'pages'}, + { 'id': 'kr_1_2', + 'title': 'Achieve 95% test coverage', + 'startValue': 72, + 'currentValue': 88, + 'targetValue': 95, + 'unit': '%'}, + { 'id': 'kr_1_3', + 'title': 'Reduce page load time', + 'startValue': 4200, + 'currentValue': 2800, + 'targetValue': 2000, + 'unit': 'ms'}], + 'createdAt': '2025-01-10T09:00:00Z', + 'updatedAt': '2025-04-01T14:30:00Z'}, + { 'id': 'goal_2', + 'title': 'Improve NPS score from 42 to 55', + 'description': 'Collect systematic customer feedback and ' + 'implement top-requested improvements to ' + 'drive NPS improvement this quarter.', + 'ownerId': 'user_1', + 'status': 'progressing', + 'progress': 30, + 'dueDate': '2025-06-30', + 'parentGoalId': None, + 'category': 'individual', + 'keyResults': [ { 'id': 'kr_2_1', + 'title': 'Conduct 20 customer ' + 'interviews', + 'startValue': 0, + 'currentValue': 7, + 'targetValue': 20, + 'unit': 'interviews'}, + { 'id': 'kr_2_2', + 'title': 'Increase NPS score', + 'startValue': 42, + 'currentValue': 45, + 'targetValue': 55, + 'unit': 'NPS'}], + 'createdAt': '2025-01-15T10:00:00Z', + 'updatedAt': '2025-03-20T11:00:00Z'}, + { 'id': 'goal_3', + 'title': 'Achieve $10M ARR by Q4', + 'description': 'Drive revenue growth through product-led ' + 'growth initiatives, new enterprise deals, ' + 'and improved retention.', + 'ownerId': 'user_2', + 'status': 'on_track', + 'progress': 58, + 'dueDate': '2025-12-31', + 'parentGoalId': 'goal_5', + 'category': 'team', + 'keyResults': [ { 'id': 'kr_3_1', + 'title': 'Close 15 enterprise deals', + 'startValue': 0, + 'currentValue': 9, + 'targetValue': 15, + 'unit': 'deals'}, + { 'id': 'kr_3_2', + 'title': 'Reach $10M ARR', + 'startValue': 5800000, + 'currentValue': 7200000, + 'targetValue': 10000000, + 'unit': '$'}], + 'createdAt': '2025-01-05T09:00:00Z', + 'updatedAt': '2025-04-03T09:00:00Z'}, + { 'id': 'goal_4', + 'title': 'Build world-class engineering culture', + 'description': 'Establish a culture of excellence through ' + 'improved processes, better tooling, and ' + 'strong mentorship programs.', + 'ownerId': 'user_6', + 'status': 'progressing', + 'progress': 42, + 'dueDate': '2025-12-31', + 'parentGoalId': 'goal_6', + 'category': 'team', + 'keyResults': [ { 'id': 'kr_4_1', + 'title': 'Improve deployment ' + 'frequency to daily', + 'startValue': 3, + 'currentValue': 5, + 'targetValue': 7, + 'unit': 'deploys/week'}, + { 'id': 'kr_4_2', + 'title': 'Achieve 90% team ' + 'satisfaction in eng ' + 'survey', + 'startValue': 72, + 'currentValue': 78, + 'targetValue': 90, + 'unit': '%'}], + 'createdAt': '2025-02-01T09:00:00Z', + 'updatedAt': '2025-03-15T14:00:00Z'}, + { 'id': 'goal_5', + 'title': 'Expand into EMEA market', + 'description': 'Open European operations and establish ' + 'partnerships with 5 regional resellers.', + 'ownerId': 'user_10', + 'status': 'on_track', + 'progress': 55, + 'dueDate': '2025-09-30', + 'parentGoalId': None, + 'category': 'company', + 'keyResults': [ { 'id': 'kr_5_1', + 'title': 'Hire EMEA country manager', + 'startValue': 0, + 'currentValue': 1, + 'targetValue': 1, + 'unit': 'hire'}, + { 'id': 'kr_5_2', + 'title': 'Sign 5 regional resellers', + 'startValue': 0, + 'currentValue': 3, + 'targetValue': 5, + 'unit': 'partners'}], + 'createdAt': '2025-01-01T09:00:00Z', + 'updatedAt': '2025-04-02T10:00:00Z'}, + { 'id': 'goal_6', + 'title': 'Achieve SOC 2 Type II certification', + 'description': 'Complete security audit and implement all ' + 'required controls to earn SOC 2 Type II ' + 'certification.', + 'ownerId': 'user_10', + 'status': 'on_track', + 'progress': 80, + 'dueDate': '2025-05-30', + 'parentGoalId': None, + 'category': 'company', + 'keyResults': [ { 'id': 'kr_6_1', + 'title': 'Complete security ' + 'assessment', + 'startValue': 0, + 'currentValue': 1, + 'targetValue': 1, + 'unit': 'audit'}, + { 'id': 'kr_6_2', + 'title': 'Remediate all critical ' + 'findings', + 'startValue': 18, + 'currentValue': 15, + 'targetValue': 0, + 'unit': 'open findings'}], + 'createdAt': '2024-11-01T09:00:00Z', + 'updatedAt': '2025-03-30T15:00:00Z'}, + { 'id': 'goal_7', + 'title': 'Complete customer success playbook', + 'description': 'Document and systematize the customer ' + 'success process for onboarding and ' + 'ongoing support.', + 'ownerId': 'user_9', + 'status': 'completed', + 'progress': 100, + 'dueDate': '2025-03-31', + 'parentGoalId': None, + 'category': 'individual', + 'keyResults': [ { 'id': 'kr_7_1', + 'title': 'Document all CS workflows', + 'startValue': 0, + 'currentValue': 12, + 'targetValue': 12, + 'unit': 'workflows'}], + 'createdAt': '2025-01-15T09:00:00Z', + 'updatedAt': '2025-03-28T16:00:00Z'}, + { 'id': 'goal_8', + 'title': 'Launch company-wide mentorship program', + 'description': 'Design and launch a structured mentorship ' + 'program pairing senior employees with new ' + 'hires.', + 'ownerId': 'user_7', + 'status': 'behind', + 'progress': 15, + 'dueDate': '2025-05-01', + 'parentGoalId': None, + 'category': 'team', + 'keyResults': [ { 'id': 'kr_8_1', + 'title': 'Pair 20 mentors with ' + 'mentees', + 'startValue': 0, + 'currentValue': 3, + 'targetValue': 20, + 'unit': 'pairs'}, + { 'id': 'kr_8_2', + 'title': 'Complete program design ' + 'documents', + 'startValue': 0, + 'currentValue': 1, + 'targetValue': 4, + 'unit': 'docs'}], + 'createdAt': '2025-02-01T09:00:00Z', + 'updatedAt': '2025-03-10T11:00:00Z'}, + { 'id': 'goal_9', + 'title': 'Reduce CI/CD pipeline time by 50%', + 'description': 'Optimize build and deployment ' + 'infrastructure to cut pipeline time from ' + '20 to 10 minutes.', + 'ownerId': 'user_15', + 'status': 'on_track', + 'progress': 70, + 'dueDate': '2025-06-30', + 'parentGoalId': 'goal_4', + 'category': 'individual', + 'keyResults': [ { 'id': 'kr_9_1', + 'title': 'Reduce build time', + 'startValue': 20, + 'currentValue': 13, + 'targetValue': 10, + 'unit': 'minutes'}, + { 'id': 'kr_9_2', + 'title': 'Implement parallel test ' + 'execution', + 'startValue': 0, + 'currentValue': 1, + 'targetValue': 1, + 'unit': 'complete'}], + 'createdAt': '2025-02-15T09:00:00Z', + 'updatedAt': '2025-04-05T10:00:00Z'}, + { 'id': 'goal_10', + 'title': 'Increase enterprise deal pipeline by 40%', + 'description': 'Expand outbound and inbound pipeline for ' + 'enterprise segment.', + 'ownerId': 'user_8', + 'status': 'progressing', + 'progress': 35, + 'dueDate': '2025-06-30', + 'parentGoalId': None, + 'category': 'individual', + 'keyResults': [ { 'id': 'kr_10_1', + 'title': 'Generate 50 qualified ' + 'enterprise leads', + 'startValue': 0, + 'currentValue': 18, + 'targetValue': 50, + 'unit': 'leads'}, + { 'id': 'kr_10_2', + 'title': 'Book 30 demo meetings', + 'startValue': 0, + 'currentValue': 12, + 'targetValue': 30, + 'unit': 'demos'}], + 'createdAt': '2025-01-20T09:00:00Z', + 'updatedAt': '2025-04-01T11:00:00Z'}, + { 'id': 'goal_11', + 'title': 'Redesign the onboarding experience', + 'description': 'Create a new employee onboarding program ' + 'that reduces time-to-productivity from 60 ' + 'to 30 days.', + 'ownerId': 'user_13', + 'status': 'on_track', + 'progress': 50, + 'dueDate': '2025-07-31', + 'parentGoalId': None, + 'category': 'team', + 'keyResults': [ { 'id': 'kr_11_1', + 'title': 'Create onboarding ' + 'curriculum', + 'startValue': 0, + 'currentValue': 6, + 'targetValue': 10, + 'unit': 'modules'}, + { 'id': 'kr_11_2', + 'title': 'Reduce ' + 'time-to-productivity', + 'startValue': 60, + 'currentValue': 45, + 'targetValue': 30, + 'unit': 'days'}], + 'createdAt': '2025-02-01T09:00:00Z', + 'updatedAt': '2025-04-02T10:00:00Z'}, + { 'id': 'goal_12', + 'title': 'Grow organic blog traffic by 3x', + 'description': 'Develop and execute content strategy to ' + 'triple monthly blog visitors.', + 'ownerId': 'user_18', + 'status': 'progressing', + 'progress': 40, + 'dueDate': '2025-09-30', + 'parentGoalId': None, + 'category': 'individual', + 'keyResults': [ { 'id': 'kr_12_1', + 'title': 'Publish 24 SEO-optimized ' + 'articles', + 'startValue': 0, + 'currentValue': 10, + 'targetValue': 24, + 'unit': 'articles'}, + { 'id': 'kr_12_2', + 'title': 'Increase monthly visitors', + 'startValue': 15000, + 'currentValue': 28000, + 'targetValue': 45000, + 'unit': 'visitors'}], + 'createdAt': '2025-01-10T09:00:00Z', + 'updatedAt': '2025-04-05T09:00:00Z'}], + 'feedback': [ { 'id': 'fb_1', + 'type': 'feedback', + 'fromUserId': 'user_2', + 'toUserId': 'user_1', + 'body': 'Sarah did an exceptional job leading the Q1 ' + 'platform planning sessions. Her preparation ' + 'and ability to align cross-functional ' + 'stakeholders was impressive. She kept the ' + 'team focused and drove us to clear decisions ' + 'even when there was ambiguity.', + 'visibility': 'private', + 'competencyTags': ['Leadership', 'Communication'], + 'valueTags': [], + 'reactions': [], + 'createdAt': '2025-03-28T10:15:00Z'}, + { 'id': 'fb_2', + 'type': 'feedback', + 'fromUserId': 'user_3', + 'toUserId': 'user_1', + 'body': 'Sarah is a great collaborator. During the ' + 'design review process, she always came ' + 'prepared with clear use cases and user ' + 'stories. I especially appreciated how she ' + 'advocated for the user perspective while ' + 'still being pragmatic about engineering ' + 'constraints.', + 'visibility': 'private', + 'competencyTags': ['Collaboration', 'User Focus'], + 'valueTags': [], + 'reactions': [], + 'createdAt': '2025-03-15T14:00:00Z'}, + { 'id': 'fb_3', + 'type': 'feedback', + 'fromUserId': 'user_6', + 'toUserId': 'user_1', + 'body': 'I appreciated how Sarah managed the v2.0 ' + 'timeline when we hit the API integration ' + 'blocker. She quickly reprioritized work, ' + 'communicated clearly with stakeholders, and ' + 'kept morale high. One area to grow: ' + 'proactively flagging risks earlier in the ' + 'cycle.', + 'visibility': 'manager_only', + 'competencyTags': [ 'Project Management', + 'Adaptability'], + 'valueTags': [], + 'reactions': [], + 'createdAt': '2025-02-20T09:30:00Z'}, + { 'id': 'fb_4', + 'type': 'praise', + 'fromUserId': 'user_2', + 'toUserId': 'user_1', + 'body': "Sarah's work on the onboarding redesign was " + 'outstanding! She shipped the new user ' + 'onboarding flow ahead of schedule and the ' + 'results speak for themselves — activation ' + 'rates are up 18% week over week. This is ' + 'exactly the kind of impact we need. 🎉', + 'visibility': 'public', + 'competencyTags': ['Execution', 'Impact'], + 'valueTags': ['Customer Focus', 'Innovation'], + 'reactions': [ {'userId': 'user_3', 'emoji': '👏'}, + {'userId': 'user_5', 'emoji': '👏'}, + {'userId': 'user_8', 'emoji': '🎉'}], + 'createdAt': '2025-04-02T11:00:00Z'}, + { 'id': 'fb_5', + 'type': 'praise', + 'fromUserId': 'user_3', + 'toUserId': 'user_1', + 'body': 'Huge shoutout to Sarah for her incredible ' + 'support during the design sprint last week. ' + 'She stayed late multiple evenings to help us ' + 'refine the prototypes and her product ' + 'instincts helped us avoid a significant ' + 'usability issue. True team player!', + 'visibility': 'public', + 'competencyTags': ['Teamwork', 'Dedication'], + 'valueTags': ['Teamwork', 'Growth Mindset'], + 'reactions': [ {'userId': 'user_2', 'emoji': '👏'}, + {'userId': 'user_4', 'emoji': '❤️'}], + 'createdAt': '2025-03-22T16:00:00Z'}, + { 'id': 'fb_6', + 'type': 'feedback', + 'fromUserId': 'user_1', + 'toUserId': 'user_3', + 'body': 'Emily has been an incredible design partner ' + 'on the v2.0 project. Her attention to detail ' + 'and ability to translate complex user needs ' + 'into elegant UI solutions has elevated our ' + 'product significantly. She proactively ' + 'identifies potential UX issues before they ' + 'become problems.', + 'visibility': 'private', + 'competencyTags': ['Design Thinking', 'Proactivity'], + 'valueTags': [], + 'reactions': [], + 'createdAt': '2025-03-25T10:00:00Z'}, + { 'id': 'fb_7', + 'type': 'praise', + 'fromUserId': 'user_1', + 'toUserId': 'user_4', + 'body': 'James went above and beyond this sprint by ' + 'independently identifying and fixing a ' + 'critical performance regression that would ' + 'have impacted our largest customers. He did ' + 'this without being asked and documented the ' + 'solution clearly for the team.', + 'visibility': 'public', + 'competencyTags': ['Initiative', 'Technical Skills'], + 'valueTags': ['Innovation', 'Integrity'], + 'reactions': [ {'userId': 'user_6', 'emoji': '👏'}, + {'userId': 'user_2', 'emoji': '🙌'}], + 'createdAt': '2025-04-05T09:00:00Z'}, + { 'id': 'fb_8', + 'type': 'praise', + 'fromUserId': 'user_5', + 'toUserId': 'user_7', + 'body': 'Lisa has been an exceptional mentor and ' + 'sponsor. She advocated for my promotion, gave ' + 'me visibility on the exec team presentation, ' + 'and provided thoughtful coaching throughout. ' + 'I am grateful to have her as my manager.', + 'visibility': 'public', + 'competencyTags': ['Mentorship', 'Leadership'], + 'valueTags': ['Teamwork', 'Growth Mindset'], + 'reactions': [{'userId': 'user_10', 'emoji': '👏'}], + 'createdAt': '2025-04-01T14:00:00Z'}, + { 'id': 'fb_9', + 'type': 'feedback', + 'fromUserId': 'user_8', + 'toUserId': 'user_1', + 'body': "Would love to get Sarah's feedback on how I " + 'presented the product roadmap to our ' + 'enterprise prospects last week. Specifically ' + 'curious if the value proposition messaging ' + 'resonated and what I could strengthen.', + 'visibility': 'private', + 'competencyTags': [], + 'valueTags': [], + 'reactions': [], + 'createdAt': '2025-04-08T15:00:00Z', + 'isPendingRequest': True}, + { 'id': 'fb_10', + 'type': 'feedback', + 'fromUserId': 'user_1', + 'toUserId': 'user_2', + 'body': 'Marcus is one of the best managers I have ' + 'had. He provides clear direction, creates ' + 'space for autonomy, and always has my back ' + 'with stakeholders. He could improve by giving ' + 'more frequent informal check-ins between our ' + '1:1s, but overall I feel very supported.', + 'visibility': 'manager_only', + 'competencyTags': ['Management', 'Strategy'], + 'valueTags': [], + 'reactions': [], + 'createdAt': '2025-03-10T10:00:00Z'}], + 'oneOnOnes': [ { 'id': 'oo_1', + 'participantIds': ['user_1', 'user_2'], + 'frequency': 'weekly', + 'nextMeetingDate': '2025-04-14T14:00:00Z'}, + { 'id': 'oo_2', + 'participantIds': ['user_1', 'user_3'], + 'frequency': 'biweekly', + 'nextMeetingDate': '2025-04-16T11:00:00Z'}, + { 'id': 'oo_3', + 'participantIds': ['user_1', 'user_14'], + 'frequency': 'weekly', + 'nextMeetingDate': '2025-04-15T10:00:00Z'}], + 'meetings': [ { 'id': 'meeting_1', + 'oneOnOneId': 'oo_1', + 'date': '2025-04-14T14:00:00Z', + 'status': 'upcoming', + 'talkingPoints': [ { 'id': 'tp_1_1', + 'text': 'Discuss Q2 goal ' + 'progress and any ' + 'blockers', + 'addedBy': 'user_1', + 'discussed': False, + 'order': 0}, + { 'id': 'tp_1_2', + 'text': 'Review promotion ' + 'timeline and next ' + 'steps', + 'addedBy': 'user_1', + 'discussed': False, + 'order': 1}, + { 'id': 'tp_1_3', + 'text': 'Align on v2.0 launch ' + 'communication plan', + 'addedBy': 'user_2', + 'discussed': False, + 'order': 2}, + { 'id': 'tp_1_4', + 'text': 'Team capacity ' + 'planning for May', + 'addedBy': 'user_2', + 'discussed': False, + 'order': 3}], + 'actionItems': [ { 'id': 'ai_1_1', + 'text': 'Draft Q2 roadmap ' + 'summary for exec ' + 'review', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-18', + 'completed': False}, + { 'id': 'ai_1_2', + 'text': 'Schedule skip-level ' + 'with Michael', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-15', + 'completed': False}], + 'notes': ''}, + { 'id': 'meeting_2', + 'oneOnOneId': 'oo_2', + 'date': '2025-04-16T11:00:00Z', + 'status': 'upcoming', + 'talkingPoints': [ { 'id': 'tp_2_1', + 'text': 'Review the new ' + 'settings page ' + 'designs', + 'addedBy': 'user_3', + 'discussed': False, + 'order': 0}, + { 'id': 'tp_2_2', + 'text': 'Discuss ' + 'collaboration ' + 'process improvements', + 'addedBy': 'user_1', + 'discussed': False, + 'order': 1}, + { 'id': 'tp_2_3', + 'text': 'Feedback on the ' + 'onboarding flow ' + 'iterations', + 'addedBy': 'user_1', + 'discussed': False, + 'order': 2}], + 'actionItems': [], + 'notes': ''}, + { 'id': 'meeting_3', + 'oneOnOneId': 'oo_1', + 'date': '2025-04-07T14:00:00Z', + 'status': 'completed', + 'talkingPoints': [ { 'id': 'tp_3_1', + 'text': 'Q1 performance ' + 'review preparation', + 'addedBy': 'user_2', + 'discussed': True, + 'order': 0}, + { 'id': 'tp_3_2', + 'text': 'v2.0 milestone ' + 'status update', + 'addedBy': 'user_1', + 'discussed': True, + 'order': 1}, + { 'id': 'tp_3_3', + 'text': 'Cross-functional ' + 'team alignment ' + 'issues', + 'addedBy': 'user_1', + 'discussed': True, + 'order': 2}], + 'actionItems': [ { 'id': 'ai_3_1', + 'text': 'Complete self-review ' + 'by April 10', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-10', + 'completed': False}, + { 'id': 'ai_3_2', + 'text': 'Set up cross-team sync ' + 'with Engineering', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-09', + 'completed': True}], + 'notes': 'Good check-in. Sarah is making solid ' + 'progress on the v2.0 launch. Main risk is ' + 'the API integration timeline — need to ' + 'ensure James has what he needs. Self-review ' + 'deadline coming up this week.'}, + { 'id': 'meeting_4', + 'oneOnOneId': 'oo_1', + 'date': '2025-03-31T14:00:00Z', + 'status': 'completed', + 'talkingPoints': [ { 'id': 'tp_4_1', + 'text': 'Q1 wrap-up and wins ' + 'to celebrate', + 'addedBy': 'user_2', + 'discussed': True, + 'order': 0}, + { 'id': 'tp_4_2', + 'text': 'Career development ' + 'discussion — ' + 'promotion path', + 'addedBy': 'user_1', + 'discussed': True, + 'order': 1}], + 'actionItems': [ { 'id': 'ai_4_1', + 'text': 'Document impact ' + 'metrics for promotion ' + 'packet', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-07', + 'completed': True}], + 'notes': 'Great end-of-quarter conversation. Sarah has ' + 'had a strong Q1 and is on track for ' + 'promotion consideration. Marcus committed to ' + 'presenting her case at the next calibration ' + 'session.'}, + { 'id': 'meeting_5', + 'oneOnOneId': 'oo_2', + 'date': '2025-04-02T11:00:00Z', + 'status': 'completed', + 'talkingPoints': [ { 'id': 'tp_5_1', + 'text': 'Design handoff ' + 'process for v2.0', + 'addedBy': 'user_1', + 'discussed': True, + 'order': 0}, + { 'id': 'tp_5_2', + 'text': "Emily's growth area " + 'progress update', + 'addedBy': 'user_3', + 'discussed': True, + 'order': 1}], + 'actionItems': [ { 'id': 'ai_5_1', + 'text': 'Create design-to-dev ' + 'handoff template', + 'assigneeId': 'user_3', + 'dueDate': '2025-04-09', + 'completed': False}], + 'notes': 'Productive session. Emily is doing great ' + 'work on the design system. We agreed on a ' + 'new handoff checklist to improve the ' + 'PM-Design collaboration workflow.'}, + { 'id': 'meeting_6', + 'oneOnOneId': 'oo_1', + 'date': '2025-03-24T14:00:00Z', + 'status': 'completed', + 'talkingPoints': [ { 'id': 'tp_6_1', + 'text': 'Mid-quarter ' + 'check-in: goals ' + 'progress', + 'addedBy': 'user_2', + 'discussed': True, + 'order': 0}, + { 'id': 'tp_6_2', + 'text': 'Feedback on customer ' + 'advisory board ' + 'presentation', + 'addedBy': 'user_1', + 'discussed': True, + 'order': 1}], + 'actionItems': [], + 'notes': 'Solid meeting. Sarah received very positive ' + 'feedback from the CAB presentation. Goals ' + 'are tracking well — NPS goal needs more ' + 'focus in Q2.'}, + { 'id': 'meeting_7', + 'oneOnOneId': 'oo_3', + 'date': '2025-04-15T10:00:00Z', + 'status': 'upcoming', + 'talkingPoints': [ { 'id': 'tp_7_1', + 'text': 'Onboarding progress ' + 'check-in', + 'addedBy': 'user_1', + 'discussed': False, + 'order': 0}, + { 'id': 'tp_7_2', + 'text': 'Assign first ' + 'independent feature ' + 'ownership', + 'addedBy': 'user_1', + 'discussed': False, + 'order': 1}, + { 'id': 'tp_7_3', + 'text': 'Questions about ' + 'product strategy', + 'addedBy': 'user_14', + 'discussed': False, + 'order': 2}], + 'actionItems': [ { 'id': 'ai_7_1', + 'text': 'Review the analytics ' + 'dashboard PRD draft', + 'assigneeId': 'user_14', + 'dueDate': '2025-04-17', + 'completed': False}], + 'notes': ''}], + 'reviewCycles': [ { 'id': 'rc_1', + 'name': 'Q1 2025 Performance Review', + 'status': 'active', + 'startDate': '2025-03-15', + 'endDate': '2025-04-15', + 'steps': [ 'nominate_peers', + 'manage_team', + 'share_results'], + 'currentStep': 'manage_team', + 'revieweeIds': [ 'user_1', + 'user_3', + 'user_4', + 'user_5', + 'user_6', + 'user_11', + 'user_14', + 'user_15'], + 'nominationsSubmitted': True}, + { 'id': 'rc_2', + 'name': 'Q3 2024 Performance Review', + 'status': 'completed', + 'startDate': '2024-09-15', + 'endDate': '2024-10-15', + 'steps': [ 'nominate_peers', + 'manage_team', + 'share_results'], + 'currentStep': 'share_results', + 'revieweeIds': [ 'user_1', + 'user_3', + 'user_4', + 'user_8', + 'user_11'], + 'nominationsSubmitted': True}], + 'reviews': [ { 'id': 'rev_1', + 'cycleId': 'rc_1', + 'revieweeId': 'user_3', + 'status': 'completed', + 'nominatedPeerIds': ['user_1', 'user_2'], + 'reviews': [ { 'reviewerId': 'user_2', + 'type': 'manager', + 'overallRating': 'exceeds_expectations', + 'responses': [ { 'question': 'What ' + 'are ' + 'this ' + "person's " + 'key ' + 'strengths?', + 'answer': 'Emily ' + 'is a ' + 'gifted ' + 'designer ' + 'with ' + 'exceptional ' + 'product ' + 'instincts. ' + 'She ' + 'consistently ' + 'delivers ' + 'high-quality ' + 'work ' + 'under ' + 'tight ' + 'timelines.'}, + { 'question': 'What ' + 'areas ' + 'could ' + 'this ' + 'person ' + 'improve?', + 'answer': 'Could ' + 'be ' + 'more ' + 'proactive ' + 'in ' + 'communicating ' + 'blockers ' + 'to ' + 'the ' + 'broader ' + 'team.'}], + 'competencyRatings': [ { 'competency': 'Design ' + 'Quality', + 'rating': 5}, + { 'competency': 'Collaboration', + 'rating': 4}, + { 'competency': 'Communication', + 'rating': 3}], + 'submittedAt': '2025-04-02T11:00:00Z'}]}, + { 'id': 'rev_2', + 'cycleId': 'rc_1', + 'revieweeId': 'user_4', + 'status': 'still_receiving', + 'nominatedPeerIds': ['user_6', 'user_1', 'user_11'], + 'reviews': []}, + { 'id': 'rev_3', + 'cycleId': 'rc_1', + 'revieweeId': 'user_5', + 'status': 'still_receiving', + 'nominatedPeerIds': ['user_7', 'user_3', 'user_18'], + 'reviews': []}, + { 'id': 'rev_4', + 'cycleId': 'rc_1', + 'revieweeId': 'user_6', + 'status': 'not_started', + 'nominatedPeerIds': [], + 'reviews': []}, + { 'id': 'rev_5', + 'cycleId': 'rc_1', + 'revieweeId': 'user_1', + 'status': 'not_started', + 'nominatedPeerIds': ['user_2', 'user_3', 'user_6'], + 'selfReviewSubmitted': False, + 'reviews': []}, + { 'id': 'rev_6', + 'cycleId': 'rc_1', + 'revieweeId': 'user_11', + 'status': 'still_receiving', + 'nominatedPeerIds': ['user_4', 'user_15'], + 'reviews': []}, + { 'id': 'rev_7', + 'cycleId': 'rc_1', + 'revieweeId': 'user_14', + 'status': 'not_started', + 'nominatedPeerIds': [], + 'reviews': []}, + { 'id': 'rev_8', + 'cycleId': 'rc_1', + 'revieweeId': 'user_15', + 'status': 'completed', + 'nominatedPeerIds': ['user_11', 'user_23'], + 'reviews': [ { 'reviewerId': 'user_6', + 'type': 'manager', + 'overallRating': 'meets_expectations', + 'responses': [ { 'question': 'What ' + 'are ' + 'this ' + "person's " + 'key ' + 'strengths?', + 'answer': 'Carlos ' + 'has ' + 'made ' + 'significant ' + 'improvements ' + 'to ' + 'our ' + 'CI/CD ' + 'pipeline. ' + 'Solid ' + 'technical ' + 'skills.'}, + { 'question': 'What ' + 'areas ' + 'could ' + 'this ' + 'person ' + 'improve?', + 'answer': 'Could ' + 'benefit ' + 'from ' + 'more ' + 'cross-team ' + 'visibility ' + 'and ' + 'communication.'}], + 'competencyRatings': [ { 'competency': 'Technical ' + 'Skills', + 'rating': 4}, + { 'competency': 'Infrastructure', + 'rating': 5}, + { 'competency': 'Communication', + 'rating': 3}], + 'submittedAt': '2025-04-04T09:00:00Z'}]}], + 'updates': [ { 'id': 'upd_1', + 'authorId': 'user_1', + 'weekOf': '2025-04-07', + 'accomplishments': 'Completed the API integration spec ' + 'for the payments module. Reviewed 3 ' + 'PRs from the engineering team. Led ' + 'the weekly product sync and ' + 'resolved the design-engineering ' + 'handoff bottleneck. Had productive ' + '1:1 with Marcus to align on Q2 ' + 'priorities.', + 'challenges': 'Still blocked on design approvals for ' + 'the settings page — Emily is slammed ' + 'with the v2.0 sprint. Also struggling to ' + 'get time with stakeholders for the ' + 'pricing strategy review.', + 'priorities': 'Finalize the settings page UI with ' + 'Emily. Begin QA testing planning for ' + 'payments flow. Schedule the pricing ' + 'strategy working session with Lisa and ' + 'Rachel.', + 'mood': 'good', + 'createdAt': '2025-04-11T16:00:00Z'}, + { 'id': 'upd_2', + 'authorId': 'user_1', + 'weekOf': '2025-03-31', + 'accomplishments': 'Wrapped up Q1 with a great CAB ' + 'presentation — received very ' + 'positive feedback from 8 enterprise ' + 'customers. Finalized the v2.0 ' + 'feature set and communicated it to ' + 'the engineering team. Reviewed and ' + 'approved 4 designs from Emily.', + 'challenges': "The API timeline risk with James's team " + 'needs attention. We may need to descope ' + 'one feature to hit the launch date. Also ' + 'dealing with ambiguity around the EMEA ' + 'expansion requirements.', + 'priorities': 'Kick off Q2 planning. Finalize v2.0 ' + 'scope decision by Tuesday. Set up ' + 'cross-functional sync for the EMEA ' + 'product requirements.', + 'mood': 'great', + 'createdAt': '2025-04-04T17:00:00Z'}, + { 'id': 'upd_3', + 'authorId': 'user_1', + 'weekOf': '2025-03-24', + 'accomplishments': 'Prepared and delivered the Customer ' + 'Advisory Board presentation. Got ' + 'the onboarding redesign shipped — ' + 'activation rates up 18% already. ' + 'Completed mid-quarter goal check-in ' + 'with Marcus.', + 'challenges': 'Stakeholder alignment continues to be ' + 'challenging on the pricing project. ' + 'Different teams have conflicting ' + 'requirements that need executive ' + 'arbitration.', + 'priorities': 'CAB follow-up action items. Continue ' + 'v2.0 design reviews. Resolve pricing ' + 'project stakeholder conflicts.', + 'mood': 'good', + 'createdAt': '2025-03-28T16:00:00Z'}, + { 'id': 'upd_4', + 'authorId': 'user_1', + 'weekOf': '2025-03-17', + 'accomplishments': 'Started the Q1 review cycle ' + 'self-assessment. Kicked off the ' + 'onboarding redesign project with ' + 'Emily. Resolved 2 critical product ' + 'bugs that were affecting enterprise ' + 'customers.', + 'challenges': 'Team bandwidth is stretched — 3 ' + 'concurrent initiatives is too many. Need ' + 'to make a prioritization call. Also ' + 'feeling a bit overwhelmed with the ' + 'review cycle on top of regular work.', + 'priorities': 'Complete self-assessment draft. ' + 'Prioritize the three current initiatives ' + 'and deprioritize one. Prepare for CAB ' + 'presentation.', + 'mood': 'okay', + 'createdAt': '2025-03-21T15:00:00Z'}], + 'growthAreas': [ { 'id': 'ga_1', + 'userId': 'user_1', + 'title': 'Improve my onboarding training skills', + 'description': 'Develop the ability to create and ' + 'deliver effective onboarding ' + 'programs that get new team members ' + 'productive quickly and feeling ' + 'welcomed into the team culture.', + 'status': 'active', + 'actions': [ { 'id': 'ga_1_a1', + 'text': 'Shadow 2 onboarding ' + 'sessions led by senior ' + 'trainers', + 'completed': True}, + { 'id': 'ga_1_a2', + 'text': 'Create an onboarding ' + 'checklist template for ' + 'new PMs', + 'completed': False}], + 'createdAt': '2024-11-15T10:00:00Z', + 'updatedAt': '2024-12-27T14:00:00Z'}, + { 'id': 'ga_2', + 'userId': 'user_1', + 'title': 'Establish cross-functional team of talent ' + 'experts', + 'description': 'Build a network of cross-functional ' + 'partners to improve ' + 'product-engineering collaboration ' + 'and reduce friction in the ' + 'development process.', + 'status': 'active', + 'actions': [ { 'id': 'ga_2_a1', + 'text': 'Schedule monthly ' + 'cross-functional ' + 'PM/Eng/Design working ' + 'sessions', + 'completed': True}, + { 'id': 'ga_2_a2', + 'text': 'Create a shared ' + 'decision-making ' + 'framework document', + 'completed': True}], + 'createdAt': '2024-10-01T10:00:00Z', + 'updatedAt': '2024-12-27T12:00:00Z'}, + { 'id': 'ga_3', + 'userId': 'user_1', + 'title': 'Learn data visualization techniques', + 'description': 'Develop proficiency in data ' + 'visualization tools and techniques ' + 'to better analyze product metrics ' + 'and communicate insights to ' + 'stakeholders.', + 'status': 'draft', + 'actions': [ { 'id': 'ga_3_a1', + 'text': 'Complete Tableau ' + 'fundamentals course', + 'completed': False}], + 'createdAt': '2025-01-10T09:00:00Z', + 'updatedAt': '2025-01-10T09:00:00Z'}], + 'careerTracks': [ { 'id': 'ct_1', + 'title': 'Product Manager', + 'levels': [ { 'id': 'ct_1_l1', + 'name': 'Associate Product ' + 'Manager', + 'level': 1, + 'competencies': [ { 'name': 'Product ' + 'Thinking', + 'description': 'Understands ' + 'basic ' + 'product ' + 'principles ' + 'and ' + 'user ' + 'needs. ' + 'Can ' + 'articulate ' + 'the ' + 'problem ' + 'being ' + 'solved.'}, + { 'name': 'Data ' + 'Analysis', + 'description': 'Comfortable ' + 'reading ' + 'dashboards ' + 'and ' + 'interpreting ' + 'key ' + 'metrics ' + 'with ' + 'guidance.'}, + { 'name': 'Execution', + 'description': 'Manages ' + 'sprint ' + 'tasks ' + 'and ' + 'delivers ' + 'features ' + 'with ' + 'close ' + 'manager ' + 'support.'}, + { 'name': 'Communication', + 'description': 'Communicates ' + 'clearly ' + 'in ' + 'writing ' + 'and ' + 'in ' + 'small ' + 'group ' + 'settings.'}]}, + { 'id': 'ct_1_l2', + 'name': 'Product Manager', + 'level': 2, + 'competencies': [ { 'name': 'Product ' + 'Thinking', + 'description': 'Defines ' + 'product ' + 'strategy ' + 'for ' + 'a ' + 'feature ' + 'area. ' + 'Conducts ' + 'independent ' + 'user ' + 'research.'}, + { 'name': 'Data ' + 'Analysis', + 'description': 'Designs ' + 'experiments, ' + 'interprets ' + 'A/B ' + 'test ' + 'results, ' + 'and ' + 'drives ' + 'metric ' + 'improvements.'}, + { 'name': 'Execution', + 'description': 'Owns ' + 'product ' + 'roadmap ' + 'for ' + 'a ' + 'feature ' + 'area. ' + 'Manages ' + 'stakeholder ' + 'expectations ' + 'independently.'}, + { 'name': 'Communication', + 'description': 'Presents ' + 'to ' + 'senior ' + 'leadership. ' + 'Writes ' + 'compelling ' + 'PRDs ' + 'and ' + 'strategy ' + 'docs.'}]}, + { 'id': 'ct_1_l3', + 'name': 'Senior Product Manager', + 'level': 3, + 'competencies': [ { 'name': 'Product ' + 'Thinking', + 'description': 'Defines ' + 'multi-quarter ' + 'strategy ' + 'for ' + 'a ' + 'product ' + 'area. ' + 'Anticipates ' + 'market ' + 'trends.'}, + { 'name': 'Data ' + 'Analysis', + 'description': 'Leads ' + 'data-driven ' + 'culture. ' + 'Mentors ' + 'others ' + 'on ' + 'experimentation ' + 'best ' + 'practices.'}, + { 'name': 'Execution', + 'description': 'Manages ' + 'complex, ' + 'cross-functional ' + 'initiatives. ' + 'Unblocks ' + 'organizational ' + 'bottlenecks.'}, + { 'name': 'Communication', + 'description': 'Executive ' + 'presence. ' + 'Influences ' + 'decisions ' + 'across ' + 'the ' + 'organization.'}]}]}, + { 'id': 'ct_2', + 'title': 'Software Engineer', + 'levels': [ { 'id': 'ct_2_l1', + 'name': 'Junior Engineer', + 'level': 1, + 'competencies': [ { 'name': 'Technical ' + 'Skills', + 'description': 'Writes ' + 'clean ' + 'code ' + 'in ' + 'primary ' + 'language. ' + 'Completes ' + 'well-defined ' + 'tasks ' + 'independently.'}, + { 'name': 'Problem ' + 'Solving', + 'description': 'Debugs ' + 'simple ' + 'issues. ' + 'Asks ' + 'for ' + 'help ' + 'when ' + 'stuck ' + 'for ' + 'more ' + 'than ' + 'an ' + 'hour.'}, + { 'name': 'Collaboration', + 'description': 'Participates ' + 'constructively ' + 'in ' + 'code ' + 'reviews. ' + 'Asks ' + 'good ' + 'questions.'}, + { 'name': 'Delivery', + 'description': 'Meets ' + 'sprint ' + 'commitments ' + 'with ' + 'occasional ' + 'help.'}, + { 'name': 'Learning', + 'description': 'Proactively ' + 'learns ' + 'from ' + 'feedback ' + 'and ' + 'online ' + 'resources.'}]}, + { 'id': 'ct_2_l2', + 'name': 'Software Engineer', + 'level': 2, + 'competencies': [ { 'name': 'Technical ' + 'Skills', + 'description': 'Proficient ' + 'in ' + 'the ' + 'tech ' + 'stack. ' + 'Writes ' + 'well-tested, ' + 'maintainable ' + 'code.'}, + { 'name': 'Problem ' + 'Solving', + 'description': 'Diagnoses ' + 'and ' + 'resolves ' + 'complex ' + 'bugs. ' + 'Proposes ' + 'solutions ' + 'independently.'}, + { 'name': 'Collaboration', + 'description': 'Mentors ' + 'junior ' + 'engineers. ' + 'Gives ' + 'substantive ' + 'code ' + 'review ' + 'feedback.'}, + { 'name': 'Delivery', + 'description': 'Reliable ' + 'sprint ' + 'delivery. ' + 'Manages ' + 'personal ' + 'work ' + 'estimates ' + 'accurately.'}, + { 'name': 'System ' + 'Design', + 'description': 'Contributes ' + 'meaningfully ' + 'to ' + 'feature ' + 'architecture ' + 'discussions.'}]}, + { 'id': 'ct_2_l3', + 'name': 'Senior Engineer', + 'level': 3, + 'competencies': [ { 'name': 'Technical ' + 'Skills', + 'description': 'Deep ' + 'expertise ' + 'in ' + 'multiple ' + 'areas. ' + 'Shapes ' + 'team ' + 'technical ' + 'standards.'}, + { 'name': 'Problem ' + 'Solving', + 'description': 'Solves ' + 'ambiguous, ' + 'high-impact ' + 'technical ' + 'problems ' + 'across ' + 'systems.'}, + { 'name': 'Collaboration', + 'description': 'Elevates ' + 'team ' + 'quality ' + 'through ' + 'mentorship ' + 'and ' + 'process ' + 'improvement.'}, + { 'name': 'Delivery', + 'description': 'Leads ' + 'multi-sprint ' + 'initiatives. ' + 'Manages ' + 'technical ' + 'risk.'}, + { 'name': 'System ' + 'Design', + 'description': 'Leads ' + 'architectural ' + 'decisions ' + 'for ' + 'complex ' + 'systems.'}]}, + { 'id': 'ct_2_l4', + 'name': 'Staff Engineer', + 'level': 4, + 'competencies': [ { 'name': 'Technical ' + 'Skills', + 'description': 'Organization-wide ' + 'technical ' + 'authority. ' + 'Evaluates ' + 'and ' + 'adopts ' + 'new ' + 'technologies.'}, + { 'name': 'Problem ' + 'Solving', + 'description': 'Frames ' + 'and ' + 'solves ' + 'the ' + 'highest-leverage ' + 'technical ' + 'problems ' + 'in ' + 'the ' + 'org.'}, + { 'name': 'Collaboration', + 'description': 'Partners ' + 'with ' + 'leadership ' + 'across ' + 'engineering, ' + 'product, ' + 'and ' + 'design.'}, + { 'name': 'Delivery', + 'description': 'Aligns ' + 'technical ' + 'roadmap ' + 'with ' + 'company ' + 'strategy.'}, + { 'name': 'System ' + 'Design', + 'description': 'Defines ' + 'company-wide ' + 'architectural ' + 'principles ' + 'and ' + 'patterns.'}]}]}], + 'surveys': [ { 'id': 'survey_1', + 'title': 'Q1 2025 Engagement Pulse', + 'status': 'active', + 'startDate': '2025-03-20', + 'endDate': '2025-04-20', + 'responseRate': 78, + 'questions': [ { 'id': 'sq_1', + 'text': 'I feel valued and ' + 'recognized for my ' + 'contributions at work.', + 'type': 'likert', + 'category': 'Belonging'}, + { 'id': 'sq_2', + 'text': 'My manager actively ' + 'supports my career ' + 'development and growth.', + 'type': 'likert', + 'category': 'Manager ' + 'Effectiveness'}, + { 'id': 'sq_3', + 'text': 'I have the tools, ' + 'resources, and ' + 'information I need to do ' + 'my job well.', + 'type': 'likert', + 'category': 'Enablement'}, + { 'id': 'sq_4', + 'text': 'How likely are you to ' + 'recommend Evergreen ' + 'Technologies as a great ' + 'place to work? (0 = not ' + 'at all, 10 = extremely ' + 'likely)', + 'type': 'enps', + 'category': 'eNPS'}, + { 'id': 'sq_5', + 'text': 'What is one thing we ' + 'could do to improve your ' + 'experience at Evergreen ' + 'Technologies?', + 'type': 'open_text', + 'category': 'Open Feedback'}], + 'userHasResponded': False}, + { 'id': 'survey_2', + 'title': 'Q3 2024 Engagement Pulse', + 'status': 'closed', + 'startDate': '2024-09-01', + 'endDate': '2024-09-20', + 'responseRate': 82, + 'questions': [ { 'id': 'sq2_1', + 'text': 'I feel a strong sense of ' + 'belonging at this ' + 'company.', + 'type': 'likert', + 'category': 'Belonging'}, + { 'id': 'sq2_2', + 'text': 'My manager gives me ' + 'useful feedback to help ' + 'me grow.', + 'type': 'likert', + 'category': 'Manager ' + 'Effectiveness'}, + { 'id': 'sq2_3', + 'text': 'I am proud to work at ' + 'this company.', + 'type': 'likert', + 'category': 'Pride'}, + { 'id': 'sq2_4', + 'text': 'How likely are you to ' + 'recommend us as a ' + 'workplace?', + 'type': 'enps', + 'category': 'eNPS'}, + { 'id': 'sq2_5', + 'text': 'Any additional feedback ' + 'for leadership?', + 'type': 'open_text', + 'category': 'Open Feedback'}], + 'userHasResponded': True}], + 'surveyResults': { 'survey_1': { 'overallScore': 4.1, + 'eNPS': 32, + 'categoryScores': { 'Belonging': 4.2, + 'Manager Effectiveness': 4.4, + 'Enablement': 3.8}, + 'responseRate': 78}, + 'survey_2': { 'overallScore': 3.9, + 'eNPS': 28, + 'categoryScores': { 'Belonging': 4, + 'Manager Effectiveness': 4.1, + 'Pride': 3.7}, + 'responseRate': 82}}, + 'tasks': [ { 'id': 'task_1', + 'title': 'Submit self-review for Q1 2025 Performance ' + 'Review', + 'type': 'review', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-15', + 'priority': 'high', + 'completed': False, + 'relatedEntityId': 'rc_1', + 'relatedEntityType': 'review_cycle', + 'createdAt': '2025-03-15T09:00:00Z'}, + { 'id': 'task_2', + 'title': 'Complete Q1 Engagement Pulse survey', + 'type': 'survey', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-20', + 'priority': 'medium', + 'completed': False, + 'relatedEntityId': 'survey_1', + 'relatedEntityType': 'survey', + 'createdAt': '2025-03-20T09:00:00Z'}, + { 'id': 'task_3', + 'title': 'Update progress on "Launch v2.0 of the ' + 'platform" goal', + 'type': 'goal', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-12', + 'priority': 'medium', + 'completed': False, + 'relatedEntityId': 'goal_1', + 'relatedEntityType': 'goal', + 'createdAt': '2025-04-08T09:00:00Z'}, + { 'id': 'task_4', + 'title': 'Prepare talking points for 1:1 with Marcus', + 'type': 'general', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-14', + 'priority': 'low', + 'completed': False, + 'relatedEntityId': 'oo_1', + 'relatedEntityType': '1on1', + 'createdAt': '2025-04-09T09:00:00Z'}, + { 'id': 'task_5', + 'title': "Review Emily's feedback request", + 'type': 'feedback', + 'assigneeId': 'user_1', + 'dueDate': '2025-04-13', + 'priority': 'medium', + 'completed': False, + 'relatedEntityId': 'fb_9', + 'relatedEntityType': 'feedback', + 'createdAt': '2025-04-08T15:00:00Z'}], + 'celebrations': [ { 'id': 'celeb_1', + 'type': 'birthday', + 'userId': 'user_4', + 'date': '2025-04-12', + 'details': None}, + { 'id': 'celeb_2', + 'type': 'birthday', + 'userId': 'user_5', + 'date': '2025-04-15', + 'details': None}, + { 'id': 'celeb_3', + 'type': 'anniversary', + 'userId': 'user_6', + 'date': '2025-04-20', + 'details': '7 years'}, + { 'id': 'celeb_4', + 'type': 'new_hire', + 'userId': 'user_8', + 'date': '2025-04-08', + 'details': None}, + { 'id': 'celeb_5', + 'type': 'new_hire', + 'userId': 'user_19', + 'date': '2025-04-05', + 'details': None}, + { 'id': 'celeb_6', + 'type': 'anniversary', + 'userId': 'user_3', + 'date': '2025-04-22', + 'details': '3 years'}, + { 'id': 'celeb_7', + 'type': 'birthday', + 'userId': 'user_9', + 'date': '2025-04-25', + 'details': None}, + { 'id': 'celeb_8', + 'type': 'new_hire', + 'userId': 'user_14', + 'date': '2025-04-01', + 'details': None}, + { 'id': 'celeb_9', + 'type': 'birthday', + 'userId': 'user_22', + 'date': '2025-04-18', + 'details': None}, + { 'id': 'celeb_10', + 'type': 'anniversary', + 'userId': 'user_13', + 'date': '2025-04-11', + 'details': '6 years'}, + { 'id': 'celeb_11', + 'type': 'new_hire', + 'userId': 'user_18', + 'date': '2025-04-03', + 'details': None}], + 'company': { 'name': 'Evergreen Technologies, Inc', + 'departments': [ 'Engineering', + 'Product', + 'Design', + 'Marketing', + 'Sales', + 'People Operations', + 'Finance', + 'Executive'], + 'values': [ 'Innovation', + 'Teamwork', + 'Customer Focus', + 'Integrity', + 'Growth Mindset'], + 'headcount': 24}, + 'careerVision': 'Build a world-class product marketing function at ' + 'Evergreen Technologies', + 'compensation': { 'baseSalary': 125000, + 'bonusTarget': 15, + 'equityShares': 5000, + 'currency': 'USD', + 'history': [ { 'date': 'January 2025', + 'type': 'Merit Increase', + 'oldValue': '$118,000', + 'newValue': '$125,000'}, + { 'date': 'March 2023', + 'type': 'Promotion', + 'oldValue': '$105,000', + 'newValue': '$118,000'}, + { 'date': 'March 2021', + 'type': 'Starting Salary', + 'oldValue': '—', + 'newValue': '$105,000'}]}}} + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, start_new_session=True) + time.sleep(delay_sec) + + +for name, url in MOCK_URLS.items(): + resp = requests.post(f'{url}/post?sid={sid}', + json={'action': 'set', 'state': STATES[name]}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None' + print(f'State injected: {name} sid={sid}') + +# Open the PRIMARY app as the main window first, then open every other +# involved mock as an additional browser tab so the agent can see/reach all +# relevant apps (e.g. read the email in the Gmail tab AND post in Slack). +# Without this, secondary-app data is injected but has no on-screen entry +# point, and the agent wastes its budget hunting for a non-existent client. +launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}') +for _name, _url in MOCK_URLS.items(): + if _url == PRIMARY_URL: + continue + launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0) + print(f'Opened tab: {_name} at {_url}/?sid={sid}') diff --git a/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward.py b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..2f0182d3e4a1987679290898e56e7105dc3fdc26 --- /dev/null +++ b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward.py @@ -0,0 +1,108 @@ +""" +Reward Script: em_stale_mr_nudge_b95 +Task ID: f331e349-9a63-51ae-b592-8b21f8fc65ac +Domain: mock_websites +Mocks: gitlab_mock, slack_mock, lattice_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.25] slack_new_msg + - [0.3] nudge names the stale MR (Resolve login issues) + - [0.15] does NOT cite the already-merged MR + - [0.3] Lattice feedback to James Kim (user_4) about review latency +""" +import re +import sys + +import requests + +MOCK_URLS = { + "gitlab_mock": "http://28.7.186.212:8157", + "slack_mock": "http://28.7.186.212:8198", + "lattice_mock": "http://28.7.186.212:8175" +} +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: new message by user_1 in #engineering +c0_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c0_seed = set(SEED.get('slack_mock:engineering', [])) +c0_new = [m for m in c0_msgs if m.get('messageId') not in c0_seed and m.get('senderId') == 'user_1'] +c0_blob = _lc(' '.join((m.get('content') or '') for m in c0_new)) +if c0_new: + print('PASS: new message by user_1 in #engineering (0.25)') + total += 0.25 +else: + print('FAIL: no new user_1 message in #engineering') + +# c1: slack #engineering contains (nudge names the stale MR (Resolve login issues)) +c1_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c1_seed = set(SEED.get('slack_mock:engineering', [])) +c1_blob = _lc(' '.join((m.get('content') or '') for m in c1_msgs if m.get('messageId') not in c1_seed and m.get('senderId') == 'user_1')) +if any(t in c1_blob for t in ['resolve login', 'login issues', '!1', 'mr #1', 'mr 1']): + print('PASS: nudge names the stale MR (Resolve login issues) (0.3)') + total += 0.3 +else: + print('FAIL: nudge names the stale MR (Resolve login issues)') + +# c2: slack #engineering does NOT falsely include (does NOT cite the already-merged MR) +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 c2_new_exists := any(m.get('messageId') not in c2_seed and m.get('senderId')=='user_1' for m in c2_msgs): + if not any(t in c2_blob for t in ['dark mode']): + print('PASS: does NOT cite the already-merged MR (0.15)') + total += 0.15 + else: + print('FAIL: does NOT cite the already-merged MR') +else: + print('FAIL: does NOT cite the already-merged MR (no new message at all)') + +# c3: new lattice feedback to James Kim (user_4) (Lattice feedback to James Kim (user_4) about review latency) +c3_seed = {f.get('id') for f in ((STATES['lattice_mock'].get('initial_state') or {}).get('feedback') or [])} +c3_new = [f for f in (cur('lattice_mock').get('feedback') or []) if f.get('id') not in c3_seed and f.get('toUserId') == 'user_4'] +c3_txt = _lc(' '.join(f.get('body','') for f in c3_new)) +if c3_new and any(t in c3_txt for t in ['review', 'mr', 'merge request', 'velocity']): + print('PASS: Lattice feedback to James Kim (user_4) about review latency (0.3)') + total += 0.3 +else: + print('FAIL: Lattice feedback to James Kim (user_4) about review latency') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward_label.json b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..6916fa13f752868d71ff18c6f7cba3ff31a3364a --- /dev/null +++ b/legacy/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward_label.json @@ -0,0 +1,62 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/f331e349-9a63-51ae-b592-8b21f8fc65ac/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:26:09", + "label": { + "task_id": "f331e349-9a63-51ae-b592-8b21f8fc65ac", + "domain": "mock_websites", + "summary": "验证在 Slack #engineering 频道由 user_1 发送关于陈旧 MR (Resolve login issues) 的提醒消息且不引用已合并 MR,同时在 Lattice 中向 James Kim (user_4) 提交关于 review latency 的新反馈", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "slack_mock", + "lattice_mock", + "gitlab_mock" + ], + "scoring_components": [ + { + "name": "c0: slack_new_msg", + "weight": 0.25, + "description": "检查 Slack #engineering 频道是否有 user_1 发送的新消息", + "check_logic": "从 slack_mock current_state 的 messages.engineering 中过滤出 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId 为 'user_1' 的消息;若列表非空则通过", + "pass_condition": "存在至少一条 user_1 在 #engineering 频道发送的新消息" + }, + { + "name": "c1: nudge names the stale MR", + "weight": 0.3, + "description": "检查 Slack #engineering 中 user_1 的新消息内容是否提到了指定的陈旧 MR (Resolve login issues)", + "check_logic": "将 user_1 在 #engineering 的新消息内容拼接为小写字符串,检查是否包含 'resolve login'、'login issues'、'!1'、'mr #1'、'mr 1' 中的任意一个", + "pass_condition": "消息内容小写后包含任一指定关键词" + }, + { + "name": "c2: does NOT cite the already-merged MR", + "weight": 0.15, + "description": "检查 Slack #engineering 中 user_1 的新消息没有错误引用已合并的 MR", + "check_logic": "先确认存在 user_1 的新消息 (c2_new_exists);然后将新消息内容拼接为小写字符串,检查是否不包含 'dark mode'", + "pass_condition": "存在新消息且消息内容小写后不包含 'dark mode'" + }, + { + "name": "c3: Lattice feedback to James Kim", + "weight": 0.3, + "description": "检查 Lattice 中是否向 James Kim (user_4) 提交了关于 review latency 的新反馈", + "check_logic": "从 lattice_mock initial_state 的 feedback 中提取 id 作为 seed;在 current_state 的 feedback 中找出 id 不在 seed 中且 toUserId 为 'user_4' 的新反馈;将新反馈的 body 拼接为小写字符串,检查是否包含 'review'、'mr'、'merge request'、'velocity' 中的任意一个", + "pass_condition": "存在至少一条给 user_4 的新反馈,且反馈内容小写后包含任一指定关键词" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 REWARD: 0.0 后退出", + "从任一 MOCK_URLS 获取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后退出", + "c0 失败:#engineering 中无 user_1 的新消息,不得 0.25 分", + "c1 失败:新消息未提及 stale MR 关键词,不得 0.3 分", + "c2 失败:无新消息或消息中包含 'dark mode',不得 0.15 分", + "c3 失败:无给 user_4 的新反馈或反馈内容不含关键词,不得 0.3 分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后向 gitlab_mock、slack_mock、lattice_mock 发送请求获取当前状态,任一失败也返回 0.0。接着分四项评分:c0 检查 slack_mock 的 #engineering 频道是否有 user_1 的新消息(排除 seed),有则加 0.25;c1 检查这些新消息文本是否包含陈旧 MR 'Resolve login issues' 的相关关键词,有则加 0.3;c2 在确认有新消息的前提下,检查消息文本是否不包含已合并 MR 的关键词 'dark mode',满足则加 0.15;c3 对比 lattice_mock 的 initial_state 与 current_state,找出给 user_4 的新 feedback,若内容包含 review latency 相关关键词则加 0.3。最后将总分通过 min(total, 1.0) 钳制并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 看是 `f331e349-9a63-51ae-b592-8b21f8fc65ac`,但 docstring 第一行也写了 `Reward Script: em_stale_mr_nudge_b95`。根据要求,\"从文件 docstring 中提取的任务 ID,如 se_review_006;若无法确定则填 null\"。这里明确写了 `Task ID: f331e349-9a63-51ae-b592-8b21f8fc65ac`,所以 task_id 应该是这个 UUID。\n\n2. **Domain**: docstring 中写了 `Domain: mock_websites`。\n\n3. **Summary**: 一句话概括。这个脚本验证在 Slack #engineering 频道发送关于陈旧 MR (Resolve login issues) 的提醒消息,不引用已合并的 MR,并在 Lattice 中给 James Kim (user_4) 发送关于 review latency 的反馈。\n\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n\n5. **data_sources**: `gitlab_mock`, `slack_mock`, `lattice_mock`,以及 `/tmp/task_web_sid`。\n\n6. **scoring_components**:\n - Component 1 (c0): slack_new_msg, weight 0.25。检查 slack_mock #engineering 频道中 user_1 发送的新消息(排除 seed 中的消息)。\n - Component 2 (c1): nudge names the stale MR, weight 0.3。检查 user_1 在 #engineering 的新消息内容是否包含 'resolve login', 'login issues', '!1', 'mr #1', 'mr 1'。\n - Component 3 (c2): does NOT cite the already-merged MR, weight 0.15。检查 user_1 在 #engineering 的新消息是否不包含 'dark mode'(前提是确实有新消息)。\n - Component 4 (c3): Lattice feedback to James Kim, weight 0.3。检查 lattice_mock 中是否有新的给 user_4 的 feedback,且内容包含 'review', 'mr', 'merge request', 'velocity'。\n\n7. **total_max_score**: 1.0\n\n8. **score_aggregation**: 各组件分数相加,最后 `round(min(total, 1.0), 4)`,即相加后钳制到 1.0。\n\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 获取 mock 状态失败(requests 异常):打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - c0 失败:没有新消息,不得 0.25 分\n - c1 失败:消息未提及 stale MR,不得 0.3 分\n - c2 失败:消息引用了已合并 MR(包含 'dark mode')或根本没有新消息,不得 0.15 分\n - c3 失败:没有新 feedback 或内容不包含关键词,不得 0.3 分\n\n10. **scoring_logic_explanation**: 详细中文解释,按执行顺序。\n\n11. **confidence**: 1.0,因为代码逻辑清晰完整。\n\n让我再仔细检查一下 c2 的逻辑:\n```python\nif c2_new_exists := any(m.get('messageId') not in c2_seed and m.get('senderId')=='user_1' for m in c2_msgs):\n if not any(t in c2_blob for t in ['dark mode']):\n print('PASS...')\n total += 0.15\n else:\n print('FAIL...')\nelse:\n print('FAIL: does NOT cite the already-merged MR (no new message at all)')\n```\n所以 c2 的前提是有新消息,然后检查不包含 'dark mode'。\n\nc3 的逻辑:\n```python\nc3_seed = {f.get('id') for f in ((STATES['lattice_mock'].get('initial_state') or {}).get('feedback') or [])}\nc3_new = [f for f in (cur('lattice_mock').get('feedback') or []) if f.get('id') not in c3_seed and f.get('toUserId') == 'user_4']\nc3_txt = _lc(' '.join(f.get('body','') for f in c3_new))\nif c3_new and any(t in c3_txt for t in ['review', 'mr', 'merge request', 'velocity']):\n```\n注意这里用的是 `STATES['lattice_mock']` 直接获取 initial_state,而不是用 `cur()`。`cur()` 获取的是 current_state。所以 seed 是从 initial_state 的 feedback 中获取的 id 集合,然后与 current_state 的 feedback 比较。\n\n所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\nJSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"f331e349-9a63-51ae-b592-8b21f8fc65ac\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Slack #engineering 频道由 user_1 发送关于陈旧 MR (Resolve login issues) 的提醒消息且不引用已合并 MR,同时在 Lattice 中向 James Kim (user_4) 提交关于 review latency 的新反馈\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"slack_mock\", \"lattice_mock\", \"gitlab_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"c0: slack_new_msg\",\n \"weight\": 0.25,\n \"description\": \"检查 Slack #engineering 频道是否有 user_1 发送的新消息\",\n \"check_logic\": \"从 slack_mock current_state 的 messages.engineering 中过滤出 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId 为 'user_1' 的消息;若列表非空则通过\",\n \"pass_condition\": \"存在至少一条 user_1 在 #engineering 频道发送的新消息\"\n },\n {\n \"name\": \"c1: nudge names the stale MR\",\n \"weight\": 0.3,\n \"description\": \"检查 Slack #engineering 中 user_1 的新消息内容是否提到了指定的陈旧 MR (Resolve login issues)\",\n \"check_logic\": \"将 user_1 在 #engineering 的新消息内容拼接为小写字符串,检查是否包含 'resolve login'、'login issues'、'!1'、'mr #1'、'mr 1' 中的任意一个\",\n \"pass_condition\": \"消息内容小写后包含任一指定关键词\"\n },\n {\n \"name\": \"c2: does NOT cite the already-merged MR\",\n \"weight\": 0.15,\n \"description\": \"检查 Slack #engineering 中 user_1 的新消息没有错误引用已合并的 MR\",\n \"check_logic\": \"先确认存在 user_1 的新消息 (c2_new_exists);然后将新消息内容拼接为小写字符串,检查是否不包含 'dark mode'\",\n \"pass_condition\": \"存在新消息且消息内容小写后不包含 'dark mode'\"\n },\n {\n \"name\": \"c3: Lattice feedback to James Kim\",\n \"weight\": 0.3,\n \"description\": \"检查 Lattice 中是否向 James Kim (user_4) 提交了关于 review latency 的新反馈\",\n \"check_logic\": \"从 lattice_mock initial_state 的 feedback 中提取 id 作为 seed;在 current_state 的 feedback 中找出 id 不在 seed 中且 toUserId 为 'user_4' 的新反馈;将新反馈的 body 拼接为小写字符串,检查是否包含 'review'、'mr'、'merge request'、'velocity' 中的任意一个\",\n \"pass_condition\": \"存在至少一条给 user_4 的新反馈,且反馈内容小写后包含任一指定关键词\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 REWARD: 0.0 后退出\",\n \"从任一 MOCK_URLS 获取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后退出\",\n \"c0 失败:#engineering 中无 user_1 的新消息,不得 0.25 分\",\n \"c1 失败:新消息未提及 stale MR 关键词,不得 0.3 分\",\n \"c2 失败:无新消息或消息中包含 'dark mode',不得 0.15 分\",\n \"c3 失败:无给 user_4 的新反馈或反馈内容不含关键词,不得 0.3 分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后向 gitlab_mock、slack_mock、lattice_mock 发送请求获取当前状态,任一失败也返回 0.0。接着分四项评分:c0 检查 slack_mock 的 #engineering 频道是否有 user_1 的新消息(排除 seed),有则加 0.25;c1 检查这些新消息文本是否包含陈旧 MR 'Resolve login issues' 的相关关键词,有则加 0.3;c2 在确认有新消息的前提下,检查消息文本是否不包含已合并 MR 的关键词 'dark mode',满足则加 0.15;c3 对比 lattice_mock 的 initial_state 与 current_state,找出给 user_4 的新 feedback,若内容包含 review latency 相关关键词则加 0.3。最后将总分通过 min(total, 1.0) 钳制并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查是否符合所有要求:\n- 只输出 JSON 对象:是\n- 无 Markdown 代码块:是\n- 无额外解释:是\n- 无 thinking 标签:是\n- 第一个字符是 {,最后一个是 }:是\n- task_id 从 docstring 提取:是\n- domain 从 docstring 提取:是\n- is_placeholder: false:是\n- data_sources 包含所有来源:是\n- weight 显式给出:是\n- 字符串 value 使用中文,标识符保留原样:是\n- confidence: 1.0:是\n\n看起来没问题。 {\"task_id\":\"f331e349-9a63-51ae-b592-8b21f8fc65ac\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Slack #engineering 频道由 user_1 发送关于陈旧 MR (Resolve login issues) 的提醒消息且不引用已合并 MR,同时在 Lattice 中向 James Kim (user_4) 提交关于 review latency 的新反馈\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"slack_mock\",\"lattice_mock\",\"gitlab_mock\"],\"scoring_components\":[{\"name\":\"c0: slack_new_msg\",\"weight\":0.25,\"description\":\"检查 Slack #engineering 频道是否有 user_1 发送的新消息\",\"check_logic\":\"从 slack_mock current_state 的 messages.engineering 中过滤出 messageId 不在 SEED['slack_mock:engineering'] 中且 senderId 为 'user_1' 的消息;若列表非空则通过\",\"pass_condition\":\"存在至少一条 user_1 在 #engineering 频道发送的新消息\"},{\"name\":\"c1: nudge names the stale MR\",\"weight\":0.3,\"description\":\"检查 Slack #engineering 中 user_1 的新消息内容是否提到了指定的陈旧 MR (Resolve login issues)\",\"check_logic\":\"将 user_1 在 #engineering 的新消息内容拼接为小写字符串,检查是否包含 'resolve login'、'login issues'、'!1'、'mr #1'、'mr 1' 中的任意一个\",\"pass_condition\":\"消息内容小写后包含任一指定关键词\"},{\"name\":\"c2: does NOT cite the already-merged MR\",\"weight\":0.15,\"description\":\"检查 Slack #engineering 中 user_1 的新消息没有错误引用已合并的 MR\",\"check_logic\":\"先确认存在 user_1 的新消息 (c2_new_exists);然后将新消息内容拼接为小写字符串,检查是否不包含 'dark mode'\",\"pass_condition\":\"存在新消息且消息内容小写后不包含 'dark mode'\"},{\"name\":\"c3: Lattice feedback to James Kim\",\"weight\":0.3,\"description\":\"检查 Lattice 中是否向 James Kim (user_4) 提交了关于 review latency 的新反馈\",\"check_logic\":\"从 lattice_mock initial_state 的 feedback 中提取 id 作为 seed;在 current_state 的 feedback 中找出 id 不在 seed 中且 toUserId 为 'user_4' 的新反馈;将新反馈的 body 拼接为小写字符串,检查是否包含 'review'、'mr'、'merge request'、'velocity' 中的任意一个\",\"pass_condition\":\"存在至少一条给 user_4 的新反馈,且反馈内容小写后包含任一指定关键词\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 REWARD: 0.0 后退出\",\"从任一 MOCK_URLS 获取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后退出\",\"c0 失败:#engineering 中无 user_1 的新消息,不得 0.25 分\",\"c1 失败:新消息未提及 stale MR 关键词,不得 0.3 分\",\"c2 失败:无新消息或消息中包含 'dark mode',不得 0.15 分\",\"c3 失败:无给 user_4 的新反馈或反馈内容不含关键词,不得 0.3 分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后向 gitlab_mock、slack_mock、lattice_mock 发送请求获取当前状态,任一失败也返回 0.0。接着分四项评分:c0 检查 slack_mock 的 #engineering 频道是否有 user_1 的新消息(排除 seed),有则加 0.25;c1 检查这些新消息文本是否包含陈旧 MR 'Resolve login issues' 的相关关键词,有则加 0.3;c2 在确认有新消息的前提下,检查消息文本是否不包含已合并 MR 的关键词 'dark mode',满足则加 0.15;c3 对比 lattice_mock 的 initial_state 与 current_state,找出给 user_4 的新 feedback,若内容包含 review latency 相关关键词则加 0.3。最后将总分通过 min(total, 1.0) 钳制并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/hr_handbook_002/_cua_gym_vm_bridge.sh b/legacy/hr_handbook_002/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/hr_handbook_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://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/hr_handbook_002/initial_setup.py b/legacy/hr_handbook_002/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..178b62805cd07433e85116210358183834dd5109 --- /dev/null +++ b/legacy/hr_handbook_002/initial_setup.py @@ -0,0 +1,198 @@ +""" +Initial Setup: HR Handbook update — pre-task state. +Task ID: hr_handbook_002 +Domain: mock_websites (multi-mock: google_docs + docusign + slack) + +Cross-VM model note: + initial_setup.py runs ONLY on initial_env; golden_patch.py runs ONLY on + golden_env. The two VMs have SEPARATE filesystems, but mock state lives on a + single shared remote server keyed by `sid`. To keep reward(initial_env)==0 and + reward(golden_env)==1, the two environments MUST use DIFFERENT sids (otherwise + golden_patch's write would also change what initial_env's reward reads). + Hence sids are DETERMINISTIC per env (not a shared random UUID). Each script + writes its own VM's /tmp/task_web_sid so reward.py picks up the right sid. +""" +import os +import shlex +import subprocess +import time + +import requests + +MOCKS = { + 'google_docs': 'http://28.7.186.212:8162', + 'docusign': 'http://28.7.186.212:8150', + 'slack': 'http://28.7.186.212:8198', +} + +# This script only ever runs on initial_env → use the INITIAL sid. +SID = 'hr-handbook-002-initial' +with open('/tmp/task_web_sid', 'w') as f: + f.write(SID) +print(f'sid={SID}') + + +# --------------------------------------------------------------------------- +# State builders (shared shape with golden_patch.py so state_diff is clean). +# --------------------------------------------------------------------------- +HANDBOOK_HTML = ( + "

Employee Handbook

" + "

Welcome to Northbridge Technologies. This handbook outlines the " + "policies, benefits, and expectations for all employees.

" + "

Introduction

" + "

Northbridge Technologies is committed to fostering an inclusive, " + "collaborative, and high-performing workplace. This handbook is reviewed " + "annually by the People Operations team.

" + "

Code of Conduct

" + "

All employees are expected to act with integrity, treat colleagues " + "with respect, and comply with company policies and applicable laws. " + "Violations should be reported to People Operations.

" + "

Paid Time Off

" + "

Full-time employees accrue 20 days of paid time off (PTO) per year, " + "plus 11 company-observed holidays. PTO accrues monthly and may be carried " + "over up to a maximum of 10 days into the following year. Requests should " + "be submitted in Workday at least two weeks in advance.

" + "

Health Benefits

" + "

The company provides medical, dental, and vision coverage effective on " + "the first day of employment. Employees may enroll dependents during open " + "enrollment or after a qualifying life event.

" + "

Remote Work Policy

" + "

Employees may work remotely up to three days per week with manager " + "approval. All remote workers must remain reachable during core hours of " + "10:00 AM to 4:00 PM in their local time zone.

" +) + + +def build_gdocs_state(): + return { + "currentUser": {"id": "user-1", "name": "Morgan Davis", "email": "morgan.davis@company.com", "avatar": "https://picsum.photos/100/100?random=user1"}, + "users": [ + {"id": "user-1", "name": "Morgan Davis", "email": "morgan.davis@company.com", "avatar": "https://picsum.photos/100/100?random=user1"}, + {"id": "user-2", "name": "Alex Rivera", "email": "alex@company.com", "avatar": "https://picsum.photos/100/100?random=user2"}, + {"id": "user-3", "name": "Blair Thompson", "email": "blair@company.com", "avatar": "https://picsum.photos/100/100?random=user3"}, + {"id": "user-4", "name": "Chen Wei", "email": "chen@company.com", "avatar": "https://picsum.photos/100/100?random=user4"}, + ], + "documents": { + "doc-handbook": { + "id": "doc-handbook", "title": "Employee Handbook", "content": HANDBOOK_HTML, + "ownerId": "user-1", "starred": True, + "created": "2025-01-06T09:00:00Z", "updated": "2025-05-12T15:30:00Z", + "sharedWith": [ + {"userId": "user-2", "permission": "viewer"}, + {"userId": "user-3", "permission": "viewer"}, + {"userId": "user-4", "permission": "viewer"}, + ], + "linkSharing": {"enabled": True, "permission": "viewer"}, + }, + "doc-orgchart": { + "id": "doc-orgchart", "title": "2025 Org Chart Notes", + "content": "

2025 Org Chart Notes

Draft notes for the engineering reorg.

", + "ownerId": "user-1", "starred": False, + "created": "2025-02-20T11:00:00Z", "updated": "2025-03-01T10:15:00Z", + "sharedWith": [], "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + }, + "comments": [], + "ui": {"currentDocId": "doc-handbook", "sidebarOpen": False, "sidebarTab": "comments", "shareDialogOpen": False, "findReplaceOpen": False, "viewMode": "editing", "zoom": 100, "documentListView": "grid", "searchQuery": ""}, + } + + +def build_docusign_state(): + return { + "user": {"id": "user_1", "name": "Morgan Davis", "email": "morgan.davis@company.com", "title": "Director of People Operations", "company": "Northbridge Technologies", "avatar": "https://picsum.photos/seed/morgan/100/100", "signatureDataUrl": "", "initialsDataUrl": "", "memberSince": "2022-03-01", "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120, "timezone": "America/Los_Angeles"}}, + "envelopes": [ + { + "id": "env_offer_kim", "subject": "Offer Letter - Jordan Kim", "message": "Please review and sign your offer letter.", + "status": "completed", "createdAt": "2025-04-02T09:15:00Z", "sentAt": "2025-04-02T09:20:00Z", "completedAt": "2025-04-03T16:40:00Z", + "voidedAt": None, "declinedAt": None, "lastActivityAt": "2025-04-03T16:40:00Z", "expiresAt": None, + "senderId": "user_1", "folderId": None, "templateId": None, "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2, + "documents": [{"id": "doc_offer_1", "name": "Offer_Letter_Jordan_Kim.pdf", "pageCount": 3, "order": 1, "fileUrl": "https://picsum.photos/seed/offer/800/1100", "fileType": "pdf"}], + "recipients": [{"id": "rec_offer_1", "name": "Jordan Kim", "email": "jordan.kim@example.com", "role": "signer", "routingOrder": 1, "status": "signed", "signedAt": "2025-04-03T16:40:00Z", "viewedAt": "2025-04-02T12:00:00Z", "deliveredAt": "2025-04-02T09:21:00Z", "declinedAt": None, "declineReason": None}], + "fields": [], + "history": [ + {"id": "evt_offer_1", "timestamp": "2025-04-02T09:15:00Z", "action": "created", "actorName": "Morgan Davis", "actorEmail": "morgan.davis@company.com", "details": "Envelope created"}, + {"id": "evt_offer_2", "timestamp": "2025-04-03T16:40:00Z", "action": "completed", "actorName": "Jordan Kim", "actorEmail": "jordan.kim@example.com", "details": "All recipients signed"}, + ], + } + ], + "templates": [ + {"id": "tpl_handbook", "name": "Employee Handbook Acknowledgement", "description": "Current Employee Handbook for acknowledgement signature.", "createdAt": "2025-01-10T08:00:00Z", "lastUsedAt": "2025-01-10T08:00:00Z", "usageCount": 0, "ownerId": "user_1", "shared": True, "documents": [{"id": "tpl_doc_handbook", "name": "Employee_Handbook.pdf", "pageCount": 12, "order": 1, "fileUrl": "https://picsum.photos/seed/handbook/800/1100", "fileType": "pdf"}], "roles": [{"id": "role_signer", "name": "Employee", "order": 1}], "fields": []} + ], + "folders": [{"id": "folder_hr", "name": "HR Documents", "parentFolder": None, "createdAt": "2024-12-01T08:00:00Z"}], + "contacts": [ + {"id": "contact_alex", "name": "Alex Rivera", "email": "alex@company.com", "company": "Northbridge Technologies", "title": "Senior Software Engineer"}, + {"id": "contact_blair", "name": "Blair Thompson", "email": "blair@company.com", "company": "Northbridge Technologies", "title": "Software Engineer"}, + {"id": "contact_chen", "name": "Chen Wei", "email": "chen@company.com", "company": "Northbridge Technologies", "title": "Staff Engineer"}, + {"id": "contact_jordan", "name": "Jordan Kim", "email": "jordan.kim@example.com", "company": "Northbridge Technologies", "title": "Product Manager"}, + ], + "auditLog": [ + {"id": "audit_1", "timestamp": "2025-04-02T09:15:00Z", "action": "CREATE_ENVELOPE", "details": "Offer Letter - Jordan Kim", "envelopeId": "env_offer_kim"}, + {"id": "audit_2", "timestamp": "2025-04-03T16:40:00Z", "action": "COMPLETE_ENVELOPE", "details": "Offer Letter - Jordan Kim completed", "envelopeId": "env_offer_kim"}, + ], + } + + +def build_slack_state(): + return { + "currentUser": {"userId": "user_1", "fullName": "Morgan Davis", "displayName": "Morgan", "email": "morgan.davis@company.com", "avatar": "https://picsum.photos/200/200?random=1", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles", "title": "Director of People Operations"}, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Northbridge Technologies", "icon": ""}, + "users": [ + {"userId": "user_1", "fullName": "Morgan Davis", "displayName": "Morgan", "email": "morgan.davis@company.com", "avatar": "https://picsum.photos/200/200?random=1", "status": "online"}, + {"userId": "user_2", "fullName": "Alex Rivera", "displayName": "Alex", "email": "alex@company.com", "avatar": "https://picsum.photos/200/200?random=2", "status": "online"}, + {"userId": "user_3", "fullName": "Blair Thompson", "displayName": "Blair", "email": "blair@company.com", "avatar": "https://picsum.photos/200/200?random=3", "status": "away"}, + {"userId": "user_4", "fullName": "Chen Wei", "displayName": "Chen", "email": "chen@company.com", "avatar": "https://picsum.photos/200/200?random=4", "status": "online"}, + ], + "channels": [ + {"channelId": "general", "name": "general", "description": "Company-wide announcements", "topic": "Welcome", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_1", "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "engineering", "name": "engineering", "description": "Engineering team discussion", "topic": "Ship it", "isPrivate": False, "isStarred": True, "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_2", "createdAt": "2024-01-02T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "general": [ + {"messageId": "msg_g1", "senderId": "user_1", "content": "Reminder: all-hands is Thursday at 10am.", "timestamp": "2025-05-19T16:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "engineering": [ + {"messageId": "msg_e1", "senderId": "user_2", "content": "The CI pipeline is green again after the flaky test fix.", "timestamp": "2025-05-20T14:02:00Z", "threadId": None, "reactions": [{"emoji": "tada", "users": ["user_3", "user_4"]}], "attachments": [], "isEdited": False}, + {"messageId": "msg_e2", "senderId": "user_4", "content": "Can someone review my PR for the caching layer? #1284", "timestamp": "2025-05-20T15:18:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_e3", "senderId": "user_3", "content": "On it. Will get to it after standup.", "timestamp": "2025-05-20T15:25: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 INITIAL state into all three mocks (action: "set"). +# --------------------------------------------------------------------------- +payloads = { + 'google_docs': build_gdocs_state(), + 'docusign': build_docusign_state(), + 'slack': build_slack_state(), +} + +for name, state in payloads.items(): + url = MOCKS[name] + resp = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={SID}', timeout=15).json() + assert go.get('initial_state') is not None, f'{name} initial_state is None after injection' + print(f'Injected {name}: ok') + + +# --------------------------------------------------------------------------- +# Launch browser (GUI-ready) — primary mock is Google Docs. +# --------------------------------------------------------------------------- +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 "{MOCKS["google_docs"]}/?sid={SID}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {MOCKS["google_docs"]}/?sid={SID}') +launch_gui(f'google-chrome "{MOCKS["docusign"]}/?sid={SID}"', delay_sec=1.5) +print(f'GUI_READY: launched browser at {MOCKS["docusign"]}/?sid={SID}') +launch_gui(f'google-chrome "{MOCKS["slack"]}/?sid={SID}"', delay_sec=1.5) +print(f'GUI_READY: launched browser at {MOCKS["slack"]}/?sid={SID}') diff --git a/legacy/hr_handbook_002/reward.py b/legacy/hr_handbook_002/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..e5cc7e5a38e48d541f8206dcc753b1ea94033498 --- /dev/null +++ b/legacy/hr_handbook_002/reward.py @@ -0,0 +1,250 @@ +""" +Reward Script: HR Handbook Parental Leave rollout (Google Docs -> DocuSign -> Slack) +Task ID: hr_handbook_002 +Domain: mock_websites (multi-mock: google-docs, docusign, slack) + +Scoring (1.0 total), all DETERMINISTIC / programmatic — no LLM judge: + Component A — Google Docs (0.34) + A1 (0.14) New 'Parental Leave' heading present in handbook (absent in initial) + A2 (0.10) Parental Leave heading positioned immediately after 'Paid Time Off' + A3 (0.10) Parental Leave body mentions 12 weeks of paid leave; other sections preserved + Component B — DocuSign (0.33) + B1 (0.13) A new handbook-acknowledgement envelope exists (absent in initial) + B2 (0.10) That envelope status == 'sent' + B3 (0.10) Recipients cover all three engineers alex@/blair@/chen@company.com + Component C — Slack #engineering (0.33) + C1 (0.13) A new message exists in #engineering (absent in initial) + C2 (0.10) Message announces the new parental leave policy + C3 (0.10) Message states an acknowledgement request was sent + +Every component compares current_state against initial_state so it scores ONLY +task-introduced changes: each check fails on initial_env and passes on golden_env. +""" +import os +import re +import sys + +# The VM reaches the mocks only through the corporate proxy. The run-python +# context may not inherit it, so set it explicitly before importing requests use. +os.environ.setdefault('https_proxy', 'http://star-proxy.oa.com:3128') +os.environ.setdefault('http_proxy', 'http://star-proxy.oa.com:3128') +os.environ.setdefault('HTTPS_PROXY', 'http://star-proxy.oa.com:3128') +os.environ.setdefault('HTTP_PROXY', 'http://star-proxy.oa.com:3128') + +import requests + +MOCKS = { + 'google-docs': 'http://28.7.186.212:8162', + 'docusign': 'http://28.7.186.212:8150', + 'slack': 'http://28.7.186.212:8198', +} + +ENGINEER_EMAILS = {'alex@company.com', 'blair@company.com', 'chen@company.com'} + + +def fail(msg): + print(f'CRITICAL: {msg}') + print('REWARD: 0.0') + sys.exit(0) + + +# --- Read the per-environment deterministic 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 /go 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: + fail(f'Cannot fetch state from {url}/go?sid={sid}: {e}') + + +def headings_in_order(html): + """Return list of

/

heading texts in document order.""" + return [h.strip() for h in re.findall(r']*>(.*?)', html or '', re.IGNORECASE | re.DOTALL)] + + +def section_body(html, heading): + """Return text between the given

heading and the next heading.""" + # Find the heading occurrence, capture everything until the next ]*>\s*' + re.escape(heading) + r'\s*

(.*?)(?=/

标题文本并归一化为小写。检查 'parental leave' 是否在当前标题列表中且不在初始标题列表中(has_now and not had_before)。", + "pass_condition": "当前 HTML 标题列表包含 'parental leave',且初始 HTML 标题列表不包含 'parental leave'。" + }, + { + "name": "A2 — Parental Leave 紧跟 Paid Time Off", + "weight": 0.1, + "description": "检查 Parental Leave 章节在文档顺序中是否直接位于 Paid Time Off 之后。", + "check_logic": "在当前小写标题列表中分别查找 'paid time off' 与 'parental leave' 的索引,判断 pl_idx == pto_idx + 1。", + "pass_condition": "'parental leave' 的索引等于 'paid time off' 索引加 1。" + }, + { + "name": "A3 — 正文提及 12 周带薪假且保留原章节", + "weight": 0.1, + "description": "检查 Parental Leave 正文包含 12 周带薪假信息,且原始章节未被删除。", + "check_logic": "使用正则提取 Parental Leave 与下一个 `fail()` -> 打印 REWARD: 0.0 并退出\n - 从任一 mock 服务 `/go?sid={sid}` 获取状态失败 -> `fail()` -> 0.0\n - 各组件内部异常会被捕获,打印 ERROR,该组件得 0 分,但不影响其他组件(因为 try-except 在函数内部,返回 0.0)\n - 注意:组件内部检查失败只是不得分,不会提前退出。\n\n 所以 failure modes 包括:\n - 无法读取 sid 文件\n - 无法从 mock 服务拉取状态\n - 各子组件检查不通过(不得分)\n\n10. **scoring_logic_explanation**: 详细中文解释,按执行顺序:\n - 首先读取 `/tmp/task_web_sid` 获取环境标识 sid,失败则直接返回 0.0。\n - 使用 sid 分别向 google-docs、docusign、slack 三个 mock 服务的 `/go` 端点拉取 initial_state 和 current_state。\n - 任一拉取失败即返回 0.0。\n - 然后依次执行三个验证函数:\n - verify_docs (0.34): 解析 handbook HTML,按 A1/A2/A3 逐项检查标题新增、顺序、正文内容和章节完整性。\n - verify_docusign (0.33): 对比信封列表,识别新增的 handbook acknowledgement 信封,检查其存在性、状态、收件人。\n - verify_slack (0.33): 对比 #engineering 消息,识别新消息,检查其存在性及内容是否包含 policy 和 acknowledgement 关键词。\n - 各子组件独立评分,失败仅扣该子组件分数,异常被捕获后该组件得 0 分。\n - 最后将 A+B+C 得分相加,四舍五入到 4 位小数,并用 min(..., 1.0) 钳制在 1.0 以内,输出 REWARD。\n\n11. **confidence**: 1.0,因为源码完整清晰。\n\n现在检查 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 `` 标签\n- 第一个字符必须是 `{`,最后一个字符必须是 `}`\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n我需要确保 JSON 是合法的。注意在 JSON 字符串中,双引号需要转义,反斜杠等也需要处理。但中文描述中如果有引号,要用中文引号或者转义。\n\n让我再仔细看看代码中的一些细节:\n\n- `twelve_weeks = bool(re.search(r'12\\s*weeks?', body)) and ('pa' in body)` — 这里 `'pa' in body` 是为了检查 paid/parental。这个逻辑有点奇怪但确实是代码里的。\n- `original_sections` 列表在代码里明确列出。\n- `is_handbook_ack` 函数逻辑:`text = f\"{e.get('subject', '')} {e.get('message', '')}\".lower()`,`doc_names = ' '.join(d.get('name', '') for d in (e.get('documents') or [])).lower()`,`blob = text + ' ' + doc_names`,返回 `'handbook' in blob and ('acknowledg' in blob or 'sign' in blob or 'handbook' in doc_names)`。注意 `'handbook' in doc_names` 这个条件在 `blob` 里已经包含了,但代码确实如此。\n- `ack_envs = [e for e in new_envs if is_handbook_ack(e)]`\n- `env = ack_envs[0] if ack_envs else None`\n\n在描述 check_logic 时,要准确反映代码。\n\n关于 data_sources,代码中明确的是:\n- `/tmp/task_web_sid`\n- `http://28.7.186.212:8162` (google-docs)\n- `http://28.7.186.212:8150` (docusign)\n- `http://28.7.186.212:8198` (slack)\n\n根据示例,应该写成类似 `slack_mock`、`github_mock` 的形式。我会写成 `google-docs_mock`、`docusign_mock`、`slack_mock` 和 `/tmp/task_web_sid`。\n\n关于 domain,docstring 写的是 `mock_websites (multi-mock: google-docs, docusign, slack)`。按照要求格式如 `mock_websites / software_engineer / libreoffice_calc`,我应该填 `mock_websites`。\n\n关于 scoring_components 的 name,我可以保留 A1, A2 等标识。\n\n让我构建最终的 JSON。确保没有 trailing commas,所有字符串用双引号。\n\n一个潜在问题:JSON 中不能有多余的换行或注释?不,JSON 标准不允许注释,但换行是可以的。不过为了安全,我会输出紧凑或格式化的 JSON。格式化更易读,只要合法即可。\n\n再检查 failure_modes:\n- \"读取 sid 文件失败\" -> fail() -> sys.exit(0) 并打印 REWARD: 0.0\n- \"从 mock 服务拉取状态失败\" -> fail() -> 同上\n- \"组件内部异常\" -> 捕获后该组件返回 0.0\n- \"各子条件不满足\" -> 该子组件不得分\n\nscoring_logic_explanation 需要按执行顺序:\n1. 读取 sid\n2. 拉取三个 mock 状态\n3. verify_docs: 解析 HTML,比较 initial/current,检查标题、顺序、正文、保留章节\n4. verify_docusign: 比较信封,找新信封,筛选 handbook ack,检查状态、收件人\n5. verify_slack: 比较消息,找新消息,检查内容关键词\n6. 汇总:相加,round,min(1.0)\n\nconfidence: 1.0\n\n好,开始写 JSON。 {\"task_id\":\"hr_handbook_002\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Google Docs 员工手册中新增 Parental Leave 章节并通过 DocuSign 向三位工程师发送确认信封,同时在 Slack #engineering 频道发布政策公告的完整任务流程。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google-docs_mock\",\"docusign_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"A1 — Parental Leave 标题新增\",\"weight\":0.14,\"description\":\"检查 handbook 中是否新增加了 Parental Leave 标题,且初始状态不存在该标题。\",\"check_logic\":\"从 google-docs 的 initial_state 与 current_state 中提取 doc-handbook 的 HTML,使用正则提取

/

标题文本并归一化为小写。检查 'parental leave' 是否在当前标题列表中且不在初始标题列表中(has_now and not had_before)。\",\"pass_condition\":\"当前 HTML 标题列表包含 'parental leave',且初始 HTML 标题列表不包含 'parental leave'。\"},{\"name\":\"A2 — Parental Leave 紧跟 Paid Time Off\",\"weight\":0.10,\"description\":\"检查 Parental Leave 章节在文档顺序中是否直接位于 Paid Time Off 之后。\",\"check_logic\":\"在当前小写标题列表中分别查找 'paid time off' 与 'parental leave' 的索引,判断 pl_idx == pto_idx + 1。\",\"pass_condition\":\"'parental leave' 的索引等于 'paid time off' 索引加 1。\"},{\"name\":\"A3 — 正文提及 12 周带薪假且保留原章节\",\"weight\":0.10,\"description\":\"检查 Parental Leave 正文包含 12 周带薪假信息,且原始章节未被删除。\",\"check_logic\":\"使用正则提取 Parental Leave 与下一个 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/hr_onboarding_001/initial_setup.py b/legacy/hr_onboarding_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..49488cc4bbe0b3698ebfc6d38997e983ef82994e --- /dev/null +++ b/legacy/hr_onboarding_001/initial_setup.py @@ -0,0 +1,180 @@ +""" +Initial Setup: HR onboarding — create Jane Doe's onboarding checklist (Workday) and +schedule a New Hire Orientation calendar event (Google Calendar). +Task ID: hr_onboarding_001 +Domain: mock_websites (multi-mock: workday_mock + google_calendar_mock) + +Pre-task state: + - Workday: Jane Doe worker record exists (Software Engineer, hire 2026-07-01, + jane.doe@company.com). An "Engineering New Hire" onboarding template exists. + NO active onboarding checklist instance for Jane yet (onboardingChecklists = []). + - Google Calendar: realistic events on other days; 2026-07-01 is empty. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +WORKDAY_URL = 'http://28.7.186.212:8212' +CALENDAR_URL = 'http://28.7.186.212:8161' + +# --- Session id (shared across both mocks) --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +def avatar(name, bg='0875E1'): + return f'https://ui-avatars.com/api/?name={name.replace(" ", "+")}&background={bg}&color=fff&size=128' + + +# ---------------------------------------------------------------------------- +# Workday initial state +# ---------------------------------------------------------------------------- +def build_workday_state(): + hr_admin = { + "id": "emp_hr", "name": "Patricia Hayes", "email": "patricia.hayes@acmecorp.com", + "phone": "+1 (415) 555-0190", "role": "Manager", "department": "Human Resources", + "departmentId": "dept005", "avatar": avatar("Patricia Hayes", "7C3AED"), + "managerId": None, "title": "HR Administrator", "location": "San Francisco, CA", + "joinDate": "2019-02-11", "employeeType": "Full-Time", + "skills": ["Workday", "Onboarding", "Compliance"], + "birthday": "1984-09-30", "workAnniversary": "2019-02-11" + } + + employees = [ + hr_admin, + {"id": "emp001", "name": "Alex Morgan", "email": "alex.morgan@acmecorp.com", "phone": "+1 (415) 555-0142", "role": "Manager", "department": "Engineering", "departmentId": "dept001", "avatar": avatar("Alex Morgan"), "managerId": "emp002", "title": "Senior Software Engineer", "location": "San Francisco, CA", "joinDate": "2020-03-15", "employeeType": "Full-Time", "birthday": "1990-04-12", "workAnniversary": "2020-03-15"}, + {"id": "emp002", "name": "Sarah Connor", "email": "sarah.connor@acmecorp.com", "phone": "+1 (415) 555-0101", "role": "Director", "department": "Engineering", "departmentId": "dept001", "avatar": avatar("Sarah Connor", "7C3AED"), "managerId": None, "title": "Director of Engineering", "location": "San Francisco, CA", "joinDate": "2018-06-01", "employeeType": "Full-Time", "birthday": "1985-11-03", "workAnniversary": "2018-06-01"}, + {"id": "emp003", "name": "John Smith", "email": "john.smith@acmecorp.com", "phone": "+1 (415) 555-0103", "role": "Employee", "department": "Engineering", "departmentId": "dept001", "avatar": avatar("John Smith"), "managerId": "emp001", "title": "Software Engineer", "location": "Austin, TX", "joinDate": "2021-09-20", "employeeType": "Full-Time", "birthday": "1992-07-19", "workAnniversary": "2021-09-20"}, + {"id": "emp004", "name": "Emily Chen", "email": "emily.chen@acmecorp.com", "phone": "+1 (415) 555-0104", "role": "Manager", "department": "Design", "departmentId": "dept002", "avatar": avatar("Emily Chen"), "managerId": "emp002", "title": "Design Lead", "location": "San Francisco, CA", "joinDate": "2020-11-02", "employeeType": "Full-Time", "birthday": "1991-01-25", "workAnniversary": "2020-11-02"}, + {"id": "emp005", "name": "Marcus Johnson", "email": "marcus.johnson@acmecorp.com", "phone": "+1 (415) 555-0105", "role": "Employee", "department": "Engineering", "departmentId": "dept001", "avatar": avatar("Marcus Johnson"), "managerId": "emp001", "title": "Backend Engineer", "location": "Remote", "joinDate": "2022-01-10", "employeeType": "Full-Time", "birthday": "1988-03-08", "workAnniversary": "2022-01-10"}, + {"id": "emp006", "name": "Lisa Park", "email": "lisa.park@acmecorp.com", "phone": "+1 (415) 555-0106", "role": "Employee", "department": "Design", "departmentId": "dept002", "avatar": avatar("Lisa Park"), "managerId": "emp004", "title": "Product Designer", "location": "Seattle, WA", "joinDate": "2021-04-15", "employeeType": "Full-Time", "birthday": "1993-12-02", "workAnniversary": "2021-04-15"}, + {"id": "emp007", "name": "David Kim", "email": "david.kim@acmecorp.com", "phone": "+1 (415) 555-0107", "role": "Manager", "department": "Marketing", "departmentId": "dept003", "avatar": avatar("David Kim"), "managerId": "emp002", "title": "Marketing Manager", "location": "New York, NY", "joinDate": "2019-08-19", "employeeType": "Full-Time", "birthday": "1986-06-14", "workAnniversary": "2019-08-19"}, + {"id": "emp008", "name": "Rachel Green", "email": "rachel.green@acmecorp.com", "phone": "+1 (415) 555-0108", "role": "Employee", "department": "Marketing", "departmentId": "dept003", "avatar": avatar("Rachel Green"), "managerId": "emp007", "title": "Marketing Specialist", "location": "New York, NY", "joinDate": "2022-05-23", "employeeType": "Full-Time", "birthday": "1994-02-28", "workAnniversary": "2022-05-23"}, + {"id": "emp009", "name": "James Wilson", "email": "james.wilson@acmecorp.com", "phone": "+1 (415) 555-0109", "role": "Employee", "department": "Finance", "departmentId": "dept004", "avatar": avatar("James Wilson"), "managerId": "emp002", "title": "Financial Analyst", "location": "Chicago, IL", "joinDate": "2020-07-06", "employeeType": "Full-Time", "birthday": "1989-10-11", "workAnniversary": "2020-07-06"}, + {"id": "emp010", "name": "Nina Patel", "email": "nina.patel@acmecorp.com", "phone": "+1 (415) 555-0110", "role": "Employee", "department": "Human Resources", "departmentId": "dept005", "avatar": avatar("Nina Patel"), "managerId": "emp_hr", "title": "HR Generalist", "location": "San Francisco, CA", "joinDate": "2021-10-01", "employeeType": "Full-Time", "birthday": "1990-05-17", "workAnniversary": "2021-10-01"}, + # --- The new hire --- + {"id": "emp011", "name": "Jane Doe", "email": "jane.doe@company.com", "phone": "+1 (415) 555-0211", "role": "Employee", "department": "Engineering", "departmentId": "dept001", "avatar": avatar("Jane Doe"), "managerId": "emp001", "title": "Software Engineer", "location": "San Francisco, CA", "joinDate": "2026-07-01", "employeeType": "Full-Time", "birthday": "1995-08-21", "workAnniversary": "2026-07-01"}, + ] + + state = { + "currentUser": hr_admin, + "employees": employees, + "departments": [ + {"id": "dept001", "name": "Engineering", "headcount": 6, "managerId": "emp002"}, + {"id": "dept002", "name": "Design", "headcount": 2, "managerId": "emp004"}, + {"id": "dept003", "name": "Marketing", "headcount": 2, "managerId": "emp007"}, + {"id": "dept004", "name": "Finance", "headcount": 1, "managerId": "emp002"}, + {"id": "dept005", "name": "Human Resources", "headcount": 2, "managerId": "emp_hr"}, + ], + "timeEntries": [ + {"entryId": "te1", "employeeId": "emp_hr", "date": "2026-06-22", "hours": 8, "project": "General", "status": "Approved", "notes": "Onboarding prep"}, + {"entryId": "te2", "employeeId": "emp_hr", "date": "2026-06-23", "hours": 8, "project": "General", "status": "Approved", "notes": ""}, + ], + "timeOffRequests": [ + {"requestId": "tr1", "employeeId": "emp003", "type": "Vacation", "startDate": "2026-07-13", "endDate": "2026-07-17", "status": "Pending", "reason": "Summer trip", "totalHours": 40, "reviewedBy": None, "reviewedDate": None}, + ], + "timeOffBalance": {"vacation": 96, "sick": 40, "personal": 16}, + "payroll": [ + {"paystubId": "ps1", "employeeId": "emp_hr", "period": "Jun 1 - Jun 15, 2026", "payDate": "2026-06-15", "date": "2026-06-15", "grossPay": 5192.31, "federalTax": 830.77, "stateTax": 415.38, "socialSecurity": 321.92, "medicare": 75.29, "healthInsurance": 110.00, "retirement401k": 259.62, "otherDeductions": 12.00, "totalDeductions": 2024.98, "netPay": 3167.33, "deductions": 2024.98}, + ], + "benefits": { + "employeeId": "emp_hr", "enrollmentStatus": "Complete", + "plans": [ + {"id": "b1", "type": "Medical", "name": "Medical - PPO Plus", "provider": "BlueCross BlueShield", "coverageLevel": "Employee Only", "employeeCost": 180.00, "employerCost": 620.00, "cost": 180.00, "status": "Active", "effectiveDate": "2026-01-01", "details": {"deductible": 1500, "outOfPocketMax": 5000, "copay": 25, "coinsurance": 20}}, + ], + "dependents": [] + }, + "reviews": [], + "goals": [ + {"goalId": "g1", "employeeId": "emp_hr", "title": "Streamline onboarding process", "description": "Reduce time-to-productivity for new hires.", "category": "Business", "status": "On Track", "progress": 60, "dueDate": "2026-12-31", "createdDate": "2026-01-15", "milestones": ["Standardize templates"]}, + ], + "tasks": [ + {"taskId": "t1", "employeeId": "emp_hr", "type": "Approval", "subType": "Time Off Request", "description": "Approve Time Off for John Smith", "status": "Pending", "dueDate": "2026-07-01", "createdDate": "2026-06-24", "relatedId": "tr1", "initiator": "John Smith", "businessProcess": "Request Time Off", "priority": "Normal", "comments": []}, + {"taskId": "t2", "employeeId": "emp_hr", "type": "To-Do", "subType": "Onboarding", "description": "Prepare workstation for incoming engineering hire", "status": "Pending", "dueDate": "2026-06-30", "createdDate": "2026-06-20", "relatedId": None, "initiator": "System", "businessProcess": "New Hire Onboarding", "priority": "High", "comments": []}, + {"taskId": "t3", "employeeId": "emp_hr", "type": "To-Do", "subType": "Onboarding", "description": "Complete New Hire Onboarding checklist for Jane Doe (Software Engineer)", "status": "Pending", "dueDate": "2026-07-01", "createdDate": "2026-06-24", "relatedId": "emp011", "initiator": "System", "businessProcess": "New Hire Onboarding", "priority": "High", "comments": []}, + ], + "announcements": [ + {"id": "a1", "title": "Q3 All-Hands Meeting", "date": "2026-06-25", "content": "Join us for the quarterly all-hands on July 10.", "category": "Company", "priority": "Normal"}, + {"id": "a2", "title": "New Onboarding Templates Live", "date": "2026-06-18", "content": "Standardized onboarding checklist templates are now available in Workday.", "category": "HR", "priority": "Normal"}, + ], + "notifications": [ + {"id": "n1", "type": "task", "title": "Onboarding Task", "message": "Prepare workstation for incoming engineering hire.", "timestamp": "2026-06-24T09:00:00.000Z", "read": False, "link": "/inbox"}, + {"id": "n2", "type": "system", "title": "Welcome", "message": "Jane Doe's worker record has been created.", "timestamp": "2026-06-24T08:30:00.000Z", "read": False, "link": "/directory"}, + ], + "clockStatus": {"isClockedIn": False, "startTime": None}, + + # --- Custom onboarding structures --- + # Template exists; NO active checklist instance for Jane yet. + "onboardingTemplates": [ + { + "id": "tmpl_eng_new_hire", + "name": "Engineering New Hire", + "department": "Engineering", + "items": ["Sign Offer Letter", "IT Setup", "Benefits Enrollment", "Policy Acknowledgement"], + } + ], + "onboardingChecklists": [], + } + return state + + +# ---------------------------------------------------------------------------- +# Google Calendar initial state (2026-07-01 deliberately empty) +# ---------------------------------------------------------------------------- +def build_calendar_state(): + return { + "user": {"id": "u1", "username": "Patricia Hayes", "email": "patricia.hayes@acmecorp.com", "avatar": "https://picsum.photos/100/100?random=user1"}, + "calendars": [ + {"id": "c1", "name": "Personal", "color": "#039BE5", "visible": True, "userId": "u1", "isDefault": True}, + {"id": "c2", "name": "Work", "color": "#33B679", "visible": True, "userId": "u1", "isDefault": False}, + {"id": "c3", "name": "Family", "color": "#8E24AA", "visible": True, "userId": "u1", "isDefault": False}, + ], + "events": [ + {"id": "evt_001", "calendarId": "c2", "title": "Team Standup", "start": "2026-06-30T09:00:00.000Z", "end": "2026-06-30T09:30:00.000Z", "allDay": False, "location": "Zoom", "description": "Daily sync", "guests": ["alex.morgan@acmecorp.com"], "color": "#33B679", "recurring": "daily", "reminders": [{"type": "popup", "minutes": 5}], "meetLink": "", "status": "confirmed"}, + {"id": "evt_002", "calendarId": "c2", "title": "HR Staff Meeting", "start": "2026-06-29T14:00:00.000Z", "end": "2026-06-29T15:00:00.000Z", "allDay": False, "location": "Conference Room B", "description": "Weekly HR sync", "guests": ["nina.patel@acmecorp.com"], "color": "#33B679", "recurring": "weekly", "reminders": [{"type": "popup", "minutes": 10}], "meetLink": "", "status": "confirmed"}, + {"id": "evt_003", "calendarId": "c1", "title": "Dentist Appointment", "start": "2026-07-02T16:00:00.000Z", "end": "2026-07-02T17:00:00.000Z", "allDay": False, "location": "Downtown Dental", "description": "", "guests": [], "color": "#039BE5", "recurring": "none", "reminders": [{"type": "popup", "minutes": 30}], "meetLink": "", "status": "confirmed"}, + ], + "view": "week", + "currentDate": "2026-07-01T00:00:00.000Z", + "sidebarOpen": True, + "settings": { + "weekStart": 0, "defaultDuration": 60, "defaultView": "week", + "defaultReminder": {"type": "popup", "minutes": 10}, "timeFormat": "12h", + "showWeekNumbers": False, "showDeclinedEvents": False + }, + } + + +def inject(url, state): + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'Inject failed for {url}: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'initial_state is None for {url}' + return go + + +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(): + inject(WORKDAY_URL, build_workday_state()) + print(f'Workday state injected: sid={sid}') + inject(CALENDAR_URL, build_calendar_state()) + print(f'Calendar state injected: sid={sid}') + + # GUI-ready: open both apps in Chrome (Workday is the primary starting point). + launch_gui(f'google-chrome "{WORKDAY_URL}/?sid={sid}"', delay_sec=2.0) + launch_gui(f'google-chrome "{CALENDAR_URL}/?sid={sid}"', delay_sec=2.0) + print(f'GUI_READY: launched Workday and Google Calendar with sid={sid}') + + +main() diff --git a/legacy/hr_onboarding_001/reward.py b/legacy/hr_onboarding_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..371b82d4198c2be2f05c5d7e2537e65a57a734da --- /dev/null +++ b/legacy/hr_onboarding_001/reward.py @@ -0,0 +1,161 @@ +""" +Reward Script: HR onboarding for Jane Doe — Workday onboarding task completion + + Google Calendar 'New Hire Orientation' event. +Task ID: hr_onboarding_001 +Domain: mock_websites (workday_mock + google_calendar_mock) + +NOTE: the Workday mock UI supports completing/updating existing tasks (it has NO +"instantiate onboarding checklist from template" feature). So the Workday half of +this task is scored on completing Jane Doe's pre-seeded onboarding to-do task, +which is what the app actually supports. + +All checks are DELTA vs initial_state, so reward(initial_env) == 0.0. + +Scoring (all programmatic; total 1.0): + Component A (0.50) — Workday: Jane Doe's 'New Hire Onboarding' to-do task (t3) + transitioned from Pending to Completed. + Component C (0.25) — Calendar: a 'New Hire Orientation' event on 2026-07-01, + 10:00–11:00 (1 hour) exists. + Component D (0.25) — Calendar: that orientation event invites jane.doe@company.com. +""" + +import re +import sys + +import requests + +WORKDAY_URL = 'http://28.7.186.212:8212' +GCAL_URL = 'http://28.7.186.212:8161' + +JANE_TASK_ID = 't3' +EXPECTED_GUEST = 'jane.doe@company.com' +EVENT_TITLE_KEY = 'new hire orientation' +EXPECTED_DATE = '2026-07-01' + + +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 parse_hhmm(iso_str): + if not isinstance(iso_str, str): + return (None, None, None) + m = re.match(r'(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})', iso_str) + if not m: + return (None, None, None) + return (m.group(1), int(m.group(2)), int(m.group(3))) + + +def verify_workday(sid): + """Component A (0.50): Jane's onboarding task moved from Pending to Completed.""" + init, cur = fetch(WORKDAY_URL, sid) + if cur is None: + print('FAIL: Workday unreachable') + return 0.0 + try: + def task_status(state): + for t in (state.get('tasks') or []): + if t.get('taskId') == JANE_TASK_ID: + return str(t.get('status', '')).strip().lower() + return None + + init_status = task_status(init) + cur_status = task_status(cur) + # Accept 'completed'/'complete'/'done' as terminal states. + done = cur_status in ('completed', 'complete', 'done') + was_pending = init_status not in ('completed', 'complete', 'done') + if done and was_pending: + print(f"PASS: Component A — Jane's onboarding task completed " + f"(init={init_status!r} cur={cur_status!r}) (0.50)") + return 0.50 + print(f"FAIL: Component A — task status. init={init_status!r} cur={cur_status!r} " + f"(expected Pending -> Completed)") + return 0.0 + except Exception as e: + print(f'ERROR: Component A — {e}') + return 0.0 + + +def verify_calendar(sid): + """Components C (0.25) + D (0.25).""" + init, cur = fetch(GCAL_URL, sid) + if cur is None: + print('FAIL: Calendar unreachable') + return 0.0 + score = 0.0 + try: + init_ids = {e.get('id') for e in (init.get('events') or [])} + events = cur.get('events') or [] + orientation = None + for ev in events: + if EVENT_TITLE_KEY in str(ev.get('title', '')).strip().lower() \ + and ev.get('id') not in init_ids: + orientation = ev + break + # Fallback: match by title even if id-set check is inconclusive. + if orientation is None: + for ev in events: + if EVENT_TITLE_KEY in str(ev.get('title', '')).strip().lower(): + orientation = ev + break + + # Component C: on 2026-07-01, 10:00–11:00 (0.25) + if orientation is None: + print("FAIL: Component C — no 'New Hire Orientation' event found") + return score + s_date, s_h, s_m = parse_hhmm(orientation.get('start')) + e_date, e_h, e_m = parse_hhmm(orientation.get('end')) + ok_start = (s_date == EXPECTED_DATE and s_h == 10 and s_m == 0) + ok_end = (e_date == EXPECTED_DATE and e_h == 11 and e_m == 0) + if ok_start and ok_end: + print(f"PASS: Component C — orientation on {EXPECTED_DATE} 10:00–11:00 " + f"(start={orientation.get('start')!r} end={orientation.get('end')!r}) (0.25)") + score += 0.25 + else: + print(f"FAIL: Component C — timing (start={orientation.get('start')!r} " + f"end={orientation.get('end')!r}; expected {EXPECTED_DATE} 10:00->11:00)") + + # Component D: invites jane.doe@company.com (0.25) + guests = [str(g).strip().lower() for g in (orientation.get('guests') or [])] + if EXPECTED_GUEST in guests: + print(f"PASS: Component D — guest {EXPECTED_GUEST} invited (0.25)") + score += 0.25 + else: + print(f"FAIL: Component D — {EXPECTED_GUEST} not in guests={orientation.get('guests')}") + return score + except Exception as e: + print(f'ERROR: Calendar component — {e}') + return score + + +def main(): + sid = read_sid() + if not sid: + print('REWARD: 0.0') + return + total = 0.0 + total += verify_workday(sid) + total += verify_calendar(sid) + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + + +main() diff --git a/legacy/hr_onboarding_001/reward_label.json b/legacy/hr_onboarding_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..fdcca6379994ce0464e7453e5c45382f87187c5c --- /dev/null +++ b/legacy/hr_onboarding_001/reward_label.json @@ -0,0 +1,56 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/hr_onboarding_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:26:42", + "label": { + "task_id": "hr_onboarding_001", + "domain": "mock_websites", + "summary": "验证 Jane Doe 在 Workday 中的入职待办任务是否完成,并在 Google Calendar 中创建指定时间且邀请 Jane 的'New Hire Orientation'事件", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "workday_mock", + "google_calendar_mock" + ], + "scoring_components": [ + { + "name": "Component A", + "weight": 0.5, + "description": "Workday 中 Jane Doe 的入职待办任务从 Pending 变为 Completed", + "check_logic": "通过 fetch 获取 initial_state 和 current_state,遍历 state['tasks'] 查找 taskId 为 't3' 的任务,检查初始状态不在 ('completed', 'complete', 'done') 中且当前状态在该集合中", + "pass_condition": "初始状态不是已完成状态,且当前状态为 'completed'、'complete' 或 'done'" + }, + { + "name": "Component C", + "weight": 0.25, + "description": "Google Calendar 中存在日期为 2026-07-01、时段 10:00–11:00 的'New Hire Orientation'事件", + "check_logic": "从 current_state['events'] 中筛选标题包含 'new hire orientation' 且 id 不在 initial_state 事件 id 集合中的事件(有 fallback 仅按标题匹配),使用 parse_hhmm 解析 start 和 end 字段,检查日期是否为 2026-07-01、start 是否为 10:00、end 是否为 11:00", + "pass_condition": "事件 start 为 2026-07-01T10:00 且 end 为 2026-07-01T11:00" + }, + { + "name": "Component D", + "weight": 0.25, + "description": "该 orientation 事件邀请了 jane.doe@company.com", + "check_logic": "检查 orientation 事件的 guests 列表中是否存在 'jane.doe@company.com'(将 guests 元素转为小写字符串后比较)", + "pass_condition": "guests 列表中包含 'jane.doe@company.com'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空时提前退出,返回 0.0", + "Workday 服务不可达(fetch 返回 None)导致 Component A 得 0.0", + "Calendar 服务不可达(fetch 返回 None)导致 Calendar 部分得 0.0", + "Workday 中 taskId='t3' 不存在或状态未从 Pending 变为 Completed,Component A 得 0.0", + "Calendar 中找不到标题包含 'new hire orientation' 的事件时直接返回 0.0,跳过 Component D 检查", + "事件 start/end 时间不符合 2026-07-01 10:00–11:00 导致 Component C 不得分", + "事件 guests 不包含 jane.doe@company.com 导致 Component D 不得分", + "解析状态或事件时发生异常被捕获,返回 0.0 或当前已得分数" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接输出 REWARD: 0.0 并退出。随后分别验证 Workday 和 Calendar 两个部分:在 verify_workday 中,向 workday_mock 请求 initial_state 和 current_state,查找 tasks 列表里 taskId 为 't3' 的任务,若其初始状态不是已完成且当前状态变为 'completed'/'complete'/'done',则获得 0.50 分;在 verify_calendar 中,向 google_calendar_mock 请求状态,从 current_state['events'] 中找出标题包含 'new hire orientation' 且不在初始事件中的新事件(支持仅按标题匹配的 fallback),若找不到则直接返回 0.0。找到事件后,先解析 start 和 end 时间,若日期为 2026-07-01 且时段为 10:00–11:00 则获得 0.25 分;再检查 guests 列表是否包含 'jane.doe@company.com',包含则再获得 0.25 分。最终总分为三部分之和,通过 min(total, 1.0) 钳制上限为 1.0,并四舍五入保留 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 中提取到 `hr_onboarding_001`\n2. **Domain**: 从 docstring 中提取到 `mock_websites (workday_mock + google_calendar_mock)`,按照要求应该是 `mock_websites`\n3. **Summary**: 一句话概括:验证 Jane Doe 的 Workday 入职任务是否完成,以及 Google Calendar 是否创建了指定时间并邀请 Jane 的\"New Hire Orientation\"事件。\n4. **is_placeholder**: false,因为脚本有实际的检查逻辑。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `WORKDAY_URL = 'http://28.7.186.212:8212'` (workday_mock)\n - `GCAL_URL = 'http://28.7.186.212:8161'` (google_calendar_mock)\n\n6. **scoring_components**:\n - Component A (0.50): Workday 检查 Jane Doe 的 taskId='t3' 从 Pending 变为 Completed/Complete/Done\n - Component C (0.25): Calendar 检查是否存在标题包含 'new hire orientation' 的新事件(不在 initial_state 中,或有 fallback),日期为 2026-07-01,10:00-11:00\n - Component D (0.25): Calendar 检查该事件的 guests 包含 'jane.doe@company.com'\n\n 注意代码中 Component C 和 D 在同一个函数 `verify_calendar` 中,但分数是分开的。我需要把它们分成两个组件。\n\n Component A:\n - name: \"Component A\"\n - weight: 0.50\n - description: Workday 中 Jane Doe 的入职待办任务从 Pending 变为 Completed\n - check_logic: 通过 fetch 获取 initial_state 和 current_state,查找 tasks 列表中 taskId 为 't3' 的 status 字段,比较初始状态不是 completed/complete/done 且当前状态是 completed/complete/done\n - pass_condition: 初始状态不是已完成状态,且当前状态为 'completed'/'complete'/'done' 之一\n\n Component C:\n - name: \"Component C\"\n - weight: 0.25\n - description: Google Calendar 中存在指定日期和时间的\"New Hire Orientation\"事件\n - check_logic: 获取 initial_state 和 current_state,从 current_state.events 中筛选标题包含 'new hire orientation' 且不在 initial_ids 中的事件(有 fallback 机制),然后解析 start 和 end 时间,检查是否为 2026-07-01T10:00 和 2026-07-01T11:00\n - pass_condition: 事件 start 为 2026-07-01 10:00,end 为 2026-07-01 11:00\n\n Component D:\n - name: \"Component D\"\n - weight: 0.25\n - description: 该 orientation 事件邀请了 jane.doe@company.com\n - check_logic: 检查 orientation 事件的 guests 列表中是否包含 'jane.doe@company.com'(不区分大小写,转为小写比较)\n - pass_condition: guests 列表中包含 'jane.doe@company.com'\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后用 `min(total, 1.0)` 钳制到上限 1.0,并四舍五入到 4 位小数。\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空,提前退出,输出 REWARD: 0.0\n - Workday 服务不可达(fetch 返回 None),Component A 得 0.0\n - Calendar 服务不可达(fetch 返回 None),Component C+D 得 0.0\n - Workday 中找不到 taskId='t3' 或状态未从 Pending 变为 Completed,Component A 得 0.0\n - Calendar 中找不到标题包含 'new hire orientation' 的事件,Component C 失败,返回当前 score(此时 Component D 也不会执行,因为代码中 return score)\n - 事件时间不符合 2026-07-01 10:00-11:00,Component C 不得分\n - 事件 guests 不包含 jane.doe@company.com,Component D 不得分\n - 任何异常被捕获后返回 0.0 或当前 score\n\n 等等,我需要仔细看代码:在 Component C 失败时(orientation is None),代码是 `return score`,此时 score 是 0.0,所以 Component D 不会执行。这是一个失败路径。\n\n10. **scoring_logic_explanation**: \n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。\n - 然后分别调用 verify_workday 和 verify_calendar。\n - verify_workday: 向 Workday mock 服务获取 initial_state 和 current_state,查找 tasks 中 taskId 为 't3' 的任务,检查其初始状态不是已完成(completed/complete/done)且当前状态是已完成,通过则得 0.50,否则 0.0。\n - verify_calendar: 向 Google Calendar mock 服务获取状态,从 current_state.events 中查找标题包含 'new hire orientation' 且不在 initial_state 中的新事件(有 fallback 仅按标题匹配)。找到后:\n - 检查 start/end 是否为 2026-07-01 10:00 和 11:00,符合则得 0.25;\n - 检查 guests 列表是否包含 'jane.doe@company.com',符合则得 0.25。\n - 如果找不到事件,直接返回 0.0,跳过 D 检查。\n - 最终分数为各组件得分之和,用 min(total, 1.0) 钳制上限,四舍五入到 4 位小数。\n\n11. **confidence**: 1.0,因为代码逻辑清晰,docstring 完整。\n\n让我再检查一下 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n我需要确保所有 value 都是中文,但代码中的字段名、标识符保留原样。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"hr_onboarding_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证 Jane Doe 在 Workday 中的入职待办任务是否完成,并在 Google Calendar 中创建指定时间且邀请 Jane 的'New Hire Orientation'事件\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"http://28.7.186.212:8212 (workday_mock)\",\n \"http://28.7.186.212:8161 (google_calendar_mock)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component A\",\n \"weight\": 0.5,\n \"description\": \"Workday 中 Jane Doe 的入职待办任务从 Pending 变为 Completed\",\n \"check_logic\": \"通过 fetch 获取 initial_state 和 current_state,遍历 state['tasks'] 查找 taskId 为 't3' 的任务,检查初始状态不在 ('completed', 'complete', 'done') 中且当前状态在该集合中\",\n \"pass_condition\": \"初始状态不是已完成状态,且当前状态为 'completed'、'complete' 或 'done'\"\n },\n {\n \"name\": \"Component C\",\n \"weight\": 0.25,\n \"description\": \"Google Calendar 中存在日期为 2026-07-01、时段 10:00–11:00 的'New Hire Orientation'事件\",\n \"check_logic\": \"从 current_state['events'] 中筛选标题包含 'new hire orientation' 且 id 不在 initial_state 事件 id 集合中的事件(有 fallback 仅按标题匹配),使用 parse_hhmm 解析 start 和 end 字段,检查日期是否为 2026-07-01、start 是否为 10:00、end 是否为 11:00\",\n \"pass_condition\": \"事件 start 为 2026-07-01T10:00 且 end 为 2026-07-01T11:00\"\n },\n {\n \"name\": \"Component D\",\n \"weight\": 0.25,\n \"description\": \"该 orientation 事件邀请了 jane.doe@company.com\",\n \"check_logic\": \"检查 orientation 事件的 guests 列表中是否存在 'jane.doe@company.com'(将 guests 元素转为小写字符串后比较)\",\n \"pass_condition\": \"guests 列表中包含 'jane.doe@company.com'\"\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 失败或为空时提前退出,返回 0.0\",\n \"Workday 服务不可达(fetch 返回 None)导致 Component A 得 0.0\",\n \"Calendar 服务不可达(fetch 返回 None)导致 Calendar 部分得 0.0\",\n \"Workday 中 taskId='t3' 不存在或状态未从 Pending 变为 Completed,Component A 得 0.0\",\n \"Calendar 中找不到标题包含 'new hire orientation' 的事件时直接返回 0.0,跳过 Component D 检查\",\n \"事件 start/end 时间不符合 2026-07-01 10:00–11:00 导致 Component C 不得分\",\n \"事件 guests 不包含 jane.doe@company.com 导致 Component D 不得分\",\n \"解析状态或事件时发生异常被捕获,返回 0.0 或当前已得分数\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接输出 REWARD: 0.0 并退出。随后分别验证 Workday 和 Calendar 两个部分:在 verify_workday 中,向 workday_mock 请求 initial_state 和 current_state,查找 tasks 列表里 taskId 为 't3' 的任务,若其初始状态不是已完成且当前状态变为 'completed'/'complete'/'done',则获得 0.50 分;在 verify_calendar 中,向 google_calendar_mock 请求状态,从 current_state['events'] 中找出标题包含 'new hire orientation' 且不在初始事件中的新事件(支持仅按标题匹配的 fallback),若找不到则直接返回 0.0。找到事件后,先解析 start 和 end 时间,若日期为 2026-07-01 且时段为 10:00–11:00 则获得 0.25 分;再检查 guests 列表是否包含 'jane.doe@company.com',包含则再获得 0.25 分。最终总分为三部分之和,通过 min(total, 1.0) 钳制上限为 1.0,并四舍五入保留 4 位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n等等,我注意到 data_sources 里写的是 URL,但用户示例里写的是 `slack_mock`、`github_mock` 等。不过代码里确实是具体的 IP 地址。我应该保留原样还是按 mock 服务名?docstring 里写的是 workday_mock + google_calendar_mock。代码里变量名也是 WORKDAY_URL 和 GCAL_URL。我觉得写 mock 服务名更合适,或者都写上。让我看看用户示例:`如 slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid 等`。我写 `workday_mock`、`google_calendar_mock` 以及 `/tmp/task_web_sid` 应该更符合要求。但代码中实际请求的是具体 URL。为了准确,我可以写 `workday_mock (http://28.7.186.212:8212)` 这样?但用户要求的是数据源/mock 服务/文件。我觉得写 `workday_mock`、`google_calendar_mock`、`/tmp/task_web_sid` 即可。\n\n再检查一下 weight:Component A 是 0.50,Component C 是 0.25,Component D 是 0.25。代码中确实是这些值。\n\n再检查 failure_modes 中关于 Component C 找不到事件的情况:代码中 `if orientation is None: print(\"FAIL: Component C...\"); return score`。此时 score 是 0.0,所以确实会跳过 D。\n\n还有一个细节:在 verify_calendar 中,如果 orientation 找到了,但时间不对,会打印 FAIL Component C,然后继续检查 Component D。这是正确的,因为代码没有 return,而是继续执行。\n\n好的,我觉得分析已经完整准确了。现在输出 JSON。 {\"task_id\":\"hr_onboarding_001\",\"domain\":\"mock_websites\",\"summary\":\"验证 Jane Doe 在 Workday 中的入职待办任务是否完成,并在 Google Calendar 中创建指定时间且邀请 Jane 的'New Hire Orientation'事件\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"workday_mock\",\"google_calendar_mock\"],\"scoring_components\":[{\"name\":\"Component A\",\"weight\":0.5,\"description\":\"Workday 中 Jane Doe 的入职待办任务从 Pending 变为 Completed\",\"check_logic\":\"通过 fetch 获取 initial_state 和 current_state,遍历 state['tasks'] 查找 taskId 为 't3' 的任务,检查初始状态不在 ('completed', 'complete', 'done') 中且当前状态在该集合中\",\"pass_condition\":\"初始状态不是已完成状态,且当前状态为 'completed'、'complete' 或 'done'\"},{\"name\":\"Component C\",\"weight\":0.25,\"description\":\"Google Calendar 中存在日期为 2026-07-01、时段 10:00–11:00 的'New Hire Orientation'事件\",\"check_logic\":\"从 current_state['events'] 中筛选标题包含 'new hire orientation' 且 id 不在 initial_state 事件 id 集合中的事件(有 fallback 仅按标题匹配),使用 parse_hhmm 解析 start 和 end 字段,检查日期是否为 2026-07-01、start 是否为 10:00、end 是否为 11:00\",\"pass_condition\":\"事件 start 为 2026-07-01T10:00 且 end 为 2026-07-01T11:00\"},{\"name\":\"Component D\",\"weight\":0.25,\"description\":\"该 orientation 事件邀请了 jane.doe@company.com\",\"check_logic\":\"检查 orientation 事件的 guests 列表中是否存在 'jane.doe@company.com'(将 guests 元素转为小写字符串后比较)\",\"pass_condition\":\"guests 列表中包含 'jane.doe@company.com'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空时提前退出,返回 0.0\",\"Workday 服务不可达(fetch 返回 None)导致 Component A 得 0.0\",\"Calendar 服务不可达(fetch 返回 None)导致 Calendar 部分得 0.0\",\"Workday 中 taskId='t3' 不存在或状态未从 Pending 变为 Completed,Component A 得 0.0\",\"Calendar 中找不到标题包含 'new hire orientation' 的事件时直接返回 0.0,跳过 Component D 检查\",\"事件 start/end 时间不符合 2026-07-01 10:00–11:00 导致 Component C 不得分\",\"事件 guests 不包含 jane.doe@company.com 导致 Component D 不得分\",\"解析状态或事件时发生异常被捕获,返回 0.0 或当前已得分数\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接输出 REWARD: 0.0 并退出。随后分别验证 Workday 和 Calendar 两个部分:在 verify_workday 中,向 workday_mock 请求 initial_state 和 current_state,查找 tasks 列表里 taskId 为 't3' 的任务,若其初始状态不是已完成且当前状态变为 'completed'/'complete'/'done',则获得 0.50 分;在 verify_calendar 中,向 google_calendar_mock 请求状态,从 current_state['events'] 中找出标题包含 'new hire orientation' 且不在初始事件中的新事件(支持仅按标题匹配的 fallback),若找不到则直接返回 0.0。找到事件后,先解析 start 和 end 时间,若日期为 2026-07-01 且时段为 10:00–11:00 则获得 0.25 分;再检查 guests 列表是否包含 'jane.doe@company.com',包含则再获得 0.25 分。最终总分为三部分之和,通过 min(total, 1.0) 钳制上限为 1.0,并四舍五入保留 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/mktg_leadhandoff_001/_cua_gym_vm_bridge.sh b/legacy/mktg_leadhandoff_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/mktg_leadhandoff_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://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/mktg_leadhandoff_001/initial_setup.py b/legacy/mktg_leadhandoff_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..39795f60fdc83d48ba5593823734c58210fa0ee7 --- /dev/null +++ b/legacy/mktg_leadhandoff_001/initial_setup.py @@ -0,0 +1,306 @@ +""" +Initial Setup: Product Demo Request lead handoff (HubSpot -> Airtable -> Slack) +Task ID: mktg_leadhandoff_001 +Domain: mock_websites +Mocks: hubspot_mock, airtable_mock, slack_mock + +Pre-task state: +- HubSpot CRM with 8 contacts in the 'mql' lifecycle stage (the Product Demo + Request campaign leads), each with owner = "Unassigned". Distractor contacts + in other lifecycle stages already have owners. A "Product Demo Request" lead + form (8 submissions) reinforces the campaign narrative. Jordan Blake is NOT + yet the owner of any MQL contact. +- Airtable base "RevOps" with a "Lead Handoff" table + (fields: Campaign, Lead Count, Assigned To, Handoff Date) containing one prior + unrelated handoff record. NO "Product Demo Request" record yet. +- Slack workspace with a #sales-handoff channel containing prior chatter. + Jordan Blake (@jordan) is a member. NO handoff message for this campaign yet. + +Isolation note: initial_env and golden_env are SEPARATE containers that share +the xlang.ai HTTP server. To keep their server states independent, each env +uses its OWN sid. initial_setup uses the '-init' sid; golden_patch uses +'-gold' and independently rebuilds the same baseline before applying its +changes (see golden_patch.py). reward.py on each VM reads the sid this script +(or golden_patch) writes to /tmp/task_web_sid. +""" + +import hashlib +import os +import shlex +import subprocess +import time + +import requests + +# --- Configuration --- +TASK_ID = 'mktg_leadhandoff_001' + +HUBSPOT_URL = 'http://28.7.186.212:8170' +AIRTABLE_URL = 'http://28.7.186.212:8129' +SLACK_URL = 'http://28.7.186.212:8198' + +_BASE = 'cua-' + hashlib.md5(TASK_ID.encode()).hexdigest()[:12] +SID = _BASE + '-init' # initial_env sid (distinct from golden_env) + +with open('/tmp/task_web_sid', 'w') as f: + f.write(SID) +print(f'Session ID (initial_env): {SID}') + + +# --------------------------------------------------------------------------- +# Shared baseline (pre-task) state builders. +# NOTE: golden_patch.py duplicates equivalent builders so that golden_env can +# independently reconstruct this exact baseline before applying its changes +# (Rule 1: no cross-env dependency). +# --------------------------------------------------------------------------- +def build_hubspot_state(): + companies = [ + {"id": "comp1", "name": "Brightwave Analytics", "domain": "brightwave.io", + "industry": "Technology", "phone": "+1 (555) 100-0001", "city": "Austin", + "state": "TX", "country": "United States", "numberOfEmployees": 120, + "annualRevenue": 8000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Analytics platform for product teams.", + "createDate": "2026-02-10T09:00:00Z"}, + {"id": "comp2", "name": "Northpeak Logistics", "domain": "northpeak.com", + "industry": "Manufacturing", "phone": "+1 (555) 100-0002", "city": "Denver", + "state": "CO", "country": "United States", "numberOfEmployees": 340, + "annualRevenue": 22000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Freight and supply-chain logistics.", + "createDate": "2026-02-15T09:00:00Z"}, + {"id": "comp3", "name": "Vertex Health", "domain": "vertexhealth.org", + "industry": "Healthcare", "phone": "+1 (555) 100-0003", "city": "Boston", + "state": "MA", "country": "United States", "numberOfEmployees": 210, + "annualRevenue": 15000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Patient engagement software.", + "createDate": "2026-03-01T09:00:00Z"}, + {"id": "comp4", "name": "Lumina Retail", "domain": "luminaretail.com", + "industry": "Other", "phone": "+1 (555) 100-0004", "city": "Chicago", + "state": "IL", "country": "United States", "numberOfEmployees": 95, + "annualRevenue": 6000000, "lifecycleStage": "lead", "owner": "Admin User", + "description": "Omnichannel retail operations.", + "createDate": "2026-03-05T09:00:00Z"}, + ] + + mql_leads = [ + ("c1", "Daniel", "Brooks", "daniel.brooks@brightwave.io", "+1 (555) 010-1001", "VP Product", "comp1"), + ("c2", "Priya", "Raman", "priya.raman@brightwave.io", "+1 (555) 010-1002", "Head of Analytics", "comp1"), + ("c3", "Marcus", "Webb", "marcus.webb@northpeak.com", "+1 (555) 010-1003", "Operations Director", "comp2"), + ("c4", "Elena", "Foster", "elena.foster@northpeak.com", "+1 (555) 010-1004", "Logistics Manager", "comp2"), + ("c5", "Tobias", "Klein", "tobias.klein@vertexhealth.org", "+1 (555) 010-1005", "CTO", "comp3"), + ("c6", "Hannah", "Cole", "hannah.cole@vertexhealth.org", "+1 (555) 010-1006", "Product Lead", "comp3"), + ("c7", "Victor", "Nguyen", "victor.nguyen@luminaretail.com", "+1 (555) 010-1007", "Director of Digital", "comp4"), + ("c8", "Sofia", "Marenco", "sofia.marenco@luminaretail.com", "+1 (555) 010-1008", "Ecommerce Manager", "comp4"), + ] + contacts = [] + for cid, fn, ln, email, phone, title, comp in mql_leads: + contacts.append({ + "id": cid, "firstName": fn, "lastName": ln, "email": email, "phone": phone, + "jobTitle": title, "companyId": comp, "lifecycleStage": "mql", + "leadStatus": "open", "owner": "Unassigned", "city": "United States", + "state": "", "country": "United States", + "createDate": "2026-06-25T11:00:00Z", "lastActivityDate": "2026-06-28T16:00:00Z", + "timeline": [], + }) + + # Distractors — other lifecycle stages, already owned. The agent must NOT + # touch these. c11 is already owned by Jordan Blake (an SQL contact) to make + # naive "all Jordan contacts" reasoning insufficient. + distractors = [ + ("c9", "Alice", "Freeman", "alice@oldcorp.com", "+1 (555) 010-2001", "CFO", "comp1", "customer", "connected", "Admin User"), + ("c10", "Grace", "Liu", "grace.liu@northpeak.com", "+1 (555) 010-2002", "Analyst", "comp2", "lead", "new", "Admin User"), + ("c11", "Omar", "Haddad", "omar.haddad@vertexhealth.org", "+1 (555) 010-2003", "Engineering Manager", "comp3", "sql", "open_deal", "Jordan Blake"), + ("c12", "Nina", "Alvarez", "nina.alvarez@luminaretail.com", "+1 (555) 010-2004", "VP Marketing", "comp4", "opportunity", "open_deal", "Casey Morgan"), + ] + for cid, fn, ln, email, phone, title, comp, stage, ls, owner in distractors: + contacts.append({ + "id": cid, "firstName": fn, "lastName": ln, "email": email, "phone": phone, + "jobTitle": title, "companyId": comp, "lifecycleStage": stage, + "leadStatus": ls, "owner": owner, "city": "United States", "state": "", + "country": "United States", "createDate": "2026-01-20T10:00:00Z", + "lastActivityDate": "2026-06-20T14:00:00Z", "timeline": [], + }) + + deal_stages = { + "appointment_scheduled": {"id": "appointment_scheduled", "label": "Appointment Scheduled", "probability": 20, "color": "#E5F4FF", "order": 1}, + "qualified_to_buy": {"id": "qualified_to_buy", "label": "Qualified to Buy", "probability": 40, "color": "#FFF0E6", "order": 2}, + "presentation_scheduled": {"id": "presentation_scheduled", "label": "Presentation Scheduled", "probability": 60, "color": "#FFF8E6", "order": 3}, + "decision_maker_bought_in": {"id": "decision_maker_bought_in", "label": "Decision Maker Bought-In", "probability": 80, "color": "#E8F5E9", "order": 4}, + "contract_sent": {"id": "contract_sent", "label": "Contract Sent", "probability": 90, "color": "#E6FFFA", "order": 5}, + "closed_won": {"id": "closed_won", "label": "Closed Won", "probability": 100, "color": "#E6FFEC", "order": 6}, + "closed_lost": {"id": "closed_lost", "label": "Closed Lost", "probability": 0, "color": "#FFE6E6", "order": 7}, + } + ticket_statuses = { + "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1}, + "waiting_on_contact": {"id": "waiting_on_contact", "label": "Waiting on Contact", "color": "#FFF8E6", "order": 2}, + "waiting_on_us": {"id": "waiting_on_us", "label": "Waiting on Us", "color": "#FFF0E6", "order": 3}, + "in_progress": {"id": "in_progress", "label": "In Progress", "color": "#E6FFFA", "order": 4}, + "closed": {"id": "closed", "label": "Closed", "color": "#E6FFEC", "order": 5}, + } + + return { + "contacts": contacts, + "companies": companies, + "deals": [], + "tickets": [], + "tasks": [], + "notes": [], + "templates": [], + "meetings": [], + "forms": [ + {"id": "f1", "name": "Product Demo Request", "status": "active", + "submissions": 8, "fields": ["email", "first_name", "last_name", "company", "job_title"], + "createDate": "2026-06-20T10:00:00Z", "lastSubmission": "2026-06-28T16:00:00Z"}, + {"id": "f2", "name": "Newsletter Signup", "status": "active", + "submissions": 230, "fields": ["email"], + "createDate": "2026-01-10T10:00:00Z", "lastSubmission": "2026-06-29T09:00:00Z"}, + ], + "dealStages": deal_stages, + "ticketStatuses": ticket_statuses, + "appState": { + "sidebarOpen": True, + "currentUser": {"name": "Admin User", "email": "admin@example.com", "avatar": None}, + }, + } + + +def build_airtable_state(): + collaborators = [ + {"id": "user_1", "name": "John Doe", "email": "john.doe@example.com", + "avatar": "https://ui-avatars.com/api/?name=John+Doe&background=8B5CF6&color=fff"}, + {"id": "user_2", "name": "Alice Chen", "email": "alice.chen@example.com", + "avatar": "https://ui-avatars.com/api/?name=Alice+Chen&background=EC4899&color=fff"}, + ] + fields = [ + {"id": "fld_campaign", "name": "Campaign", "type": "text", "primary": True}, + {"id": "fld_count", "name": "Lead Count", "type": "number"}, + {"id": "fld_assigned", "name": "Assigned To", "type": "text"}, + {"id": "fld_date", "name": "Handoff Date", "type": "date"}, + ] + records = [ + {"id": "rec_prior_1", "createdTime": "2026-06-10T09:30:00.000Z", + "fields": {"fld_campaign": "Spring Newsletter Signups", "fld_count": 5, + "fld_assigned": "Casey Morgan", "fld_date": "2026-06-10"}}, + ] + return { + "currentUser": collaborators[0], + "collaborators": collaborators, + "bases": {"base_revops": {"id": "base_revops", "name": "RevOps", + "color": "bg-teal-600", "tables": ["tbl_handoff"]}}, + "tables": {"tbl_handoff": { + "id": "tbl_handoff", "name": "Lead Handoff", "baseId": "base_revops", + "fields": fields, "records": records, + "views": [{"id": "view_grid", "name": "All Handoffs", "type": "grid", + "filters": [], "sorts": [], "groupBy": [], "hiddenFieldIds": [], + "fieldWidths": {}, "rowHeight": "short"}], + "activeViewId": "view_grid"}}, + "activeBaseId": "base_revops", + "activeTableId": "tbl_handoff", + "ui": {"viewSidebarOpen": False, "expandedRecordId": None, + "searchQuery": "", "isSearching": False}, + } + + +def build_slack_state(): + users = [ + {"userId": "user_1", "fullName": "Maya Patel", "displayName": "maya", + "email": "maya.patel@company.com", "avatar": "https://picsum.photos/200/200?random=1", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "user_2", "fullName": "Jordan Blake", "displayName": "jordan", + "email": "jordan.blake@company.com", "avatar": "https://picsum.photos/200/200?random=2", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"}, + {"userId": "user_3", "fullName": "Casey Morgan", "displayName": "casey", + "email": "casey.morgan@company.com", "avatar": "https://picsum.photos/200/200?random=3", + "status": "away", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"}, + {"userId": "user_4", "fullName": "Dana Reed", "displayName": "dana", + "email": "dana.reed@company.com", "avatar": "https://picsum.photos/200/200?random=4", + "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + ] + return { + "currentUser": users[0], + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme RevOps", "icon": ""}, + "users": users, + "channels": [ + {"channelId": "sales-handoff", "name": "sales-handoff", + "description": "Marketing-to-sales lead handoffs", "topic": "Qualified leads ready for sales", + "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_1", + "createdAt": "2026-05-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "general", "name": "general", "description": "General chat", "topic": "", + "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3", "user_4"], + "createdBy": "user_1", "createdAt": "2026-05-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "sales-handoff": [ + {"messageId": "msg_h1", "senderId": "user_3", + "content": "Handed off the 5 Spring Newsletter leads earlier this month — @jordan let me know if you need the list again.", + "timestamp": "2026-06-10T09:35:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + {"messageId": "msg_h2", "senderId": "user_2", + "content": "Got them, thanks Casey. Following up this week.", + "timestamp": "2026-06-10T10:00:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + "general": [ + {"messageId": "msg_g1", "senderId": "user_4", "content": "Morning team!", + "timestamp": "2026-06-30T08:00:00Z", "threadId": None, "reactions": [], + "attachments": [], "isEdited": False}, + ], + }, + "threads": {}, + "dms": [], + "bookmarkedMessages": [], + "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], + "notifications": [], + } + + +# --------------------------------------------------------------------------- +# Inject baseline state under the initial_env sid (action: set). +# --------------------------------------------------------------------------- +MOCKS = { + HUBSPOT_URL: build_hubspot_state(), + AIRTABLE_URL: build_airtable_state(), + SLACK_URL: build_slack_state(), +} + +print("Resetting any stale state and injecting initial state...") +for url, state in MOCKS.items(): + requests.post(f'{url}/post?sid={SID}', json={'action': 'reset'}, timeout=30) + r = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': state}, timeout=30) + r.raise_for_status() + print(f"OK: injected {url}") + +# --- Verify --- +print("Verifying state injection...") +hs_go = requests.get(f'{HUBSPOT_URL}/go?sid={SID}', timeout=10).json() +assert hs_go['initial_state'] is not None, 'HubSpot initial_state is None' +mql = [c for c in hs_go['current_state']['contacts'] if c['lifecycleStage'] == 'mql'] +assert len(mql) == 8, f'Expected 8 MQL contacts, got {len(mql)}' +assert all(c['owner'] == 'Unassigned' for c in mql), 'Some MQL contacts already have an owner' +# Pre-task: no Product Demo Request handoff record, no handoff message yet. +at_go = requests.get(f'{AIRTABLE_URL}/go?sid={SID}', timeout=10).json() +campaigns = [r['fields'].get('fld_campaign') for r in at_go['current_state']['tables']['tbl_handoff']['records']] +assert 'Product Demo Request' not in campaigns, 'Handoff record already present in initial state' +sl_go = requests.get(f'{SLACK_URL}/go?sid={SID}', timeout=10).json() +assert len(sl_go['current_state']['messages']['sales-handoff']) == 2, 'Unexpected #sales-handoff message count' +print(f"OK: verified 8 unassigned MQL contacts, no handoff record, no handoff message") + +# --------------------------------------------------------------------------- +# Launch browsers (GUI-ready start state) +# --------------------------------------------------------------------------- +def launch_gui(command: str, delay_sec: float = 1.0): + env = os.environ.copy() + env["DISPLAY"] = ":0" + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env) + time.sleep(delay_sec) + +print("Launching browsers...") +launch_gui(f'google-chrome "{HUBSPOT_URL}/?sid={SID}"', delay_sec=2.0) +launch_gui(f'google-chrome "{AIRTABLE_URL}/?sid={SID}"', delay_sec=1.5) +launch_gui(f'google-chrome "{SLACK_URL}/?sid={SID}"', delay_sec=1.0) +print('GUI_READY: launched HubSpot, Airtable and Slack mock websites with DISPLAY=:0') +print(f'Session ID: {SID}') diff --git a/legacy/mktg_leadhandoff_001/reward.py b/legacy/mktg_leadhandoff_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..9e15bbfe5536cb467f736f4797b23042cbeb949b --- /dev/null +++ b/legacy/mktg_leadhandoff_001/reward.py @@ -0,0 +1,244 @@ +""" +Reward Script: Lead handoff — reassign 8 MQL contacts to Jordan Blake in HubSpot, +log the handoff in Airtable 'Lead Handoff', and notify @jordan in Slack #sales-handoff. +Task ID: mktg_leadhandoff_001 +Domain: mock_websites (multi-mock: hubspot + airtable + slack) + +Scoring (all structural / deterministic — no LLM judge needed): + Component 1 — HubSpot reassignment 0.40 + Component 2 — Airtable 'Lead Handoff' record 0.35 + Component 3 — Slack #sales-handoff message 0.25 + Total 1.00 + +Each component verifies a TASK-INTRODUCED change (fails on initial_env, passes on +golden_env). Target contacts are derived from the task description ("8 contacts in +MQL lifecycle stage, none yet assigned an owner") against the INITIAL state, not by +peeking at the golden answer. +""" +import datetime +import sys + +import requests + +HUBSPOT_URL = 'http://28.7.186.212:8170' +AIRTABLE_URL = 'http://28.7.186.212:8129' +SLACK_URL = 'http://28.7.186.212:8198' + +# --- Read sid --- +try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def fetch(base_url): + """Fetch /go state for a mock. Returns (initial, current) or (None, None) on failure.""" + try: + data = requests.get(f'{base_url}/go?sid={sid}', timeout=20).json() + except Exception as e: + print(f'ERROR: cannot fetch {base_url}: {e}') + return None, None + return data.get('initial_state') or {}, data.get('current_state') or {} + + +def verify_task(): + total_score = 0.0 + + # ===================== Component 1: HubSpot reassignment (0.40) ===================== + # Derive the target set from the task: contacts that in the INITIAL state are in the + # 'mql' lifecycle stage AND have no owner assigned ("Unassigned"). The task says these + # 8 must be reassigned to owner == "Jordan Blake". We anchor to the change, and also + # guard against over-assignment (contacts that should NOT have been touched). + try: + hs_init, hs_cur = fetch(HUBSPOT_URL) + if hs_cur is None or not hs_cur.get('contacts'): + print('FAIL: Component 1 — could not read HubSpot contacts') + else: + init_contacts = {c['id']: c for c in hs_init.get('contacts', [])} + cur_contacts = {c['id']: c for c in hs_cur.get('contacts', [])} + + def is_unassigned(owner): + return (owner or '').strip().lower() in ('', 'unassigned', 'none') + + # Target contacts (from task requirement, evaluated on INITIAL state) + targets = [ + cid for cid, c in init_contacts.items() + if (c.get('lifecycleStage') or '').lower() == 'mql' and is_unassigned(c.get('owner')) + ] + n_targets = len(targets) + + # How many targets are now owned by Jordan Blake? + correct = [ + cid for cid in targets + if (cur_contacts.get(cid, {}).get('owner') or '').strip().lower() == 'jordan blake' + ] + + # Over-assignment guard: contacts NOT in the target set whose owner newly + # became 'Jordan Blake' (were not Jordan in initial). These should not exist. + extras = [] + for cid, c in cur_contacts.items(): + if cid in targets: + continue + cur_owner = (c.get('owner') or '').strip().lower() + init_owner = (init_contacts.get(cid, {}).get('owner') or '').strip().lower() + if cur_owner == 'jordan blake' and init_owner != 'jordan blake': + extras.append(cid) + + if n_targets == 0: + print('FAIL: Component 1 — no MQL/unassigned target contacts found in initial state') + else: + base = 0.40 * (len(correct) / n_targets) + # Penalize over-assignment: halve the component if unrelated contacts were + # reassigned to Jordan (task says "No other contacts ... are affected"). + if extras: + base *= 0.5 + print(f'WARN: Component 1 — over-assignment to Jordan on non-target contacts: {extras}') + total_score += base + print(f'{"PASS" if len(correct)==n_targets and not extras else "PARTIAL"}: ' + f'Component 1 — {len(correct)}/{n_targets} target MQL contacts reassigned to ' + f'Jordan Blake ({base:.3f} pts). targets={sorted(targets)}') + except Exception as e: + print(f'ERROR: Component 1 — {e}') + + # ===================== Component 2: Airtable 'Lead Handoff' record (0.35) ===================== + # A NEW record in the 'Lead Handoff' table with: + # Campaign = 'Product Demo Request', Lead Count = 8, + # Assigned To = 'Jordan Blake', Handoff Date = today. + # Sub-scores: campaign 0.15, count 0.08, assigned 0.07, date 0.05. + try: + at_init, at_cur = fetch(AIRTABLE_URL) + if at_cur is None or not at_cur.get('tables'): + print('FAIL: Component 2 — could not read Airtable tables') + else: + def find_handoff_table(state): + for tid, t in state.get('tables', {}).items(): + if t.get('name', '').strip().lower() == 'lead handoff': + return t + return None + + init_tbl = find_handoff_table(at_init) + cur_tbl = find_handoff_table(at_cur) + if cur_tbl is None: + print('FAIL: Component 2 — Lead Handoff table not found') + else: + # Map field names -> field ids (resilient to id naming) + fid = {f.get('name', '').strip().lower(): f['id'] for f in cur_tbl.get('fields', [])} + f_campaign = fid.get('campaign') + f_count = fid.get('lead count') + f_assigned = fid.get('assigned to') + f_date = fid.get('handoff date') + + init_ids = {r['id'] for r in (init_tbl.get('records', []) if init_tbl else [])} + new_records = [r for r in cur_tbl.get('records', []) if r['id'] not in init_ids] + + today = datetime.date.today().isoformat() + + def norm(v): + return str(v).strip().lower() if v is not None else '' + + # Find the best-matching new record (one mentioning the campaign) + target_rec = None + for r in new_records: + fields = r.get('fields', {}) + if f_campaign and 'product demo request' in norm(fields.get(f_campaign)): + target_rec = r + break + if target_rec is None and new_records: + # fall back to any new record for partial credit on other fields + target_rec = new_records[0] + + if target_rec is None: + print('FAIL: Component 2 — no new record added to Lead Handoff table') + else: + flds = target_rec.get('fields', {}) + # Campaign (0.15) + if f_campaign and 'product demo request' in norm(flds.get(f_campaign)): + total_score += 0.15 + print('PASS: Component 2a — Campaign = Product Demo Request (0.15 pts)') + else: + print(f'FAIL: Component 2a — Campaign mismatch: {flds.get(f_campaign)!r}') + # Lead Count (0.08) + try: + if f_count and int(float(flds.get(f_count))) == 8: + total_score += 0.08 + print('PASS: Component 2b — Lead Count = 8 (0.08 pts)') + else: + print(f'FAIL: Component 2b — Lead Count != 8: {flds.get(f_count)!r}') + except Exception: + print(f'FAIL: Component 2b — Lead Count not numeric: {flds.get(f_count)!r}') + # Assigned To (0.07) + if f_assigned and norm(flds.get(f_assigned)) == 'jordan blake': + total_score += 0.07 + print('PASS: Component 2c — Assigned To = Jordan Blake (0.07 pts)') + else: + print(f'FAIL: Component 2c — Assigned To mismatch: {flds.get(f_assigned)!r}') + # Handoff Date = today (0.05) + if f_date and norm(flds.get(f_date)) == today: + total_score += 0.05 + print(f'PASS: Component 2d — Handoff Date = today ({today}) (0.05 pts)') + else: + print(f'FAIL: Component 2d — Handoff Date != today ({today}): {flds.get(f_date)!r}') + except Exception as e: + print(f'ERROR: Component 2 — {e}') + + # ===================== Component 3: Slack #sales-handoff message (0.25) ===================== + # A NEW message in the #sales-handoff channel that mentions @jordan and references + # following up on the new leads. + # Sub-scores: new message mentioning @jordan 0.15, references follow-up of leads 0.10. + try: + sl_init, sl_cur = fetch(SLACK_URL) + if sl_cur is None or not sl_cur.get('channels'): + print('FAIL: Component 3 — could not read Slack state') + else: + # Resolve #sales-handoff channelId + ch_id = None + for ch in sl_cur.get('channels', []): + if ch.get('name', '').strip().lower() == 'sales-handoff': + ch_id = ch.get('channelId') + break + if ch_id is None: + print('FAIL: Component 3 — #sales-handoff channel not found') + else: + init_msgs = sl_init.get('messages', {}).get(ch_id, []) + cur_msgs = sl_cur.get('messages', {}).get(ch_id, []) + new_msgs = cur_msgs[len(init_msgs):] if len(cur_msgs) > len(init_msgs) else [] + + if not new_msgs: + print('FAIL: Component 3 — no new message in #sales-handoff') + else: + # Sub 3a: a new message mentioning @jordan (0.15) + mention_msgs = [m for m in new_msgs if '@jordan' in (m.get('content') or '').lower()] + if mention_msgs: + total_score += 0.15 + print('PASS: Component 3a — new #sales-handoff message mentions @jordan (0.15 pts)') + else: + print('FAIL: Component 3a — new message(s) exist but none mention @jordan') + + # Sub 3b: that message references following up on the leads (0.10) + # Deterministic: content references "follow" up AND ("8" leads or "lead"). + def references_followup(text): + t = (text or '').lower() + has_follow = 'follow' in t + has_leads = ('lead' in t) or ('8' in t) + return has_follow and has_leads + candidates = mention_msgs if mention_msgs else new_msgs + if any(references_followup(m.get('content')) for m in candidates): + total_score += 0.10 + print('PASS: Component 3b — message asks Jordan to follow up on the leads (0.10 pts)') + else: + print('FAIL: Component 3b — message does not clearly ask to follow up on the (8) leads') + except Exception as e: + print(f'ERROR: Component 3 — {e}') + + final_score = round(min(total_score, 1.0), 4) + print(f'\nScore: {total_score:.4f}/1.0') + print(f'REWARD: {final_score}') + return final_score + + +verify_task() diff --git a/legacy/mktg_leadhandoff_001/reward_label.json b/legacy/mktg_leadhandoff_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..f6de9e48ca1c041d7fe91117fff5fc146170a363 --- /dev/null +++ b/legacy/mktg_leadhandoff_001/reward_label.json @@ -0,0 +1,54 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/mktg_leadhandoff_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:37", + "label": { + "task_id": "mktg_leadhandoff_001", + "domain": "mock_websites", + "summary": "验证将8个MQL联系人重新分配给Jordan Blake,在Airtable的Lead Handoff表中记录交接,并在Slack的#sales-handoff频道通知@jordan的完整任务流程", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "hubspot_mock", + "airtable_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1 — HubSpot reassignment", + "weight": 0.4, + "description": "检查初始状态中为MQL且未分配的联系人是否被重新分配给Jordan Blake,且非目标联系人未被过度分配", + "check_logic": "从HubSpot初始状态筛选 lifecycleStage 为'mql'(不区分大小写)且 owner 为空白/'unassigned'/'none' 的联系人作为目标集;计算当前状态中目标集内 owner 变为'jordan blake'的比例作为基础分 base = 0.40 * (correct / n_targets);遍历非目标联系人,若其当前 owner 为'jordan blake'而初始 owner 不是,则判定为过度分配,base *= 0.5", + "pass_condition": "所有目标联系人均被分配给 Jordan Blake,且无非目标联系人被分配给 Jordan Blake" + }, + { + "name": "Component 2 — Airtable 'Lead Handoff' record", + "weight": 0.35, + "description": "检查是否在Airtable的Lead Handoff表中新增了符合要求的记录", + "check_logic": "对比初始与当前状态找出Lead Handoff表中的新记录(按recordId判断);优先选择Campaign字段包含'product demo request'的记录,若无则取第一条新记录;按四个子项分别评分:Campaign包含'Product Demo Request'加0.15、Lead Count等于8加0.08、Assigned To为'Jordan Blake'加0.07、Handoff Date等于今天加0.05", + "pass_condition": "新增记录包含 Campaign='Product Demo Request'、Lead Count=8、Assigned To='Jordan Blake'、Handoff Date=今天" + }, + { + "name": "Component 3 — Slack #sales-handoff message", + "weight": 0.25, + "description": "检查是否在Slack的#sales-handoff频道发送了通知Jordan跟进线索的新消息", + "check_logic": "获取#sales-handoff频道当前消息列表相对于初始状态的新增消息;检查是否有新消息内容包含'@jordan'(不区分大小写)加0.15;检查消息内容是否同时包含'follow'与('lead'或'8')加0.10,优先在提及@jordan的消息中查找,否则在所有新消息中查找", + "pass_condition": "存在新消息提及@jordan,且内容要求跟进线索" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各子项分数累加得到 total_score,最终通过 round(min(total_score, 1.0), 4) 计算并钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接退出,REWARD 为 0.0", + "任一 mock 服务 fetch 失败(网络超时或返回异常):对应组件无法评分,该组件得 0 分", + "Component 1:初始状态中不存在 MQL 且未分配的目标联系人,该组件得 0 分;将非目标联系人过度分配给 Jordan Blake 会导致该组件分数减半", + "Component 2:Airtable 中找不到 Lead Handoff 表或未新增任何记录,该组件得 0 分", + "Component 3:Slack 中找不到 #sales-handoff 频道或该频道无新消息,该组件得 0 分" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接退出并返回 0.0。随后分别向三个 mock 服务(HubSpot、Airtable、Slack)的 /go 端点拉取 initial_state 和 current_state。Component 1 基于初始状态自动推导出目标联系人集(MQL 且未分配),按正确重新分配给 Jordan Blake 的比例计算 0.40 的基础分,若发现非目标联系人被错误分配给 Jordan Blake 则将该组件分数减半。Component 2 在 Airtable 的 Lead Handoff 表中寻找新增记录,按 Campaign、Lead Count、Assigned To、Handoff Date 四个子项分别加分。Component 3 检查 Slack #sales-handoff 频道的新消息是否提及 @jordan 并要求跟进线索。所有子项分数累加后,最终分数被钳制在 1.0 并四舍五入到 4 位小数。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。我需要仔细阅读源码,提取所有必要信息。\n\n让我逐段分析:\n\n1. **文件路径和 docstring**:\n - Task ID: mktg_leadhandoff_001\n - Domain: mock_websites (multi-mock: hubspot + airtable + slack)\n - 这是一个关于营销线索交接的任务:将8个MQL联系人重新分配给Jordan Blake,在Airtable中记录交接,并在Slack中通知@jordan\n\n2. **数据源**:\n - `/tmp/task_web_sid` - 读取 session ID\n - HubSpot mock: `http://28.7.186.212:8170`\n - Airtable mock: `http://28.7.186.212:8129`\n - Slack mock: `http://28.7.186.212:8198`\n\n3. **评分组件**:\n\n **Component 1 (0.40)**: HubSpot 重新分配\n - 从初始状态找出 lifecycleStage == 'mql' 且 owner 为未分配的联系人(目标集)\n - 检查这些目标联系人是否被重新分配给 \"Jordan Blake\"\n - 检查是否有非目标联系人被错误分配给 Jordan Blake(过度分配惩罚)\n - 基础分 = 0.40 * (正确分配数 / 目标总数)\n - 如果存在过度分配,基础分减半\n - 如果初始状态没有目标联系人,失败\n\n **Component 2 (0.35)**: Airtable 'Lead Handoff' 记录\n - 在 'Lead Handoff' 表中查找新记录(与初始状态对比)\n - 子分数:\n - Campaign = 'Product Demo Request' (0.15)\n - Lead Count = 8 (0.08)\n - Assigned To = 'Jordan Blake' (0.07)\n - Handoff Date = 今天 (0.05)\n - 先找提到 campaign 的新记录,如果没有则取第一个新记录\n - 逐项检查字段\n\n **Component 3 (0.25)**: Slack #sales-handoff 消息\n - 在 #sales-handoff 频道查找新消息\n - 子分数:\n - 新消息提到 @jordan (0.15)\n - 消息内容提到跟进线索 (0.10)\n - 跟进线索的判断逻辑:包含 \"follow\" 且包含 \"lead\" 或 \"8\"\n\n4. **分数汇总**:\n - 各组件分数相加\n - 最终分数 = round(min(total_score, 1.0), 4)\n - 上限为 1.0\n\n5. **失败模式**:\n - 读取 sid 失败(/tmp/task_web_sid 不存在或为空)-> 打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - fetch 失败(任何 mock 服务无法连接)-> 对应组件失败,但继续执行其他组件\n - Component 1: 无法读取 HubSpot 联系人、初始状态没有目标联系人、过度分配(扣分)\n - Component 2: 无法读取 Airtable、Lead Handoff 表不存在、没有新记录\n - Component 3: 无法读取 Slack、#sales-handoff 频道不存在、没有新消息、消息不包含 @jordan、消息不包含跟进线索\n\n6. **is_placeholder**: false,这是一个完整的评分脚本,不是占位符。\n\n7. **confidence**: 1.0,源码完整且逻辑清晰。\n\n现在构建 JSON:\n\n- task_id: \"mktg_leadhandoff_001\"\n- domain: \"mock_websites\"\n- summary: \"验证将8个MQL联系人重新分配给Jordan Blake,在Airtable的Lead Handoff表中记录交接,并在Slack的#sales-handoff频道通知@jordan的完整任务流程\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"hubspot_mock (http://28.7.186.212:8170)\", \"airtable_mock (http://28.7.186.212:8129)\", \"slack_mock (http://28.7.186.212:8198)\"]\n- scoring_components: 三个组件\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0\"\n- failure_modes: 列出各种失败情况\n- scoring_logic_explanation: 详细说明执行顺序和逻辑\n- confidence: 1.0\n\n让我再仔细检查一下 Component 1 的权重。文档说 Component 1 是 0.40,但它是按比例计算的。在 JSON 中,weight 应该填 0.40,因为代码中显式给出了这个分值。\n\nComponent 2 总分 0.35,由 0.15+0.08+0.07+0.05 组成。在 JSON 中,我可以把 Component 2 作为一个整体,weight 0.35,然后在 check_logic 中说明子分数。\n\nComponent 3 总分 0.25,由 0.15+0.10 组成。\n\n对于 failure_modes,需要包括:\n- 读取 sid 失败导致提前退出\n- fetch 任何 mock 失败导致对应组件无法评分\n- Component 1: 初始状态无 MQL/Unassigned 目标联系人;过度分配非目标联系人给 Jordan Blake 导致分数减半\n- Component 2: Lead Handoff 表不存在或无新记录\n- Component 3: #sales-handoff 频道不存在或无新消息\n\n等等,我需要更仔细地看看 Component 1 的 \"fail\" 情况。如果 `n_targets == 0`,它打印 FAIL 但不退出,只是不加基础分。如果 `hs_cur` 为 None 或没有 contacts,也是打印 FAIL 但不退出。所以这些不会导致提前退出,只是该组件得 0 分。\n\n只有读取 sid 失败会导致 `sys.exit(0)`。\n\n让我重新组织 failure_modes:\n- 读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,REWARD: 0.0,提前退出\n- 各 mock 服务 fetch 失败:对应组件无法评分,得 0 分\n- Component 1: 初始状态无 MQL/Unassigned 联系人(该组件得 0 分);过度分配非目标联系人给 Jordan Blake(该组件分数减半)\n- Component 2: Lead Handoff 表不存在或无新记录(该子项得 0 分)\n- Component 3: #sales-handoff 频道不存在或无新消息(该子项得 0 分)\n\n现在确认 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n我需要确保 JSON 是有效的,所有引号正确转义。\n\n让我构建 scoring_components:\n\nComponent 1:\n- name: \"Component 1 — HubSpot reassignment\"\n- weight: 0.40\n- description: \"检查初始状态中为 MQL 且未分配的联系人是否被重新分配给 Jordan Blake,且非目标联系人未被过度分配\"\n- check_logic: \"从初始状态筛选 lifecycleStage == 'mql' 且 owner 为 Unassigned/None/空白的联系人作为目标集;计算当前状态中目标集内 owner 变为 'jordan blake' 的比例作为基础分 base = 0.40 * (correct / n_targets);遍历非目标联系人,若其当前 owner 为 'jordan blake' 且初始 owner 不是,则判定为过度分配,base *= 0.5\"\n- pass_condition: \"所有目标联系人均被分配给 Jordan Blake,且无非目标联系人被分配给 Jordan Blake\"\n\nComponent 2:\n- name: \"Component 2 — Airtable 'Lead Handoff' record\"\n- weight: 0.35\n- description: \"检查是否在 Airtable 的 Lead Handoff 表中新增了符合要求的记录\"\n- check_logic: \"对比初始与当前状态找出 Lead Handoff 表中的新记录;优先选择 Campaign 字段包含 'product demo request' 的记录,否则取第一条新记录;逐项检查 Campaign (0.15)、Lead Count (0.08)、Assigned To (0.07)、Handoff Date (0.05)\"\n- pass_condition: \"新增记录包含 Campaign='Product Demo Request'、Lead Count=8、Assigned To='Jordan Blake'、Handoff Date=今天\"\n\nComponent 3:\n- name: \"Component 3 — Slack #sales-handoff message\"\n- weight: 0.25\n- description: \"检查是否在 Slack 的 #sales-handoff 频道发送了通知 Jordan 跟进线索的新消息\"\n- check_logic: \"获取 #sales-handoff 频道的新消息(当前消息列表长度大于初始的部分);检查是否有新消息包含 '@jordan' (0.15);检查消息内容是否同时包含 'follow' 和 ('lead' 或 '8') (0.10)\"\n- pass_condition: \"存在新消息提及 @jordan,且内容要求跟进线索\"\n\nscore_aggregation: \"各子项分数累加得到 total_score,最终通过 round(min(total_score, 1.0), 4) 计算并钳制到 1.0\"\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接退出并返回 0.0。随后分别向三个 mock 服务(HubSpot、Airtable、Slack)的 /go 端点拉取 initial_state 和 current_state。Component 1 基于初始状态自动推导出目标联系人集(MQL 且未分配),按正确重新分配给 Jordan Blake 的比例计算 0.40 的基础分,若发现非目标联系人被错误分配给 Jordan Blake 则将该组件分数减半。Component 2 在 Airtable 的 Lead Handoff 表中寻找新增记录,按 Campaign、Lead Count、Assigned To、Handoff Date 四个子项分别加分。Component 3 检查 Slack #sales-handoff 频道的新消息是否提及 @jordan 并要求跟进线索。所有子项分数累加后,最终分数被钳制在 1.0 并四舍五入到 4 位小数。\"\n\ndata_sources: [\"/tmp/task_web_sid\", \"http://28.7.186.212:8170 (HubSpot mock)\", \"http://28.7.186.212:8129 (Airtable mock)\", \"http://28.7.186.212:8198 (Slack mock)\"]\n\n等等,用户要求 data_sources 的格式如 slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid 等。我应该用更通用的名称。\n\ndata_sources: [\"/tmp/task_web_sid\", \"hubspot_mock\", \"airtable_mock\", \"slack_mock\"]\n\n现在检查所有字段名是否保留原样:\n- task_id: \"mktg_leadhandoff_001\"\n- domain: \"mock_websites\"\n- 代码中的字段名如 lifecycleStage, owner, contacts, Lead Handoff, Campaign, Lead Count, Assigned To, Handoff Date, sales-handoff, @jordan 等都在 check_logic 和 pass_condition 中保留了。\n\n让我再检查一下 Component 2 的字段名映射逻辑。代码中是通过 `f.get('name', '').strip().lower()` 来映射字段名到 field id 的。所以字段名是大小写不敏感的。我在描述中应该提到这一点。\n\n还有 Component 1 的 `is_unassigned` 函数检查 owner 是否为 '', 'unassigned', 'none'。\n\n好的,我觉得分析已经完整了。现在输出 JSON。 {\"task_id\":\"mktg_leadhandoff_001\",\"domain\":\"mock_websites\",\"summary\":\"验证将8个MQL联系人重新分配给Jordan Blake,在Airtable的Lead Handoff表中记录交接,并在Slack的#sales-handoff频道通知@jordan的完整任务流程\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"hubspot_mock\",\"airtable_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 1 — HubSpot reassignment\",\"weight\":0.4,\"description\":\"检查初始状态中为MQL且未分配的联系人是否被重新分配给Jordan Blake,且非目标联系人未被过度分配\",\"check_logic\":\"从HubSpot初始状态筛选 lifecycleStage 为'mql'(不区分大小写)且 owner 为空白/'unassigned'/'none' 的联系人作为目标集;计算当前状态中目标集内 owner 变为'jordan blake'的比例作为基础分 base = 0.40 * (correct / n_targets);遍历非目标联系人,若其当前 owner 为'jordan blake'而初始 owner 不是,则判定为过度分配,base *= 0.5\",\"pass_condition\":\"所有目标联系人均被分配给 Jordan Blake,且无非目标联系人被分配给 Jordan Blake\"},{\"name\":\"Component 2 — Airtable 'Lead Handoff' record\",\"weight\":0.35,\"description\":\"检查是否在Airtable的Lead Handoff表中新增了符合要求的记录\",\"check_logic\":\"对比初始与当前状态找出Lead Handoff表中的新记录(按recordId判断);优先选择Campaign字段包含'product demo request'的记录,若无则取第一条新记录;按四个子项分别评分:Campaign包含'Product Demo Request'加0.15、Lead Count等于8加0.08、Assigned To为'Jordan Blake'加0.07、Handoff Date等于今天加0.05\",\"pass_condition\":\"新增记录包含 Campaign='Product Demo Request'、Lead Count=8、Assigned To='Jordan Blake'、Handoff Date=今天\"},{\"name\":\"Component 3 — Slack #sales-handoff message\",\"weight\":0.25,\"description\":\"检查是否在Slack的#sales-handoff频道发送了通知Jordan跟进线索的新消息\",\"check_logic\":\"获取#sales-handoff频道当前消息列表相对于初始状态的新增消息;检查是否有新消息内容包含'@jordan'(不区分大小写)加0.15;检查消息内容是否同时包含'follow'与('lead'或'8')加0.10,优先在提及@jordan的消息中查找,否则在所有新消息中查找\",\"pass_condition\":\"存在新消息提及@jordan,且内容要求跟进线索\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各子项分数累加得到 total_score,最终通过 round(min(total_score, 1.0), 4) 计算并钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接退出,REWARD 为 0.0\",\"任一 mock 服务 fetch 失败(网络超时或返回异常):对应组件无法评分,该组件得 0 分\",\"Component 1:初始状态中不存在 MQL 且未分配的目标联系人,该组件得 0 分;将非目标联系人过度分配给 Jordan Blake 会导致该组件分数减半\",\"Component 2:Airtable 中找不到 Lead Handoff 表或未新增任何记录,该组件得 0 分\",\"Component 3:Slack 中找不到 #sales-handoff 频道或该频道无新消息,该组件得 0 分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接退出并返回 0.0。随后分别向三个 mock 服务(HubSpot、Airtable、Slack)的 /go 端点拉取 initial_state 和 current_state。Component 1 基于初始状态自动推导出目标联系人集(MQL 且未分配),按正确重新分配给 Jordan Blake 的比例计算 0.40 的基础分,若发现非目标联系人被错误分配给 Jordan Blake 则将该组件分数减半。Component 2 在 Airtable 的 Lead Handoff 表中寻找新增记录,按 Campaign、Lead Count、Assigned To、Handoff Date 四个子项分别加分。Component 3 检查 Slack #sales-handoff 频道的新消息是否提及 @jordan 并要求跟进线索。所有子项分数累加后,最终分数被钳制在 1.0 并四舍五入到 4 位小数。\",\"confidence\":1.0}" +} diff --git a/legacy/mktg_postmortem_001/_cua_gym_vm_bridge.sh b/legacy/mktg_postmortem_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/mktg_postmortem_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://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/mktg_postmortem_001/initial_setup.py b/legacy/mktg_postmortem_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd0110730ccc079f38cb6a9ac687cd4125811bc --- /dev/null +++ b/legacy/mktg_postmortem_001/initial_setup.py @@ -0,0 +1,315 @@ +""" +Initial Setup: Spring Nurture campaign post-mortem (Google Docs -> Airtable -> Slack) +Task ID: mktg_postmortem_001 +Domain: mock_websites (multi-mock: google_docs, airtable, slack) + +Initial state: + - Google Docs: realistic marketing docs, NO 'Spring Nurture - Post-Mortem' doc. + - Airtable: 'Campaigns' table; 'Spring Nurture' record Status = 'Active'. + - Slack: #marketing channel with prior chatter, NO learnings/doc-link message. +""" +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --- Mock URLs --- +GDOCS_URL = 'http://28.7.186.212:8162' +AIRTABLE_URL = 'http://28.7.186.212:8129' +SLACK_URL = 'http://28.7.186.212:8198' + +# --- Session id (shared across all three mocks) --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) +print(f'sid={sid}') + + +def avatar(name, bg): + return f'https://ui-avatars.com/api/?name={name.replace(" ", "+")}&background={bg}&color=fff' + + +# ========================================================================= +# 1. GOOGLE DOCS initial state +# ========================================================================= +gdocs_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"}, + {"id": "user-3", "name": "Bob Smith", "email": "bob@example.com", "avatar": "https://picsum.photos/100/100?random=user3"}, +] + +gdocs_state = { + "currentUser": gdocs_users[0], + "users": gdocs_users, + "documents": { + "doc-101": { + "id": "doc-101", + "title": "Q1 Marketing Plan", + "content": "

Q1 Marketing Plan

Objectives, channels, and budget for the first quarter.

Channels

Email nurture, paid social, and webinars.

", + "ownerId": "user-1", + "starred": True, + "created": "2026-01-08T09:00:00Z", + "updated": "2026-01-20T15:30:00Z", + "sharedWith": [{"userId": "user-2", "permission": "editor"}], + "linkSharing": {"enabled": True, "permission": "viewer"}, + }, + "doc-102": { + "id": "doc-102", + "title": "Email Nurture Playbook", + "content": "

Email Nurture Playbook

Best practices for multi-touch nurture sequences, cadence, and segmentation.

", + "ownerId": "user-2", + "starred": False, + "created": "2026-02-02T11:00:00Z", + "updated": "2026-02-14T10:05:00Z", + "sharedWith": [{"userId": "user-1", "permission": "editor"}], + "linkSharing": {"enabled": False, "permission": "viewer"}, + }, + "doc-103": { + "id": "doc-103", + "title": "Brand Voice Guidelines", + "content": "

Brand Voice Guidelines

Tone, vocabulary, and style standards for all marketing copy.

", + "ownerId": "user-1", + "starred": False, + "created": "2025-11-19T14:00:00Z", + "updated": "2026-01-03T09:45: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": "", + }, +} + +# ========================================================================= +# 2. AIRTABLE initial state — Campaigns table +# ========================================================================= +collaborators = [ + {"id": "user_1", "name": "John Doe", "email": "john.doe@example.com", "avatar": avatar("John Doe", "8B5CF6")}, + {"id": "user_2", "name": "Alice Chen", "email": "alice.chen@example.com", "avatar": avatar("Alice Chen", "EC4899")}, + {"id": "user_3", "name": "Bob Smith", "email": "bob.smith@example.com", "avatar": avatar("Bob Smith", "14B8A6")}, +] + +status_options = [ + {"id": "st_planned", "name": "Planned", "color": "bg-[#FFEAB6] text-[#8D6302]"}, + {"id": "st_active", "name": "Active", "color": "bg-[#D0E8FF] text-[#0B5394]"}, + {"id": "st_completed", "name": "Completed", "color": "bg-[#D1F7C4] text-[#2D7514]"}, + {"id": "st_paused", "name": "Paused", "color": "bg-[#FFDCE5] text-[#B31846]"}, +] +channel_options = [ + {"id": "ch_email", "name": "Email", "color": "bg-[#D0E8FF] text-[#0B5394]"}, + {"id": "ch_social", "name": "Social", "color": "bg-[#FFDCE5] text-[#B31846]"}, + {"id": "ch_paid", "name": "Paid Ads", "color": "bg-[#FFEAB6] text-[#8D6302]"}, + {"id": "ch_webinar", "name": "Webinar", "color": "bg-[#E8D5FF] text-[#6B21A8]"}, +] + +campaign_fields = [ + {"id": "fld_name", "name": "Campaign Name", "type": "text", "primary": True}, + {"id": "fld_status", "name": "Status", "type": "single_select", "options": status_options}, + {"id": "fld_channel", "name": "Channel", "type": "single_select", "options": channel_options}, + {"id": "fld_mqls", "name": "MQLs", "type": "number"}, + {"id": "fld_open", "name": "Open Rate", "type": "percent"}, + {"id": "fld_conv", "name": "Conversion", "type": "percent"}, + {"id": "fld_owner", "name": "Owner", "type": "user"}, + {"id": "fld_launch", "name": "Launch Date", "type": "date"}, +] + +campaign_records = [ + { + "id": "rec_spring", + "createdTime": "2026-03-01T09:00:00.000Z", + "fields": { + "fld_name": "Spring Nurture", + "fld_status": "Active", + "fld_channel": "Email", + "fld_mqls": 142, + "fld_open": 38.5, + "fld_conv": 4.2, + "fld_owner": collaborators[1], + "fld_launch": "2026-03-01", + }, + }, + { + "id": "rec_winter", + "createdTime": "2025-12-01T09:00:00.000Z", + "fields": { + "fld_name": "Winter Webinar Series", + "fld_status": "Completed", + "fld_channel": "Webinar", + "fld_mqls": 96, + "fld_open": 41.2, + "fld_conv": 3.1, + "fld_owner": collaborators[2], + "fld_launch": "2025-12-01", + }, + }, + { + "id": "rec_q2launch", + "createdTime": "2026-04-15T09:00:00.000Z", + "fields": { + "fld_name": "Q2 Product Launch", + "fld_status": "Active", + "fld_channel": "Paid Ads", + "fld_mqls": 210, + "fld_open": 0, + "fld_conv": 5.8, + "fld_owner": collaborators[0], + "fld_launch": "2026-04-15", + }, + }, + { + "id": "rec_referral", + "createdTime": "2026-05-20T09:00:00.000Z", + "fields": { + "fld_name": "Referral Boost", + "fld_status": "Planned", + "fld_channel": "Social", + "fld_mqls": 0, + "fld_open": 0, + "fld_conv": 0, + "fld_owner": collaborators[1], + "fld_launch": "2026-07-01", + }, + }, + { + "id": "rec_reactivation", + "createdTime": "2026-02-10T09:00:00.000Z", + "fields": { + "fld_name": "Customer Reactivation", + "fld_status": "Active", + "fld_channel": "Email", + "fld_mqls": 78, + "fld_open": 29.4, + "fld_conv": 2.6, + "fld_owner": collaborators[2], + "fld_launch": "2026-02-10", + }, + }, +] + +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_all", "name": "All Campaigns", "type": "grid", "filters": [], "sorts": [], "groupBy": [], "hiddenFieldIds": [], "fieldWidths": {}, "rowHeight": "short"}, + {"id": "view_status", "name": "By Status", "type": "kanban", "groupFieldId": "fld_status"}, + ], + "activeViewId": "view_all", + } + }, + "activeBaseId": "base_mktg", + "activeTableId": "tbl_campaigns", + "ui": { + "viewSidebarOpen": False, + "expandedRecordId": None, + "searchQuery": "", + "isSearching": False, + }, +} + +# ========================================================================= +# 3. SLACK initial state — #marketing channel +# ========================================================================= +def s_user(uid, full, disp, email, rnd): + return {"userId": uid, "fullName": full, "displayName": disp, "email": email, + "avatar": f"https://picsum.photos/200/200?random={rnd}", "status": "online", + "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"} + +slack_users = [ + s_user("user_1", "John Smith", "John", "john.smith@company.com", 1), + s_user("user_2", "Sarah Johnson", "Sarah", "sarah.johnson@company.com", 2), + s_user("user_3", "Marcus Lee", "Marcus", "marcus.lee@company.com", 3), + s_user("user_4", "Priya Nair", "Priya", "priya.nair@company.com", 4), +] + +slack_state = { + "currentUser": slack_users[0], + "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", "icon": ""}, + "users": slack_users, + "channels": [ + {"channelId": "general", "name": "general", "description": "Company-wide chat", "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": "marketing", "name": "marketing", "description": "Marketing team coordination", "topic": "Campaigns & growth", "isPrivate": False, "isStarred": True, "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_2", "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "random", "name": "random", "description": "Off-topic", "topic": "", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1", "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "general": [ + {"messageId": "msg_g1", "senderId": "user_2", "content": "Morning all!", "timestamp": "2026-06-29T09:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "marketing": [ + {"messageId": "msg_m1", "senderId": "user_2", "content": "Spring Nurture wrapped up this week — great numbers across the board.", "timestamp": "2026-06-29T14:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_m2", "senderId": "user_3", "content": "Nice! Who's writing the post-mortem?", "timestamp": "2026-06-29T14:05:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + {"messageId": "msg_m3", "senderId": "user_1", "content": "I'll take it — will share the doc here once it's done.", "timestamp": "2026-06-29T14:07: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": [], +} + +# ========================================================================= +# Inject all three mocks with the same sid +# ========================================================================= +injections = [ + ("google_docs", GDOCS_URL, gdocs_state), + ("airtable", AIRTABLE_URL, airtable_state), + ("slack", SLACK_URL, slack_state), +] + +for name, url, state in injections: + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=15).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 three mocks injected successfully.') + + +# ========================================================================= +# Launch browser (GUI-ready). Primary mock = Google Docs (first step). +# ========================================================================= +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 "{GDOCS_URL}/?sid={sid}"', delay_sec=2.0) +print(f'GUI_READY: launched browser at {GDOCS_URL}/?sid={sid}') +launch_gui(f'google-chrome "{AIRTABLE_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched browser at {AIRTABLE_URL}/?sid={sid}') +launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.5) +print(f'GUI_READY: launched browser at {SLACK_URL}/?sid={sid}') diff --git a/legacy/mktg_postmortem_001/reward.py b/legacy/mktg_postmortem_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..79e1213badcaeac6dc44289eef5caa485f8b9196 --- /dev/null +++ b/legacy/mktg_postmortem_001/reward.py @@ -0,0 +1,259 @@ +""" +Reward Script: Spring Nurture post-mortem — Google Docs -> Airtable -> Slack chain +Task ID: mktg_postmortem_001 +Domain: mock_websites (multi-mock: google-docs, airtable, slack) + +Scoring (all DETERMINISTIC HTTP-state checks, total 1.0): + Component 1 — Google Doc post-mortem (0.40) + 1a: new doc titled "Spring Nurture — Post-Mortem" exists (0.15) + 1b: doc content contains all 3 metrics (142, 38.5, 4.2) (0.15) + 1c: doc content has the three required sections (0.10) + Component 2 — Airtable campaign status (0.30) + 2a: 'Spring Nurture' record Status == 'Completed' (0.20) + 2b: AND no other campaign's Status changed from initial (0.10) + Component 3 — Slack #marketing post (0.30) + 3a: new #marketing message has a numbered list (1./2./3.) (0.15) + 3b: AND that message links to the post-mortem doc (google-docs) (0.15) + +Every component verifies a task-INTRODUCED change, so reward(initial)==0.0 +and reward(golden)==1.0. No LLM judge is used (deterministic checks only). +""" +import json +import re +import sys + +import requests + +MOCKS = { + 'google-docs': 'http://28.7.186.212:8162', + 'airtable': 'http://28.7.186.212:8129', + 'slack': 'http://28.7.186.212:8198', +} + + +def _strip_html(html): + """Crude HTML -> text for content keyword checks.""" + if not isinstance(html, str): + return '' + text = re.sub(r'<[^>]+>', ' ', html) + # decode the few entities the editor emits + text = text.replace('—', '-').replace('–', '-').replace('&', '&') + return re.sub(r'\s+', ' ', text).strip() + + +def _norm_title(t): + if not isinstance(t, str): + return '' + t = t.lower() + # normalize all dash variants to a plain space so "post-mortem" / "post — mortem" match + t = re.sub(r'[‐-―\-]', ' ', t) + return re.sub(r'\s+', ' ', t).strip() + + +# --- 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=40) + 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) + + +def verify_task(): + total_score = 0.0 + + gd = states['google-docs'] + at = states['airtable'] + sl = states['slack'] + + gd_cur = gd.get('current_state') or {} + gd_init = gd.get('initial_state') or {} + at_cur = at.get('current_state') or {} + at_init = at.get('initial_state') or {} + sl_cur = sl.get('current_state') or {} + sl_init = sl.get('initial_state') or {} + + # ============================================================ + # Component 1 — Google Doc post-mortem (0.40) + # ============================================================ + post_doc = None + # 1a: locate a doc whose title is the Spring Nurture post-mortem (0.15) + try: + cur_docs = gd_cur.get('documents') or {} + init_doc_ids = set((gd_init.get('documents') or {}).keys()) + candidates = [] + for did, doc in cur_docs.items(): + nt = _norm_title(doc.get('title')) + if 'spring nurture' in nt and 'post' in nt and 'mortem' in nt: + candidates.append((did, doc)) + # Prefer a doc that did NOT exist in initial_state (task-introduced) + new_cands = [c for c in candidates if c[0] not in init_doc_ids] + chosen = new_cands or candidates + if chosen: + post_doc = chosen[0][1] + print(f"PASS: 1a — post-mortem doc found (title={post_doc.get('title')!r}) (0.15 pts)") + total_score += 0.15 + else: + print("FAIL: 1a — no document titled 'Spring Nurture — Post-Mortem' found") + except Exception as e: + print(f'ERROR: 1a — {e}') + + # 1b: doc content contains all 3 metrics (0.15) + try: + if post_doc is not None: + text = _strip_html(post_doc.get('content')) + # normalize: drop spaces around % and commas in numbers + norm = text.replace(' %', '%').replace(',', '') + have_mqls = '142' in norm + have_open = bool(re.search(r'38\.5\s*%?', norm)) + have_conv = bool(re.search(r'4\.2\s*%?', norm)) + if have_mqls and have_open and have_conv: + print('PASS: 1b — content has all 3 metrics (142 / 38.5% / 4.2%) (0.15 pts)') + total_score += 0.15 + else: + print(f'FAIL: 1b — metrics present? 142={have_mqls} 38.5={have_open} 4.2={have_conv}') + else: + print('FAIL: 1b — no post-mortem doc to inspect for metrics') + except Exception as e: + print(f'ERROR: 1b — {e}') + + # 1c: doc content has the three required sections (0.10) + try: + if post_doc is not None: + low = _strip_html(post_doc.get('content')).lower() + has_worked = 'what worked' in low or ('worked' in low and 'what' in low) + has_didnt = ("didn't" in low or 'did not' in low or "didnt" in low) + has_results = 'result' in low + if has_worked and has_didnt and has_results: + print('PASS: 1c — sections present (what worked / what didn\'t / results) (0.10 pts)') + total_score += 0.10 + else: + print(f'FAIL: 1c — sections? worked={has_worked} didnt={has_didnt} results={has_results}') + else: + print('FAIL: 1c — no post-mortem doc to inspect for sections') + except Exception as e: + print(f'ERROR: 1c — {e}') + + # ============================================================ + # Component 2 — Airtable Spring Nurture status (0.30) + # ============================================================ + def campaign_status_map(state): + """Return {campaign_name: status} for the Campaigns table.""" + out = {} + tables = state.get('tables') or {} + for t in tables.values(): + # identify by field named 'Campaign Name'/'Name' primary + 'Status' + fields = {f.get('id'): f.get('name') for f in t.get('fields', [])} + name_fid = next((fid for fid, n in fields.items() + if n in ('Campaign Name', 'Name')), None) + status_fid = next((fid for fid, n in fields.items() if n == 'Status'), None) + if name_fid is None or status_fid is None: + continue + for r in t.get('records', []): + fl = r.get('fields', {}) + nm = fl.get(name_fid) + if nm is not None: + out[nm] = fl.get(status_fid) + return out + + spring_completed = False + try: + cur_map = campaign_status_map(at_cur) + spring_status = cur_map.get('Spring Nurture') + if isinstance(spring_status, str) and spring_status.strip().lower() == 'completed': + spring_completed = True + print("PASS: 2a — 'Spring Nurture' Status == 'Completed' (0.20 pts)") + total_score += 0.20 + else: + print(f"FAIL: 2a — 'Spring Nurture' Status is {spring_status!r}, expected 'Completed'") + except Exception as e: + print(f'ERROR: 2a — {e}') + + # 2b: only Spring Nurture changed (gated on 2a so it cannot pass on initial) + try: + if spring_completed: + init_map = campaign_status_map(at_init) + cur_map = campaign_status_map(at_cur) + others_changed = [n for n in init_map + if n != 'Spring Nurture' and init_map.get(n) != cur_map.get(n)] + if not others_changed: + print('PASS: 2b — no other campaign status changed (0.10 pts)') + total_score += 0.10 + else: + print(f'FAIL: 2b — other campaigns changed: {others_changed}') + else: + print('FAIL: 2b — skipped (Spring Nurture not Completed)') + except Exception as e: + print(f'ERROR: 2b — {e}') + + # ============================================================ + # Component 3 — Slack #marketing post (0.30) + # ============================================================ + new_msgs = [] + try: + init_msgs = (sl_init.get('messages') or {}).get('marketing') or [] + cur_msgs = (sl_cur.get('messages') or {}).get('marketing') or [] + if len(cur_msgs) > len(init_msgs): + new_msgs = cur_msgs[len(init_msgs):] + except Exception as e: + print(f'ERROR: collecting new #marketing messages — {e}') + + # 3a: a new #marketing message contains a numbered list of 3 items (0.15) + numbered_msg = None + try: + for m in new_msgs: + content = m.get('content') or '' + markers = re.findall(r'(?:^|\n)\s*([1-9])[.)]\s', content) + if {'1', '2', '3'}.issubset(set(markers)): + numbered_msg = m + break + if numbered_msg is not None: + print('PASS: 3a — new #marketing message has a numbered list (1./2./3.) (0.15 pts)') + total_score += 0.15 + else: + print(f'FAIL: 3a — no new #marketing message with a 1./2./3. numbered list ({len(new_msgs)} new msgs)') + except Exception as e: + print(f'ERROR: 3a — {e}') + + # 3b: that message links to the post-mortem doc (gated on 3a) (0.15) + try: + if numbered_msg is not None: + content = numbered_msg.get('content') or '' + # accept the google-docs link domain, or a direct link carrying the doc id + links = ' '.join(a.get('url', '') for a in (numbered_msg.get('attachments') or [])) + blob = content + ' ' + links + doc_id = (post_doc or {}).get('id') if post_doc else None + has_domain = '28.7.186.212:8162' in blob or 'google-docs' in blob + has_docid = bool(doc_id) and doc_id in blob + if has_domain or has_docid: + print('PASS: 3b — message links to the post-mortem doc (0.15 pts)') + total_score += 0.15 + else: + print('FAIL: 3b — numbered-list message has no link to the post-mortem doc') + else: + print('FAIL: 3b — skipped (no numbered-list message)') + except Exception as e: + print(f'ERROR: 3b — {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/legacy/mktg_postmortem_001/reward_label.json b/legacy/mktg_postmortem_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..43c19c4b0c202dad95040e4e28fb3ba017a2e158 --- /dev/null +++ b/legacy/mktg_postmortem_001/reward_label.json @@ -0,0 +1,83 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/mktg_postmortem_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:27:49", + "label": { + "task_id": "mktg_postmortem_001", + "domain": "mock_websites", + "summary": "验证用户在 Google Docs 创建 Spring Nurture 事后分析文档、在 Airtable 将对应活动状态改为 Completed、并在 Slack #marketing 频道发布带编号列表和文档链接的消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google-docs mock (http://28.7.186.212:8162)", + "airtable mock (http://28.7.186.212:8129)", + "slack mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "Component 1a", + "weight": 0.15, + "description": "Google Doc 中存在标题为 Spring Nurture Post-Mortem 的新文档", + "check_logic": "遍历 google-docs current_state.documents,使用 _norm_title 将标题小写化并把各类连字符替换为空格,检查是否同时包含 'spring nurture'、'post'、'mortem';优先选择不在 initial_state.documents 中的新文档", + "pass_condition": "找到至少一个匹配标题的文档,且优先为任务新建文档" + }, + { + "name": "Component 1b", + "weight": 0.15, + "description": "事后分析文档内容包含三个指定指标", + "check_logic": "对 post_doc.content 使用 _strip_html 提取文本,去掉空格+%和逗号后,检查是否包含 '142'、正则匹配 '38\\.5\\s*%?'、正则匹配 '4\\.2\\s*%?'", + "pass_condition": "文本中同时出现 142、38.5(可选%)、4.2(可选%)" + }, + { + "name": "Component 1c", + "weight": 0.1, + "description": "事后分析文档包含三个必要章节", + "check_logic": "将文档文本转小写后检查:has_worked = 'what worked' 或 ('worked' 且 'what');has_didnt = \"didn't\" 或 'did not' 或 'didnt';has_results = 'result' 在文本中", + "pass_condition": "三个章节关键词同时存在" + }, + { + "name": "Component 2a", + "weight": 0.2, + "description": "Airtable 中 Spring Nurture 活动状态为 Completed", + "check_logic": "遍历 airtable current_state.tables,找到字段名为 'Campaign Name' 或 'Name' 以及 'Status' 的表,提取所有记录为 {campaign_name: status} 映射,检查 'Spring Nurture' 对应的 status 去除空白后小写等于 'completed'", + "pass_condition": "Spring Nurture 的 Status 严格等于 'Completed'(忽略大小写和空白)" + }, + { + "name": "Component 2b", + "weight": 0.1, + "description": "Airtable 中其他活动状态未被修改", + "check_logic": "仅在 2a 通过(spring_completed=True)时执行;对比 initial_state 和 current_state 中所有 campaign 的状态映射,检查除 'Spring Nurture' 外其他名称的状态是否保持不变", + "pass_condition": "除 Spring Nurture 外,没有任何其他 campaign 的状态与初始状态不同" + }, + { + "name": "Component 3a", + "weight": 0.15, + "description": "Slack #marketing 频道有新消息且包含三项编号列表", + "check_logic": "比较 slack initial_state 和 current_state 中 messages.marketing 列表长度,取出新增消息;遍历新消息内容,用正则 r'(?:^|\\n)\\s*([1-9])[.)]\\s' 查找编号标记,检查是否同时包含 '1'、'2'、'3'", + "pass_condition": "存在至少一条新增消息,其内容包含 1./2./3.(或 1)/2)/3) 等)编号列表" + }, + { + "name": "Component 3b", + "weight": 0.15, + "description": "编号列表消息链接到事后分析文档", + "check_logic": "仅在 3a 通过(numbered_msg 不为 None)时执行;合并消息 content 和 attachments 中的 url 为 blob,检查是否包含 '28.7.186.212:8162' 或 'google-docs',或包含 post_doc.id", + "pass_condition": "消息文本或附件 URL 中包含 google-docs 域名/IP,或包含具体文档 ID" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接返回 0.0 退出", + "从任一 mock 服务(google-docs/airtable/slack)拉取状态失败:打印 CRITICAL 并直接返回 0.0 退出", + "1a 失败导致 post_doc 为 None,进而使 1b 和 1c 无法通过", + "2a 失败(Spring Nurture 状态不是 Completed)导致 2b 被跳过", + "3a 失败(无编号列表消息)导致 3b 被跳过", + "各子组件检查异常会被捕获为 ERROR,该子组件不得分但不影响其他组件" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后顺序从 google-docs、airtable、slack 三个 mock 服务拉取 current_state 和 initial_state。接着按顺序检查:1) Google Docs 中是否新建了标题包含 Spring Nurture Post-Mortem 的文档,且内容包含三个指标(142、38.5%、4.2%)和三个章节(what worked / what didn't / results);2) Airtable 中 Spring Nurture 活动状态是否变为 Completed,且未改动其他活动状态;3) Slack #marketing 频道是否有新增带 1./2./3. 编号列表的消息,并且该消息链接到对应的事后分析文档。每个子组件有独立权重,通过则累加对应分数,失败或异常则跳过。最终总分经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: mktg_postmortem_001(从 docstring 中明确提取)\n - Domain: mock_websites (multi-mock: google-docs, airtable, slack)(从 docstring 中提取)\n\n2. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - `http://28.7.186.212:8162` (google-docs mock)\n - `http://28.7.186.212:8129` (airtable mock)\n - `http://28.7.186.212:8198` (slack mock)\n\n3. **评分组件**:\n\n **Component 1 — Google Doc post-mortem (0.40)**:\n - 1a (0.15): 查找标题包含 \"spring nurture\" 和 \"post\" 和 \"mortem\" 的文档,优先选择新创建的(不在 initial_state 中)。使用 `_norm_title` 规范化标题(小写、破折号变空格)。\n - 1b (0.15): 文档内容(HTML 转文本后)包含三个指标:142、38.5(可能后跟 %)、4.2(可能后跟 %)。会规范化文本(去掉 % 前的空格和逗号)。\n - 1c (0.10): 文档内容包含三个部分:\"what worked\"(或 \"worked\" 和 \"what\")、\"didn't\"/\"did not\"/\"didnt\"、\"result\"。\n\n **Component 2 — Airtable campaign status (0.30)**:\n - 2a (0.20): 在 Airtable 的 Campaigns 表中,\"Spring Nurture\" 记录的 Status 字段为 \"Completed\"(不区分大小写,去除空白)。\n - 2b (0.10): 其他 campaign 的状态没有从初始状态改变。只有当 2a 通过时才会检查。\n\n **Component 3 — Slack #marketing post (0.30)**:\n - 3a (0.15): 在 #marketing 频道中有新消息(通过比较 cur_msgs 和 init_msgs 的长度),且消息内容包含编号列表(1./2./3. 或 1)/2)/3) 等)。\n - 3b (0.15): 该编号列表消息链接到 post-mortem 文档。检查消息内容或附件 URL 中是否包含 google-docs 域名('28.7.186.212:8162' 或 'google-docs')或具体的 doc_id。\n\n4. **分数聚合**:\n - 各组件分数相加,最后 `round(min(total_score, 1.0), 4)`。\n\n5. **失败模式**:\n - 读取 `/tmp/task_web_sid` 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 从任一 mock 服务获取状态失败:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 各组件检查失败会打印 FAIL 但不退出,只是不加分\n - 2b 依赖 2a(spring_completed 为 True)\n - 3b 依赖 3a(numbered_msg 不为 None)\n - 1b 和 1c 依赖 post_doc 不为 None\n\n6. **is_placeholder**:\n - false,因为脚本有详细的确定性检查逻辑。\n\n7. **confidence**:\n - 1.0,因为代码逻辑清晰完整。\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"mktg_postmortem_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证用户在 Google Docs 创建 Spring Nurture 事后分析文档、在 Airtable 将对应活动状态改为 Completed、并在 Slack #marketing 频道发布带编号列表和文档链接的消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google-docs mock (http://28.7.186.212:8162)\", \"airtable mock (http://28.7.186.212:8129)\", \"slack mock (http://28.7.186.212:8198)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1a\",\n \"weight\": 0.15,\n \"description\": \"Google Doc 中存在标题为 Spring Nurture Post-Mortem 的新文档\",\n \"check_logic\": \"遍历 google-docs current_state.documents,使用 _norm_title 将标题小写化并把各类连字符替换为空格,检查是否同时包含 'spring nurture'、'post'、'mortem';优先选择不在 initial_state.documents 中的新文档\",\n \"pass_condition\": \"找到至少一个匹配标题的文档,且优先为任务新建文档\"\n },\n {\n \"name\": \"Component 1b\",\n \"weight\": 0.15,\n \"description\": \"事后分析文档内容包含三个指定指标\",\n \"check_logic\": \"对 post_doc.content 使用 _strip_html 提取文本,去掉空格+%和逗号后,检查是否包含 '142'、正则匹配 '38\\\\.5\\\\s*%?'、正则匹配 '4\\\\.2\\\\s*%?'\",\n \"pass_condition\": \"文本中同时出现 142、38.5(可选%)、4.2(可选%)\"\n },\n {\n \"name\": \"Component 1c\",\n \"weight\": 0.10,\n \"description\": \"事后分析文档包含三个必要章节\",\n \"check_logic\": \"将文档文本转小写后检查:has_worked = 'what worked' 或 ('worked' 且 'what');has_didnt = \\\"didn't\\\" 或 'did not' 或 'didnt';has_results = 'result' 在文本中\",\n \"pass_condition\": \"三个章节关键词同时存在\"\n },\n {\n \"name\": \"Component 2a\",\n \"weight\": 0.20,\n \"description\": \"Airtable 中 Spring Nurture 活动状态为 Completed\",\n \"check_logic\": \"遍历 airtable current_state.tables,找到字段名为 'Campaign Name' 或 'Name' 以及 'Status' 的表,提取所有记录为 {campaign_name: status} 映射,检查 'Spring Nurture' 对应的 status 去除空白后小写等于 'completed'\",\n \"pass_condition\": \"Spring Nurture 的 Status 严格等于 'Completed'(忽略大小写和空白)\"\n },\n {\n \"name\": \"Component 2b\",\n \"weight\": 0.10,\n \"description\": \"Airtable 中其他活动状态未被修改\",\n \"check_logic\": \"仅在 2a 通过(spring_completed=True)时执行;对比 initial_state 和 current_state 中所有 campaign 的状态映射,检查除 'Spring Nurture' 外其他名称的状态是否保持不变\",\n \"pass_condition\": \"除 Spring Nurture 外,没有任何其他 campaign 的状态与初始状态不同\"\n },\n {\n \"name\": \"Component 3a\",\n \"weight\": 0.15,\n \"description\": \"Slack #marketing 频道有新消息且包含三项编号列表\",\n \"check_logic\": \"比较 slack initial_state 和 current_state 中 messages.marketing 列表长度,取出新增消息;遍历新消息内容,用正则 r'(?:^|\\\\n)\\\\s*([1-9])[.)]\\\\s' 查找编号标记,检查是否同时包含 '1'、'2'、'3'\",\n \"pass_condition\": \"存在至少一条新增消息,其内容包含 1./2./3.(或 1)/2)/3) 等)编号列表\"\n },\n {\n \"name\": \"Component 3b\",\n \"weight\": 0.15,\n \"description\": \"编号列表消息链接到事后分析文档\",\n \"check_logic\": \"仅在 3a 通过(numbered_msg 不为 None)时执行;合并消息 content 和 attachments 中的 url 为 blob,检查是否包含 '28.7.186.212:8162' 或 'google-docs',或包含 post_doc.id\",\n \"pass_condition\": \"消息文本或附件 URL 中包含 google-docs 域名/IP,或包含具体文档 ID\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接返回 0.0 退出\",\n \"从任一 mock 服务(google-docs/airtable/slack)拉取状态失败:打印 CRITICAL 并直接返回 0.0 退出\",\n \"1a 失败导致 post_doc 为 None,进而使 1b 和 1c 无法通过\",\n \"2a 失败(Spring Nurture 状态不是 Completed)导致 2b 被跳过\",\n \"3a 失败(无编号列表消息)导致 3b 被跳过\",\n \"各子组件检查异常会被捕获为 ERROR,该子组件不得分但不影响其他组件\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后并行(顺序)从 google-docs、airtable、slack 三个 mock 服务拉取 current_state 和 initial_state。接着按顺序检查:1) Google Docs 中是否新建了标题包含 Spring Nurture Post-Mortem 的文档,且内容包含三个指标(142、38.5%、4.2%)和三个章节(what worked / what didn't / results);2) Airtable 中 Spring Nurture 活动状态是否变为 Completed,且未改动其他活动状态;3) Slack #marketing 频道是否有新增带 1./2./3. 编号列表的消息,并且该消息链接到对应的事后分析文档。每个子组件有独立权重,通过则累加对应分数,失败或异常则跳过。最终总分经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查字段要求:\n- task_id: \"mktg_postmortem_001\" ✓\n- domain: \"mock_websites\" ✓(docstring 中明确写了 Domain: mock_websites)\n- summary: 中文一句话 ✓\n- is_placeholder: false ✓\n- data_sources: 数组 ✓\n- scoring_components: 数组,包含 name, weight, description, check_logic, pass_condition ✓\n- total_max_score: 1.0 ✓\n- score_aggregation: 中文说明 ✓\n- failure_modes: 数组 ✓\n- scoring_logic_explanation: 详细中文解释 ✓\n- confidence: 1.0 ✓\n\n确保没有 Markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n再检查一下 domain 的提取。docstring 中写的是 \"Domain: mock_websites (multi-mock: google-docs, airtable, slack)\",所以 domain 应该是 \"mock_websites\"。\n\ndata_sources 的写法:脚本中是从 MOCKS 字典获取,我可以写服务名和 URL。\n\n所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。我在 check_logic 和 pass_condition 中保留了代码标识符如 `spring_completed`、`numbered_msg` 等,这是符合要求的。\n\n确认 weight 值:\n- 1a: 0.15\n- 1b: 0.15\n- 1c: 0.10\n- 2a: 0.20\n- 2b: 0.10\n- 3a: 0.15\n- 3b: 0.15\n总和 = 0.15+0.15+0.10+0.20+0.10+0.15+0.15 = 1.0。正确。\n\n确认 failure_modes 包含提前退出路径:\n- sid 读取失败:sys.exit(0)\n- mock 拉取失败:sys.exit(0)\n- 依赖跳过:1a 失败导致 1b/1c 失败;2a 失败导致 2b 跳过;3a 失败导致 3b 跳过。\n\n确认 score_aggregation:代码中是 `total_score += ...` 累加,最后 `round(min(total_score, 1.0), 4)`。\n\n一切看起来正确。 {\n \"task_id\": \"mktg_postmortem_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证用户在 Google Docs 创建 Spring Nurture 事后分析文档、在 Airtable 将对应活动状态改为 Completed、并在 Slack #marketing 频道发布带编号列表和文档链接的消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google-docs mock (http://28.7.186.212:8162)\", \"airtable mock (http://28.7.186.212:8129)\", \"slack mock (http://28.7.186.212:8198)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1a\",\n \"weight\": 0.15,\n \"description\": \"Google Doc 中存在标题为 Spring Nurture Post-Mortem 的新文档\",\n \"check_logic\": \"遍历 google-docs current_state.documents,使用 _norm_title 将标题小写化并把各类连字符替换为空格,检查是否同时包含 'spring nurture'、'post'、'mortem';优先选择不在 initial_state.documents 中的新文档\",\n \"pass_condition\": \"找到至少一个匹配标题的文档,且优先为任务新建文档\"\n },\n {\n \"name\": \"Component 1b\",\n \"weight\": 0.15,\n \"description\": \"事后分析文档内容包含三个指定指标\",\n \"check_logic\": \"对 post_doc.content 使用 _strip_html 提取文本,去掉空格+%和逗号后,检查是否包含 '142'、正则匹配 '38\\\\.5\\\\s*%?'、正则匹配 '4\\\\.2\\\\s*%?'\",\n \"pass_condition\": \"文本中同时出现 142、38.5(可选%)、4.2(可选%)\"\n },\n {\n \"name\": \"Component 1c\",\n \"weight\": 0.10,\n \"description\": \"事后分析文档包含三个必要章节\",\n \"check_logic\": \"将文档文本转小写后检查:has_worked = 'what worked' 或 ('worked' 且 'what');has_didnt = \\\"didn't\\\" 或 'did not' 或 'didnt';has_results = 'result' 在文本中\",\n \"pass_condition\": \"三个章节关键词同时存在\"\n },\n {\n \"name\": \"Component 2a\",\n \"weight\": 0.20,\n \"description\": \"Airtable 中 Spring Nurture 活动状态为 Completed\",\n \"check_logic\": \"遍历 airtable current_state.tables,找到字段名为 'Campaign Name' 或 'Name' 以及 'Status' 的表,提取所有记录为 {campaign_name: status} 映射,检查 'Spring Nurture' 对应的 status 去除空白后小写等于 'completed'\",\n \"pass_condition\": \"Spring Nurture 的 Status 严格等于 'Completed'(忽略大小写和空白)\"\n },\n {\n \"name\": \"Component 2b\",\n \"weight\": 0.10,\n \"description\": \"Airtable 中其他活动状态未被修改\",\n \"check_logic\": \"仅在 2a 通过(spring_completed=True)时执行;对比 initial_state 和 current_state 中所有 campaign 的状态映射,检查除 'Spring Nurture' 外其他名称的状态是否保持不变\",\n \"pass_condition\": \"除 Spring Nurture 外,没有任何其他 campaign 的状态与初始状态不同\"\n },\n {\n \"name\": \"Component 3a\",\n \"weight\": 0.15,\n \"description\": \"Slack #marketing 频道有新消息且包含三项编号列表\",\n \"check_logic\": \"比较 slack initial_state 和 current_state 中 messages.marketing 列表长度,取出新增消息;遍历新消息内容,用正则 r'(?:^|\\\\n)\\\\s*([1-9])[.)]\\\\s' 查找编号标记,检查是否同时包含 '1'、'2'、'3'\",\n \"pass_condition\": \"存在至少一条新增消息,其内容包含 1./2./3.(或 1)/2)/3) 等)编号列表\"\n },\n {\n \"name\": \"Component 3b\",\n \"weight\": 0.15,\n \"description\": \"编号列表消息链接到事后分析文档\",\n \"check_logic\": \"仅在 3a 通过(numbered_msg 不为 None)时执行;合并消息 content 和 attachments 中的 url 为 blob,检查是否包含 '28.7.186.212:8162' 或 'google-docs',或包含 post_doc.id\",\n \"pass_condition\": \"消息文本或附件 URL 中包含 google-docs 域名/IP,或包含具体文档 ID\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并直接返回 0.0 退出\",\n \"从任一 mock 服务(google-docs/airtable/slack)拉取状态失败:打印 CRITICAL 并直接返回 0.0 退出\",\n \"1a 失败导致 post_doc 为 None,进而使 1b 和 1c 无法通过\",\n \"2a 失败(Spring Nurture 状态不是 Completed)导致 2b 被跳过\",\n \"3a 失败(无编号列表消息)导致 3b 被跳过\",\n \"各子组件检查异常会被捕获为 ERROR,该子组件不得分但不影响其他组件\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后顺序从 google-docs、airtable、slack 三个 mock 服务拉取 current_state 和 initial_state。接着按顺序检查:1) Google Docs 中是否新建了标题包含 Spring Nurture Post-Mortem 的文档,且内容包含三个指标(142、38.5%、4.2%)和三个章节(what worked / what didn't / results);2) Airtable 中 Spring Nurture 活动状态是否变为 Completed,且未改动其他活动状态;3) Slack #marketing 频道是否有新增带 1./2./3. 编号列表的消息,并且该消息链接到对应的事后分析文档。每个子组件有独立权重,通过则累加对应分数,失败或异常则跳过。最终总分经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}" +} diff --git a/legacy/prof15_calibration_cycle_003/_cua_gym_vm_bridge.sh b/legacy/prof15_calibration_cycle_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/prof15_calibration_cycle_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/prof15_calibration_cycle_003/initial_setup.py b/legacy/prof15_calibration_cycle_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9bf2839cb809242e253767c465c680de5df470e7 --- /dev/null +++ b/legacy/prof15_calibration_cycle_003/initial_setup.py @@ -0,0 +1,352 @@ +""" +Initial Setup: FY2026 Cycle 1 HR Performance Calibration pipeline +Task ID: prof15_calibration_cycle_003 +Domain: mock_websites (multi-app: Lattice, Workday, Google Sheets, Google Docs, + Google Calendar, Slack, Gmail) + +This script runs on initial_env. It brings all 7 mock apps to the documented +INITIAL state (the starting point BEFORE the agent does anything): + - Lattice: 4 cohort members with their FY2026 review statuses (read-only source) + - Workday: 4 cohort members with their managers (read-only source) + - Google Sheets 'Cycle 1': Maya Chen (row 3) + Liam Patterson (row 13) populated; + Sofia Reyes and Tom Becker rows MISSING + - Google Docs: no 'Cycle 1 Calibration Agenda' doc + - Google Calendar: no calibration event + - Slack: #people-partners channel present and readable, no task message yet + - Gmail: HRBP account ready, no sent message yet +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --------------------------------------------------------------------------- +# Mock endpoints (fixed IP:port per task_config.json) +# --------------------------------------------------------------------------- +MOCKS = { + "lattice": "http://28.7.186.212:8175", + "workday": "http://28.7.186.212:8212", + "sheets": "http://28.7.186.212:8165", + "docs": "http://28.7.186.212:8162", + "calendar": "http://28.7.186.212:8161", + "slack": "http://28.7.186.212:8198", + "gmail": "http://28.7.186.212:8158", +} + +# Cohort definition (shared by all mocks) +COHORT = [ + # name, dept, level, lattice_status, goals_met, manager + ("Maya Chen", "Engineering", "IC3", "Submitted", "4 of 5", "Daniel Okafor"), + ("Liam Patterson", "Sales", "L4", "Needs Calibration", "3 of 6", "Priya Nair"), + ("Sofia Reyes", "Engineering", "L5", "Submitted", "6 of 6", "Daniel Okafor"), + ("Tom Becker", "Sales", "L3", "Submitted", "5 of 5", "Priya Nair"), +] + +# User IDs for the cohort +UID = { + "Maya Chen": "u_chen", + "Liam Patterson": "u_patterson", + "Sofia Reyes": "u_reyes", + "Tom Becker": "u_becker", +} +MGR_OKAFOR = "emp_okaf" # Daniel Okafor +MGR_NAIR = "emp_nair" # Priya Nair + + +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) + + +# --------------------------------------------------------------------------- +# State builders +# --------------------------------------------------------------------------- +def build_lattice_state(): + users = [{ + "id": UID[name], "firstName": name.split()[0], "lastName": name.split()[1], + "email": f"{name.split()[0].lower()}.{name.split()[1].lower()}@northwindcloud.com", + "avatar": None, "title": f"{level} {dept}", "department": dept, + "team": "Revenue & Engineering", "location": "Remote", "startDate": "2023-01-15", + "managerId": MGR_OKAFOR if mgr == "Daniel Okafor" else MGR_NAIR, + "directReportIds": [], "role": "ic", "status": "active", + "birthday": "1990-01-01", "workAnniversary": "2023-01-15", + } for (name, dept, level, status, goals, mgr) in COHORT] + + reviews = [{ + "id": f"rev_{UID[name][2:]}", + "cycleId": "rc_fy2026_c1", + "revieweeId": UID[name], + "status": status, + "goalsMet": goals, + "nominatedPeerIds": [], + "selfReviewSubmitted": status == "Submitted", + "reviews": [], + } for (name, dept, level, status, goals, mgr) in COHORT] + + return { + "currentUser": { + "id": "u_hrbp", "firstName": "HR", "lastName": "Partner", + "email": "hrbp@northwindcloud.com", "avatar": None, + "title": "HR Business Partner", "department": "People", "team": "People Team", + "location": "Remote", "startDate": "2022-05-01", "managerId": None, + "directReportIds": [], "role": "manager", "status": "active", + "birthday": "1988-03-20", "workAnniversary": "2022-05-01", + }, + "users": [{ + "id": "u_hrbp", "firstName": "HR", "lastName": "Partner", + "email": "hrbp@northwindcloud.com", "avatar": None, + "title": "HR Business Partner", "department": "People", "team": "People Team", + "location": "Remote", "startDate": "2022-05-01", "managerId": None, + "directReportIds": [], "role": "manager", "status": "active", + "birthday": "1988-03-20", "workAnniversary": "2022-05-01", + }] + users, + "goals": [], "feedback": [], "oneOnOnes": [], "meetings": [], + "reviewCycles": [{ + "id": "rc_fy2026_c1", "name": "FY2026 Cycle 1 Performance Review", + "status": "active", "startDate": "2026-06-15", "endDate": "2026-07-15", + "steps": ["nominate_peers", "manage_team", "share_results"], + "currentStep": "manage_team", + "revieweeIds": [UID[n] for (n, *_ ) in COHORT], + "nominationsSubmitted": True, + }], + "reviews": reviews, + "updates": [], "growthAreas": [], "careerTracks": [], "surveys": [], + "surveyResults": {}, "tasks": [], "celebrations": [], "company": {}, + "careerVision": {}, "compensation": {}, + } + + +def build_workday_state(): + employees = [{ + "id": UID[name], "name": name, + "email": f"{name.split()[0].lower()}.{name.split()[1].lower()}@northwindcloud.com", + "phone": "+1 (415) 555-0100", "role": "Employee", "department": dept, + "departmentId": "dept_eng" if dept == "Engineering" else "dept_sales", + "avatar": "", "managerId": MGR_OKAFOR if mgr == "Daniel Okafor" else MGR_NAIR, + "title": f"{level} {dept}", "location": "Remote", "joinDate": "2023-01-15", + "employeeType": "Full-Time", "birthday": "1990-01-01", "workAnniversary": "2023-01-15", + } for (name, dept, level, status, goals, mgr) in COHORT] + + # Managers + managers = [ + {"id": MGR_OKAFOR, "name": "Daniel Okafor", "email": "daniel.okafor@northwindcloud.com", + "phone": "+1 (415) 555-0200", "role": "Manager", "department": "Engineering", + "departmentId": "dept_eng", "avatar": "", "managerId": None, "title": "Engineering Manager", + "location": "Remote", "joinDate": "2020-03-01", "employeeType": "Full-Time", + "birthday": "1985-06-10", "workAnniversary": "2020-03-01"}, + {"id": MGR_NAIR, "name": "Priya Nair", "email": "priya.nair@northwindcloud.com", + "phone": "+1 (415) 555-0201", "role": "Manager", "department": "Sales", + "departmentId": "dept_sales", "avatar": "", "managerId": None, "title": "Sales Manager", + "location": "Remote", "joinDate": "2020-09-01", "employeeType": "Full-Time", + "birthday": "1986-09-15", "workAnniversary": "2020-09-01"}, + ] + + return { + "currentUser": { + "id": "emp_hrbp", "name": "HR Partner", "email": "hrbp@northwindcloud.com", + "phone": "+1 (415) 555-0000", "role": "Manager", "department": "Human Resources", + "departmentId": "dept_hr", "avatar": "", "managerId": None, + "title": "HR Business Partner", "location": "Remote", "joinDate": "2022-05-01", + "employeeType": "Full-Time", "birthday": "1988-03-20", "workAnniversary": "2022-05-01", + }, + "employees": managers + employees, + "departments": [ + {"id": "dept_eng", "name": "Engineering", "headcount": 2, "managerId": MGR_OKAFOR}, + {"id": "dept_sales", "name": "Sales", "headcount": 2, "managerId": MGR_NAIR}, + {"id": "dept_hr", "name": "Human Resources", "headcount": 1, "managerId": None}, + ], + "timeEntries": [], "timeOffRequests": [], "timeOffBalance": {}, + "payroll": [], "benefits": {}, "reviews": [], "goals": [], "tasks": [], + "announcements": [], "notifications": [], "contactDrafts": [], "clockStatus": {}, + } + + +def build_sheets_state(): + # Chen = row 3, Patterson = row 13. Reyes & Becker MISSING (will be added by agent). + data = { + "A1": {"value": "Employee", "formula": "Employee", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "B1": {"value": "Department", "formula": "Department", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "C1": {"value": "Level", "formula": "Level", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "D1": {"value": "Review Status", "formula": "Review Status", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "E1": {"value": "Goals Met", "formula": "Goals Met", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "F1": {"value": "Manager", "formula": "Manager", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + # Row 3: Maya Chen + "A3": {"value": "Maya Chen", "formula": "Maya Chen"}, + "B3": {"value": "Engineering", "formula": "Engineering"}, + "C3": {"value": "IC3", "formula": "IC3"}, + "D3": {"value": "Submitted", "formula": "Submitted"}, + "E3": {"value": "4 of 5", "formula": "4 of 5"}, + "F3": {"value": "Daniel Okafor", "formula": "Daniel Okafor"}, + # Row 13: Liam Patterson + "A13": {"value": "Liam Patterson", "formula": "Liam Patterson"}, + "B13": {"value": "Sales", "formula": "Sales"}, + "C13": {"value": "L4", "formula": "L4"}, + "D13": {"value": "Needs Calibration", "formula": "Needs Calibration"}, + "E13": {"value": "3 of 6", "formula": "3 of 6"}, + "F13": {"value": "Priya Nair", "formula": "Priya Nair"}, + } + return { + "id": "workbook_1", + "title": "Calibration Tracker 2026", + "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": "Cycle 1", + "rowCount": 100, "colCount": 6, + "frozenRows": 1, "frozenCols": 0, "tabColor": "#1A73E8", "isHidden": False, + "columnWidths": {"0": 150, "1": 130, "2": 80, "3": 160, "4": 100, "5": 150}, + "rowHeights": {}, "filterRange": None, "filterCriteria": {}, + "sortColumn": None, "sortDirection": None, + "data": data, + }], + } + + +def build_docs_state(): + return { + "currentUser": {"id": "user-1", "name": "HR Business Partner", + "email": "hrbp@northwindcloud.com", "avatar": ""}, + "users": [{"id": "user-1", "name": "HR Business Partner", + "email": "hrbp@northwindcloud.com", "avatar": ""}], + "documents": {}, + "comments": [], + "ui": {"currentDocId": None, "sidebarOpen": False, "sidebarTab": "comments", + "shareDialogOpen": False, "findReplaceOpen": False, "viewMode": "editing", + "zoom": 100, "documentListView": "grid", "searchQuery": ""}, + } + + +def build_calendar_state(): + return { + "user": {"id": "u1", "username": "HR Business Partner", + "email": "hrbp@northwindcloud.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-07-02T00:00:00.000Z", + "sidebarOpen": True, + "settings": {"weekStart": 0, "defaultDuration": 60, "defaultView": "week", + "defaultReminder": {"type": "popup", "minutes": 10}, "timeFormat": "12h", + "showWeekNumbers": False, "showDeclinedEvents": False}, + } + + +def build_slack_state(): + return { + "currentUser": { + "userId": "user_1", "fullName": "HR Business Partner", "displayName": "HRBP", + "email": "hrbp@northwindcloud.com", "avatar": "", "title": "HR Business Partner", + "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York", + }, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Northwind Cloud", "icon": ""}, + "users": [ + {"userId": "user_1", "fullName": "HR Business Partner", "displayName": "HRBP", + "email": "hrbp@northwindcloud.com", "avatar": "", "title": "HR Business Partner", "status": "active"}, + {"userId": "user_2", "fullName": "Daniel Okafor", "displayName": "Daniel", + "email": "daniel.okafor@northwindcloud.com", "avatar": "", "title": "Engineering Manager", "status": "active"}, + {"userId": "user_3", "fullName": "Priya Nair", "displayName": "Priya", + "email": "priya.nair@northwindcloud.com", "avatar": "", "title": "Sales Manager", "status": "active"}, + ], + "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": "2026-01-01T00:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "people-partners", "name": "people-partners", + "description": "People Partners calibration coordination", "topic": "Calibration discussions", + "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"], + "createdBy": "user_1", "createdAt": "2026-01-01T00:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": {"general": [], "people-partners": []}, + "threads": {}, "dms": [], "bookmarkedMessages": [], "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], "notifications": [], + } + + +def build_gmail_state(): + return { + "user": {"userId": "u1", "username": "HR Business Partner", + "email": "hrbp@northwindcloud.com", "avatar": ""}, + "emails": [ + { + "id": "email_1", "threadId": "thread_1", + "from": {"name": "Daniel Okafor", "email": "daniel.okafor@northwindcloud.com"}, + "to": [{"name": "HR Business Partner", "email": "hrbp@northwindcloud.com"}], + "subject": "FY2026 Cycle 1 calibration prep", + "body": "Hi — looking forward to the Cycle 1 calibration. Let me know the date.", + "timestamp": "2026-07-01T09:00:00Z", "read": False, "starred": False, + "important": False, "labels": [], "category": "primary", "folder": "inbox", + "attachments": [], + } + ], + "labels": [ + {"id": "l1", "name": "Work", "color": "#ef4444"}, + {"id": "l2", "name": "Personal", "color": "#3b82f6"}, + ], + "drafts": [], + "settings": {}, + } + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- +def main(): + sid = str(uuid.uuid4()) + with open("/tmp/task_web_sid", "w") as f: + f.write(sid) + + states = { + "lattice": build_lattice_state(), + "workday": build_workday_state(), + "sheets": build_sheets_state(), + "docs": build_docs_state(), + "calendar": build_calendar_state(), + "slack": build_slack_state(), + "gmail": build_gmail_state(), + } + + for name, url in MOCKS.items(): + state = states[name] + resp = requests.post(f"{url}/post?sid={sid}", + json={"action": "set", "state": state}, timeout=30) + assert resp.status_code == 200, f"{name} injection failed: {resp.text}" + print(f"Injected initial state for {name}: {resp.json().get('success')}") + + # 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: all 7 mocks have initial_state set") + + # Launch a Chrome window for EACH mock (agent needs all open) + for name, url in MOCKS.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.4) + + print(f"GUI_READY: launched browser windows for all 7 mocks (sid={sid})") + + +if __name__ == "__main__": + main() diff --git a/legacy/prof15_calibration_cycle_003/reward.py b/legacy/prof15_calibration_cycle_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..a39deea1c150092f2efd750a758e427fef11028b --- /dev/null +++ b/legacy/prof15_calibration_cycle_003/reward.py @@ -0,0 +1,358 @@ +""" +Reward Script: FY2026 Cycle 1 Performance Calibration (multi-app HR pipeline) +Task ID: prof15_calibration_cycle_003 +Domain: mock_websites (multi-mock: Sheets 8165, Docs 8162, Calendar 8161, Slack 8198, Gmail 8158) +Scoring: 5 independent components verifying deterministic end-state across 5 apps. + Each component scores a task-introduced change (fails on initial_env, passes on golden_env). + The doc link is derived from the actual agenda doc id and matched in Calendar/Slack/Gmail. +""" +import json +import sys +import urllib.request +import urllib.error + +BASE = "http://28.7.186.212" + +# Mock ports (from task_config.json) +PORT_SHEETS = 8165 +PORT_DOCS = 8162 +PORT_CALENDAR = 8161 +PORT_SLACK = 8198 +PORT_GMAIL = 8158 + +# Expected cohort data (from task_config.json ground truth) +EXPECTED_EMPLOYEES = { + "Maya Chen": ("Engineering", "IC3", "Submitted", "4 of 5", "Daniel Okafor"), + "Liam Patterson": ("Sales", "L4", "Needs Calibration", "3 of 6", "Priya Nair"), + "Sofia Reyes": ("Engineering", "L5", "Submitted", "6 of 6", "Daniel Okafor"), + "Tom Becker": ("Sales", "L3", "Submitted", "5 of 5", "Priya Nair"), +} + +MANAGERS = ["daniel.okafor@northwindcloud.com", "priya.nair@northwindcloud.com"] +DOC_TITLE = "Cycle 1 Calibration Agenda" + +# Exact text from task_config.json ground truth +FOCUS_LIST_LINE = "Needs focused discussion: Liam Patterson (Sales L4) — 3 of 6 goals, Needs Calibration." +LOGISTICS_LINE = "30-min per employee; managers Daniel Okafor and Priya Nair required." +SLACK_MESSAGE_EXPECTATIONS = [ + "Maya Chen", "Liam Patterson", "Sofia Reyes", "Tom Becker", + "NEEDS CALIBRATION", "Daniel Okafor", "Priya Nair", +] +EMAIL_SUBJECT = "Performance Calibration — Cycle 1 (2026-07-10)" +CAL_EVENT_TITLE = "Performance Calibration — Cycle 1" +CAL_START = "2026-07-10T13:00:00" +CAL_END = "2026-07-10T15:00:00" + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +def _fetch(port, sid): + """Fetch /go?sid= state for a mock. Returns parsed JSON or raises.""" + url = f"{BASE}:{port}/go?sid={sid}" + with urllib.request.urlopen(url, timeout=20) as r: + return json.load(r) + + +# --------------------------------------------------------------------------- +# Component 1: Google Sheets — all 4 cohort rows present with correct A-F values +# --------------------------------------------------------------------------- +def check_component_1(sheets_state): + """All 4 cohort employees present in 'Cycle 1' sheet with correct + Employee/Department/Level/Review Status/Goals Met/Manager (A-F). + Pass condition: every EXPECTED_EMPLOYEES tuple is found among the sheet rows. + Fails on initial_env (Reyes & Becker rows missing).""" + try: + sheets = sheets_state.get('sheets', []) + if not sheets: + return False, 0.0, 'no sheets in workbook' + # Find the 'Cycle 1' sheet + target = None + for s in sheets: + if s.get('name') == 'Cycle 1': + target = s + break + if target is None: + return False, 0.0, "sheet 'Cycle 1' not found" + data = target.get('data', {}) + # Build list of (A,B,C,D,E,F) row tuples from cell data + # Cells are keyed like 'A3','B3'... group by row number. + rows = {} + for key, cell in data.items(): + if len(key) < 2: + continue + col = key[0] + # row index is the trailing digits + try: + rownum = int(key[1:]) + except ValueError: + continue + val = cell.get('value') + if val is None: + continue + rows.setdefault(rownum, {})[col] = str(val).strip() + # Skip header row (row 1) + found = {} + for rownum, cells in rows.items(): + if rownum == 1: + continue + emp = cells.get('A') + if emp in EXPECTED_EMPLOYEES: + b = cells.get('B', '') + c = cells.get('C', '') + d = cells.get('D', '') + e = cells.get('E', '') + f = cells.get('F', '') + exp = EXPECTED_EMPLOYEES[emp] + if (b, c, d, e, f) == exp: + found[emp] = rownum + missing = [e for e in EXPECTED_EMPLOYEES if e not in found] + if not missing: + return True, 0.25, f'all 4 employees present with correct A-F values; rows={found}' + return False, 0.0, f'missing employees: {missing}' + except Exception as e: + return False, 0.0, f'exception: {e}' + + +# --------------------------------------------------------------------------- +# Component 2: Google Docs — 'Cycle 1 Calibration Agenda' doc with required sections +# --------------------------------------------------------------------------- +def check_component_2(docs_state): + """A document titled 'Cycle 1 Calibration Agenda' exists with H1 title, + a Cohort section listing all 4 employees (dept/level/status/goals), a Focus + List section with the exact Liam Patterson line, and a Logistics section with + the exact sentence. Pass condition: all 4 checks pass. Fails on initial_env + (no such doc). Returns (passed, score, detail, doc_id) via tuple len 4.""" + try: + docs = docs_state.get('documents', {}) + agenda = None + for doc in docs.values(): + if doc.get('title') == DOC_TITLE: + agenda = doc + break + if agenda is None: + return False, 0.0, "no document titled 'Cycle 1 Calibration Agenda'", None + content = agenda.get('content', '') or '' + # H1 title + if '

Cycle 1 Calibration Agenda

' not in content: + return False, 0.0, 'H1 title missing', None + # Cohort section listing all 4 employees + if 'Cohort' not in content: + return False, 0.0, 'Cohort section missing', None + cohort_ok = all( + all(tok in content for tok in [name]) + for name in EXPECTED_EMPLOYEES + ) + # verify each employee's key attributes appear near their entry + checks = { + "Maya Chen": ["Engineering", "IC3", "Submitted", "4 of 5"], + "Liam Patterson": ["Sales", "L4", "Needs Calibration", "3 of 6"], + "Sofia Reyes": ["Engineering", "L5", "Submitted", "6 of 6"], + "Tom Becker": ["Sales", "L3", "Submitted", "5 of 5"], + } + attr_ok = all( + all(t in content for t in toks) for toks in checks.values() + ) + if not (cohort_ok and attr_ok): + return False, 0.0, 'Cohort section incomplete (missing employee or attribute)', None + # Focus List exact line + if 'Focus List' not in content: + return False, 0.0, 'Focus List section missing', None + if FOCUS_LIST_LINE not in content: + return False, 0.0, 'Focus List exact Liam line missing', None + # Logistics exact sentence + if 'Logistics' not in content: + return False, 0.0, 'Logistics section missing', None + if LOGISTICS_LINE not in content: + return False, 0.0, 'Logistics exact sentence missing', None + doc_id = agenda.get('id') + return True, 0.20, f'all sections present (doc id={doc_id})', doc_id + except Exception as e: + return False, 0.0, f'exception: {e}', None + + +# --------------------------------------------------------------------------- +# Component 3: Google Calendar — event with time, guests, and doc link +# --------------------------------------------------------------------------- +def check_component_3(cal_state, doc_id): + """Event 'Performance Calibration — Cycle 1' on 2026-07-10 13:00-15:00 with + both managers as guests and a description containing the agenda doc link. + Pass condition: event exists with matching title/start/end/guests/doc-link. + Fails on initial_env (no such event).""" + try: + if not doc_id: + return False, 0.0, 'no agenda doc id to match link against' + events = cal_state.get('events', []) + for ev in events: + if ev.get('title') != CAL_EVENT_TITLE: + continue + start = (ev.get('start') or '')[:19] + end = (ev.get('end') or '')[:19] + guests = ev.get('guests', []) + desc = ev.get('description', '') or '' + if start != CAL_START: + return False, 0.0, f"start {start} != {CAL_START}" + if end != CAL_END: + return False, 0.0, f"end {end} != {CAL_END}" + guests_lower = [g.lower() for g in guests] + if not all(m.lower() in guests_lower for m in MANAGERS): + return False, 0.0, f'guests {guests} missing a manager' + # doc link must reference the actual agenda doc id + link = f"{BASE}:{PORT_DOCS}/?docId={doc_id}" + if link not in desc: + return False, 0.0, f'description missing doc link ({link})' + return True, 0.20, f'event correct with doc link for {doc_id}' + return False, 0.0, f"no event titled '{CAL_EVENT_TITLE}'" + except Exception as e: + return False, 0.0, f'exception: {e}' + + +# --------------------------------------------------------------------------- +# Component 4: Slack — new #people-partners message with cohort + managers + doc link +# --------------------------------------------------------------------------- +def check_component_4(slack_state, doc_id): + """A new message in #people-partners lists all 4 employees (Liam flagged as + NEEDS CALIBRATION), names both managers, and links the agenda doc. + Pass condition: a people-partners message contains all expected tokens and + the doc link. Fails on initial_env (channel empty).""" + try: + if not doc_id: + return False, 0.0, 'no agenda doc id to match link against' + msgs = slack_state.get('messages', {}) + pp = msgs.get('people-partners', []) + if not pp: + return False, 0.0, '#people-partners has no messages' + # check the newest message (last in list) + msg = pp[-1] + content = msg.get('content', '') or '' + link = f"{BASE}:{PORT_DOCS}/?docId={doc_id}" + missing = [t for t in SLACK_MESSAGE_EXPECTATIONS if t not in content] + if missing: + return False, 0.0, f'message missing tokens: {missing}' + if link not in content: + return False, 0.0, f'message missing doc link ({link})' + return True, 0.20, 'people-partners message complete with doc link' + except Exception as e: + return False, 0.0, f'exception: {e}' + + +# --------------------------------------------------------------------------- +# Component 5: Gmail — sent email to both managers with exact subject/body + doc link +# --------------------------------------------------------------------------- +def check_component_5(gmail_state, doc_id): + """A sent email to both managers with subject 'Performance Calibration — + Cycle 1 (2026-07-10)', the exact body, and the agenda doc link. + Pass condition: an email in folder 'sent' to both managers with matching + subject/body/doc-link. Fails on initial_env (only the inbound email exists).""" + try: + if not doc_id: + return False, 0.0, 'no agenda doc id to match link against' + emails = gmail_state.get('emails', []) + link = f"{BASE}:{PORT_DOCS}/?docId={doc_id}" + for e in emails: + to_list = [t.get('email', '').lower() for t in (e.get('to') or [])] + if not all(m.lower() in to_list for m in MANAGERS): + continue + if e.get('subject') != EMAIL_SUBJECT: + continue + body = e.get('body', '') or '' + # body must contain the cohort names, the Liam flag, and the doc link + required = ["Maya Chen", "Liam Patterson", "Sofia Reyes", "Tom Becker", + "3 of 6 goals", link] + if not all(t in body for t in required): + continue + # ensure it's the outgoing HRBP message (folder sent), not the inbound + if e.get('folder') not in ('sent', None): + # folder may be absent; rely on from/to direction + pass + return True, 0.15, f'correct sent email found (id={e.get("id")})' + return False, 0.0, 'no email to both managers with exact subject/body/doc-link' + except Exception as e: + return False, 0.0, f'exception: {e}' + + +def verify_task(): + # --- Read sid --- + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + if not sid: + raise ValueError('empty sid') + except Exception as e: + print(f'CRITICAL: cannot read sid: {e}') + print('REWARD: 0.0') + return 0.0 + + # --- Fetch all mock states --- + try: + sheets = _fetch(PORT_SHEETS, sid)['current_state'] + docs = _fetch(PORT_DOCS, sid)['current_state'] + cal = _fetch(PORT_CALENDAR, sid)['current_state'] + slack = _fetch(PORT_SLACK, sid)['current_state'] + gmail = _fetch(PORT_GMAIL, sid)['current_state'] + except Exception as e: + print(f'CRITICAL: cannot fetch mock state: {e}') + print('REWARD: 0.0') + return 0.0 + + total_score = 0.0 + + # Component 1: Sheets rows + passed, score, _ = _run_component(1, 'Sheets: all 4 cohort rows', 0.25, + check_component_1, (sheets,)) + total_score += score if passed else 0.0 + + # Component 2: Docs agenda doc (also returns doc_id for downstream link checks) + docs_passed, docs_score, docs_detail, doc_id = (False, 0.0, 'n/a', None) + try: + docs_passed, docs_score, docs_detail, doc_id = check_component_2(docs) + except Exception as e: + docs_passed, docs_score, docs_detail = False, 0.0, f'error: {e}' + status = 'PASS' if docs_passed else 'FAIL' + suffix = f' (0.2 pts)' if docs_passed else f' — {docs_detail}' + print(f'{status}: Component 2 — Docs: agenda doc{suffix}') + _comp(2, 'Docs: agenda doc', 0.20, docs_passed, docs_score, docs_detail, + description=(check_component_2.__doc__ or '').strip()) + total_score += docs_score if docs_passed else 0.0 + + # Components 3-5 depend on doc_id (the agenda doc must exist first) + passed, score, _ = _run_component(3, 'Calendar: event + guests + doc link', 0.20, + check_component_3, (cal, doc_id)) + total_score += score if passed else 0.0 + + passed, score, _ = _run_component(4, 'Slack: #people-partners message + doc link', 0.20, + check_component_4, (slack, doc_id)) + total_score += score if passed else 0.0 + + passed, score, _ = _run_component(5, 'Gmail: sent email to managers + doc link', 0.15, + check_component_5, (gmail, doc_id)) + total_score += score if passed else 0.0 + + 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/legacy/prof15_calibration_cycle_003/reward_label.json b/legacy/prof15_calibration_cycle_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..8f88d0797cb56d7c927fedcfb5cc3c3b9bd08f6a --- /dev/null +++ b/legacy/prof15_calibration_cycle_003/reward_label.json @@ -0,0 +1,73 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof15_calibration_cycle_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:28:41", + "label": { + "task_id": "prof15_calibration_cycle_003", + "domain": "mock_websites", + "summary": "验证跨5个模拟应用(Sheets、Docs、Calendar、Slack、Gmail)的HR绩效校准流程是否达到预期的确定性最终状态", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8165 (Sheets mock)", + "http://28.7.186.212:8162 (Docs mock)", + "http://28.7.186.212:8161 (Calendar mock)", + "http://28.7.186.212:8198 (Slack mock)", + "http://28.7.186.212:8158 (Gmail mock)" + ], + "scoring_components": [ + { + "name": "Component 1: Sheets 员工数据", + "weight": 0.25, + "description": "验证 Sheets 的 'Cycle 1' 工作表中包含4名员工的完整行数据,且 A-F 列与预期完全一致", + "check_logic": "遍历 Sheets 状态,定位名为 'Cycle 1' 的 sheet,解析单元格数据按行分组(跳过第1行表头),检查 EXPECTED_EMPLOYEES 中每个员工的 B、C、D、E、F 列元组是否与预期相等", + "pass_condition": "4名员工(Maya Chen、Liam Patterson、Sofia Reyes、Tom Becker)全部存在且对应列值完全匹配预期元组" + }, + { + "name": "Component 2: Docs 议程文档", + "weight": 0.2, + "description": "验证存在标题为 'Cycle 1 Calibration Agenda' 的文档,且包含所需的 H1 标题、Cohort、Focus List 和 Logistics 章节及精确文本", + "check_logic": "在 docs_state 中查找 title 为 DOC_TITLE 的文档;检查 content 包含 '

Cycle 1 Calibration Agenda

'、'Cohort' 及4名员工的关键属性文本、'Focus List' 及 FOCUS_LIST_LINE 精确文本、'Logistics' 及 LOGISTICS_LINE 精确文本;通过时返回 doc_id", + "pass_condition": "文档存在且 H1 标题、Cohort 章节(含4人属性)、Focus List 精确行、Logistics 精确句全部匹配" + }, + { + "name": "Component 3: Calendar 日程事件", + "weight": 0.2, + "description": "验证 Calendar 中存在指定标题、时间、嘉宾并附带议程文档链接的事件", + "check_logic": "遍历 events,匹配 title 为 CAL_EVENT_TITLE;校验 start 前19字符等于 CAL_START、end 前19字符等于 CAL_END;guests 列表包含两位 MANAGERS(不区分大小写);description 中包含基于 doc_id 构建的链接 BASE:PORT_DOCS/?docId={doc_id}", + "pass_condition": "事件标题、开始/结束时间、两位经理嘉宾均匹配,且描述中包含对应 doc_id 的文档链接" + }, + { + "name": "Component 4: Slack 频道消息", + "weight": 0.2, + "description": "验证 Slack #people-partners 频道最新消息包含所有预期关键词及议程文档链接", + "check_logic": "获取 slack_state['messages']['people-partners'] 的最后一条消息;检查 content 包含 SLACK_MESSAGE_EXPECTATIONS 列表中的所有 token(4个员工名、NEEDS CALIBRATION、两位经理名);并包含基于 doc_id 的文档链接", + "pass_condition": "#people-partners 有消息,且最新消息包含全部预期关键词和文档链接" + }, + { + "name": "Component 5: Gmail 发送邮件", + "weight": 0.15, + "description": "验证 Gmail 中存在发送给两位经理的邮件,主题、正文和文档链接均符合预期", + "check_logic": "遍历 emails,查找 to 列表包含两位 MANAGERS(不区分大小写)、subject 等于 EMAIL_SUBJECT、body 包含4个员工名、'3 of 6 goals' 及基于 doc_id 的文档链接的邮件;接受 folder 为 'sent' 或缺失", + "pass_condition": "存在发送给两位经理的邮件,主题精确匹配,正文包含所需内容和文档链接" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到4位小数输出", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0", + "获取任一 mock 状态(_fetch)失败:打印 CRITICAL 并返回 0.0", + "Component 1:'Cycle 1' 工作表不存在、或缺少员工、或 A-F 列值不匹配 → 该组件得 0.0", + "Component 2:议程文档不存在、或 H1/章节/精确文本缺失 → 该组件得 0.0,且 doc_id 为 None", + "Component 2 失败导致 doc_id 为 None:Components 3-5 将因 'no agenda doc id' 直接失败得 0.0", + "Component 3:事件标题/时间/嘉宾/文档链接任一不匹配 → 该组件得 0.0", + "Component 4:#people-partners 无消息、或缺少关键词、或缺少文档链接 → 该组件得 0.0", + "Component 5:无邮件发给两位经理、或主题/正文/链接不匹配 → 该组件得 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后使用 sid 分别向 Sheets、Docs、Calendar、Slack、Gmail 五个 mock 服务拉取当前状态,任一拉取失败也直接返回 0.0。接着按顺序执行5个独立组件检查:组件1验证 Sheets 中 'Cycle 1' 表的4名员工数据;组件2验证 Docs 议程文档的完整性与精确文本,并提取 doc_id;组件3-5分别验证 Calendar 事件、Slack 消息和 Gmail 邮件是否包含正确内容以及基于该 doc_id 的文档链接。各组件通过则累加其权重分值(0.25+0.20+0.20+0.20+0.15),不通过则该组件得 0.0 但继续后续检查。最终总分经 min(..., 1.0) 钳制并四舍五入到4位小数后作为 REWARD 输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: prof15_calibration_cycle_003\n2. **Domain**: mock_websites (multi-mock: Sheets 8165, Docs 8162, Calendar 8161, Slack 8198, Gmail 8158)\n3. **Summary**: 验证跨5个应用(Sheets、Docs、Calendar、Slack、Gmail)的HR绩效校准流程的确定性最终状态。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n5. **data_sources**: \n - /tmp/task_web_sid (读取 session ID)\n - http://28.7.186.212:8165 (Sheets mock)\n - http://28.7.186.212:8162 (Docs mock)\n - http://28.7.186.212:8161 (Calendar mock)\n - http://28.7.186.212:8198 (Slack mock)\n - http://28.7.186.212:8158 (Gmail mock)\n\n6. **Scoring Components**:\n - Component 1: Sheets - 0.25分,检查'Cycle 1'工作表中4个员工的A-F列数据是否匹配EXPECTED_EMPLOYEES。\n - Component 2: Docs - 0.20分,检查是否存在标题为'Cycle 1 Calibration Agenda'的文档,包含H1标题、Cohort部分(4个员工及属性)、Focus List部分(精确文本)、Logistics部分(精确文本)。返回doc_id。\n - Component 3: Calendar - 0.20分,检查是否存在标题为'Performance Calibration — Cycle 1'的事件,开始时间2026-07-10T13:00:00,结束时间2026-07-10T15:00:00,包含两位经理作为嘉宾,描述中包含议程文档链接(基于doc_id)。\n - Component 4: Slack - 0.20分,检查#people-partners频道最新消息是否包含所有预期标记(4个员工名字、\"NEEDS CALIBRATION\"、两位经理名字)和文档链接。\n - Component 5: Gmail - 0.15分,检查发送文件夹中是否有发送给两位经理的邮件,主题精确匹配,正文包含4个员工名字、\"3 of 6 goals\"和文档链接。\n\n7. **Score Aggregation**: 各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到4位小数。\n\n8. **Failure Modes**:\n - 读取 /tmp/task_web_sid 失败或为空 → CRITICAL,返回 0.0\n - 获取任何 mock 状态失败 → CRITICAL,返回 0.0\n - 各组件检查失败返回 0.0 分(不会提前退出,继续检查其他组件)\n - Component 2 失败会导致 doc_id 为 None,进而导致 Components 3-5 因缺少 doc_id 而失败\n\n9. **Scoring Logic Explanation**: \n - 从 /tmp/task_web_sid 读取 session ID。\n - 使用 sid 分别向 5 个 mock 服务(Sheets、Docs、Calendar、Slack、Gmail)的 /go?sid= 端点获取当前状态。\n - 组件1:在 Sheets 的 'Cycle 1' 表中查找4个员工,验证 A-F 列数据与预期完全一致。\n - 组件2:在 Docs 中查找标题为 'Cycle 1 Calibration Agenda' 的文档,验证 H1 标题、Cohort 章节包含4名员工及其属性、Focus List 章节包含指定精确文本、Logistics 章节包含指定精确文本。通过则提取 doc_id。\n - 组件3:在 Calendar 中查找指定标题和时间的事件,验证嘉宾包含两位经理,描述中包含基于 doc_id 的文档链接。\n - 组件4:检查 Slack #people-partners 频道最新一条消息,验证包含所有预期关键词和文档链接。\n - 组件5:在 Gmail 中查找发送给两位经理的邮件,验证主题、正文内容和文档链接。\n - 各组件得分累加,上限 1.0,四舍五入后输出。\n\n10. **Confidence**: 1.0\n\n让我再仔细检查一下权重:\n- Component 1: 0.25\n- Component 2: 0.20\n- Component 3: 0.20\n- Component 4: 0.20\n- Component 5: 0.15\n总和 = 1.0\n\n检查 Component 2 的特殊处理:代码中 Component 2 没有使用 _run_component 辅助函数,而是直接调用 check_component_2,然后手动打印和累加。check_component_2 返回4个值 (passed, score, detail, doc_id)。\n\n其他组件通过 _run_component 运行,返回 (passed, score, detail)。\n\nFailure modes 需要包括:\n- sid 读取失败\n- mock 状态获取失败\n- Sheets 中缺少员工或数据不匹配\n- Docs 中缺少议程文档或章节/文本不匹配\n- Calendar 中缺少事件或时间/嘉宾/链接不匹配\n- Slack 中缺少消息或关键词/链接不匹配\n- Gmail 中缺少邮件或收件人/主题/正文/链接不匹配\n- doc_id 缺失导致下游组件失败\n\n我需要确保 JSON 格式完全符合要求,没有 Markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我构建 JSON。 {\"task_id\":\"prof15_calibration_cycle_003\",\"domain\":\"mock_websites\",\"summary\":\"验证跨5个模拟应用(Sheets、Docs、Calendar、Slack、Gmail)的HR绩效校准流程是否达到预期的确定性最终状态\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"http://28.7.186.212:8165 (Sheets mock)\",\"http://28.7.186.212:8162 (Docs mock)\",\"http://28.7.186.212:8161 (Calendar mock)\",\"http://28.7.186.212:8198 (Slack mock)\",\"http://28.7.186.212:8158 (Gmail mock)\"],\"scoring_components\":[{\"name\":\"Component 1: Sheets 员工数据\",\"weight\":0.25,\"description\":\"验证 Sheets 的 'Cycle 1' 工作表中包含4名员工的完整行数据,且 A-F 列与预期完全一致\",\"check_logic\":\"遍历 Sheets 状态,定位名为 'Cycle 1' 的 sheet,解析单元格数据按行分组(跳过第1行表头),检查 EXPECTED_EMPLOYEES 中每个员工的 B、C、D、E、F 列元组是否与预期相等\",\"pass_condition\":\"4名员工(Maya Chen、Liam Patterson、Sofia Reyes、Tom Becker)全部存在且对应列值完全匹配预期元组\"},{\"name\":\"Component 2: Docs 议程文档\",\"weight\":0.20,\"description\":\"验证存在标题为 'Cycle 1 Calibration Agenda' 的文档,且包含所需的 H1 标题、Cohort、Focus List 和 Logistics 章节及精确文本\",\"check_logic\":\"在 docs_state 中查找 title 为 DOC_TITLE 的文档;检查 content 包含 '

Cycle 1 Calibration Agenda

'、'Cohort' 及4名员工的关键属性文本、'Focus List' 及 FOCUS_LIST_LINE 精确文本、'Logistics' 及 LOGISTICS_LINE 精确文本;通过时返回 doc_id\",\"pass_condition\":\"文档存在且 H1 标题、Cohort 章节(含4人属性)、Focus List 精确行、Logistics 精确句全部匹配\"},{\"name\":\"Component 3: Calendar 日程事件\",\"weight\":0.20,\"description\":\"验证 Calendar 中存在指定标题、时间、嘉宾并附带议程文档链接的事件\",\"check_logic\":\"遍历 events,匹配 title 为 CAL_EVENT_TITLE;校验 start 前19字符等于 CAL_START、end 前19字符等于 CAL_END;guests 列表包含两位 MANAGERS(不区分大小写);description 中包含基于 doc_id 构建的链接 BASE:PORT_DOCS/?docId={doc_id}\",\"pass_condition\":\"事件标题、开始/结束时间、两位经理嘉宾均匹配,且描述中包含对应 doc_id 的文档链接\"},{\"name\":\"Component 4: Slack 频道消息\",\"weight\":0.20,\"description\":\"验证 Slack #people-partners 频道最新消息包含所有预期关键词及议程文档链接\",\"check_logic\":\"获取 slack_state['messages']['people-partners'] 的最后一条消息;检查 content 包含 SLACK_MESSAGE_EXPECTATIONS 列表中的所有 token(4个员工名、NEEDS CALIBRATION、两位经理名);并包含基于 doc_id 的文档链接\",\"pass_condition\":\"#people-partners 有消息,且最新消息包含全部预期关键词和文档链接\"},{\"name\":\"Component 5: Gmail 发送邮件\",\"weight\":0.15,\"description\":\"验证 Gmail 中存在发送给两位经理的邮件,主题、正文和文档链接均符合预期\",\"check_logic\":\"遍历 emails,查找 to 列表包含两位 MANAGERS(不区分大小写)、subject 等于 EMAIL_SUBJECT、body 包含4个员工名、'3 of 6 goals' 及基于 doc_id 的文档链接的邮件;接受 folder 为 'sent' 或缺失\",\"pass_condition\":\"存在发送给两位经理的邮件,主题精确匹配,正文包含所需内容和文档链接\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到4位小数输出\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\"获取任一 mock 状态(_fetch)失败:打印 CRITICAL 并返回 0.0\",\"Component 1:'Cycle 1' 工作表不存在、或缺少员工、或 A-F 列值不匹配 → 该组件得 0.0\",\"Component 2:议程文档不存在、或 H1/章节/精确文本缺失 → 该组件得 0.0,且 doc_id 为 None\",\"Component 2 失败导致 doc_id 为 None:Components 3-5 将因 'no agenda doc id' 直接失败得 0.0\",\"Component 3:事件标题/时间/嘉宾/文档链接任一不匹配 → 该组件得 0.0\",\"Component 4:#people-partners 无消息、或缺少关键词、或缺少文档链接 → 该组件得 0.0\",\"Component 5:无邮件发给两位经理、或主题/正文/链接不匹配 → 该组件得 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后使用 sid 分别向 Sheets、Docs、Calendar、Slack、Gmail 五个 mock 服务拉取当前状态,任一拉取失败也直接返回 0.0。接着按顺序执行5个独立组件检查:组件1验证 Sheets 中 'Cycle 1' 表的4名员工数据;组件2验证 Docs 议程文档的完整性与精确文本,并提取 doc_id;组件3-5分别验证 Calendar 事件、Slack 消息和 Gmail 邮件是否包含正确内容以及基于该 doc_id 的文档链接。各组件通过则累加其权重分值(0.25+0.20+0.20+0.20+0.15),不通过则该组件得 0.0 但继续后续检查。最终总分经 min(..., 1.0) 钳制并四舍五入到4位小数后作为 REWARD 输出。\",\"confidence\":1.0}" +} diff --git a/legacy/prof16_postmortem_003/_cua_gym_vm_bridge.sh b/legacy/prof16_postmortem_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/prof16_postmortem_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/prof16_postmortem_003/initial_setup.py b/legacy/prof16_postmortem_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3083d954a2435fd347ad42808ada88ad795645 --- /dev/null +++ b/legacy/prof16_postmortem_003/initial_setup.py @@ -0,0 +1,562 @@ +""" +Initial Setup: Marketing Campaign Manager post-mortem / cross-team handoff +Task ID: prof16_postmortem_003 +Domain: mock_websites (multi-mock across 8 apps) +Mocks: hubspot(8170), google_sheets(8165), airtable(8129), monday(8185), + google_docs(8162), slack(8198), gmail(8158), google_calendar(8161) + +This script establishes the documented INITIAL STATE for the task: +- HubSpot: Q2 Webinar Series Campaign Performance with canonical figures (read-only source) +- Google Sheets: 'Campaign Reports 2026' / 'Performance' with rows 2-3 populated, row 4 EMPTY +- Airtable: base 'Campaign Ops' / table 'Campaigns' with 'Q2 Webinar Series' record + Status='Live', Notes empty +- Monday: board 'Campaign Closeout' with a 'Done' group but NO closeout item +- Google Docs: no post-mortem doc +- Slack: #marketing readable/writable, no learnings message +- Gmail: campaign manager's account, no handoff sent +- Google Calendar: no 'Q2 Webinar Series Retro' event +""" + +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# ---------------------------------------------------------------------------- +# Mock base URLs (the task-configured deployment on the VM network) +# ---------------------------------------------------------------------------- +HOST = "http://28.7.186.212" +MOCKS = { + "hubspot": f"{HOST}:8170", # read-only source of truth + "sheets": f"{HOST}:8165", + "airtable": f"{HOST}:8129", + "monday": f"{HOST}:8185", + "docs": f"{HOST}:8162", + "slack": f"{HOST}:8198", + "gmail": f"{HOST}:8158", + "calendar": f"{HOST}:8161", +} + +SID_FILE = "/tmp/task_web_sid" + +# Fixed identifiers used across initial + golden so the diff is deterministic +DOC_ID = "doc-q2-webinar-postmortem" +TODAY = "2026-07-02" + + +def build_states(): + """Return dict: mock_name -> full initial state object.""" + states = {} + + # ----------------------------------------------------------------- # + # 1. HubSpot (read-only source) — canonical campaign figures + # ----------------------------------------------------------------- # + states["hubspot"] = { + "currentUser": { + "id": "u1", "name": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + }, + "campaigns": [ + { + "id": "camp_q2_webinar", + "name": "Q2 Webinar Series", + "status": "Live", + "metrics": { + "mql": 540, + "openRate": "41.2%", + "conversionRate": "6.3%", + "registrants": 1290, + "attendees": 842, + }, + "source": "HubSpot", + } + ], + "activeCampaignId": "camp_q2_webinar", + } + + # ----------------------------------------------------------------- # + # 2. Google Sheets — 'Campaign Reports 2026' workbook, 'Performance' sheet + # rows 2-3 populated, row 4 EMPTY (to be appended by the agent) + # ----------------------------------------------------------------- # + states["sheets"] = { + "id": "workbook_campaign_reports_2026", + "title": "Campaign Reports 2026", + "activeSheetId": "sheet_performance", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [ + { + "id": "sheet_performance", + "name": "Performance", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": "#1A73E8", + "isHidden": False, + "columnWidths": {"0": 160, "1": 100, "2": 120, "3": 120, "4": 120}, + "data": { + "A1": {"value": "Campaign", "formula": "Campaign", + "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "B1": {"value": "MQLs", "formula": "MQLs", + "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "C1": {"value": "Open Rate", "formula": "Open Rate", + "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "D1": {"value": "Conversion", "formula": "Conversion", + "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "E1": {"value": "Source", "formula": "Source", + "style": {"bold": True, "bg": "#E8EAED", "align": "center"}}, + "A2": {"value": "Winter Reboot", "formula": "Winter Reboot"}, + "B2": {"value": "320", "formula": "320"}, + "C2": {"value": "38.5%", "formula": "38.5%"}, + "D2": {"value": "4.9%", "formula": "4.9%"}, + "E2": {"value": "HubSpot", "formula": "HubSpot"}, + "A3": {"value": "Spring Nurture", "formula": "Spring Nurture"}, + "B3": {"value": "410", "formula": "410"}, + "C3": {"value": "39.8%", "formula": "39.8%"}, + "D3": {"value": "5.4%", "formula": "5.4%"}, + "E3": {"value": "HubSpot", "formula": "HubSpot"}, + # Row 4 intentionally EMPTY — agent must append here + }, + } + ], + } + + # ----------------------------------------------------------------- # + # 3. Airtable — base 'Campaign Ops', table 'Campaigns' + # record 'Q2 Webinar Series' Status='Live', Notes empty + # ----------------------------------------------------------------- # + states["airtable"] = { + "currentUser": { + "id": "user_1", "name": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + "avatar": "https://ui-avatars.com/api/?name=Marketing&background=8B5CF6&color=fff", + }, + "collaborators": [ + {"id": "user_1", "name": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + "avatar": "https://ui-avatars.com/api/?name=Marketing&background=8B5CF6&color=fff"}, + {"id": "user_2", "name": "Sales Ops", + "email": "sales-ops@northwindcloud.com", + "avatar": "https://ui-avatars.com/api/?name=Sales+Ops&background=00C875&color=fff"}, + ], + "bases": { + "base_campaign_ops": { + "id": "base_campaign_ops", + "name": "Campaign Ops", + "color": "bg-teal-600", + "tables": ["tbl_campaigns"], + } + }, + "tables": { + "tbl_campaigns": { + "id": "tbl_campaigns", + "name": "Campaigns", + "baseId": "base_campaign_ops", + "fields": [ + {"id": "fld_name", "name": "Name", "type": "text", "primary": True}, + {"id": "fld_status", "name": "Status", "type": "single_select", + "options": [ + {"id": "st_live", "name": "Live", "color": "bg-[#D1F7C4] text-[#2D7514]"}, + {"id": "st_closed", "name": "Closed", "color": "bg-[#FFDCE5] text-[#B31846]"}, + ]}, + {"id": "fld_notes", "name": "Notes", "type": "long_text"}, + ], + "records": [ + { + "id": "rec_q2_webinar", + "createdTime": "2026-04-01T09:00:00.000Z", + "fields": { + "fld_name": "Q2 Webinar Series", + "fld_status": "Live", + "fld_notes": "", + }, + }, + { + "id": "rec_spring_launch", + "createdTime": "2026-03-10T09:00:00.000Z", + "fields": { + "fld_name": "Spring Product Launch", + "fld_status": "Live", + "fld_notes": "Awaiting creative from design team.", + }, + }, + ], + "views": [ + {"id": "view_all", "name": "Grid view", "type": "grid", + "filters": [], "sorts": [], "groupBy": [], "hiddenFieldIds": [], + "fieldWidths": {}, "rowHeight": "short"} + ], + "activeViewId": "view_all", + } + }, + "activeBaseId": "base_campaign_ops", + "activeTableId": "tbl_campaigns", + "ui": { + "viewSidebarOpen": False, + "expandedRecordId": None, + "searchQuery": "", + "isSearching": False, + }, + } + + # ----------------------------------------------------------------- # + # 4. Monday — board 'Campaign Closeout' with a 'Done' group, NO item + # ----------------------------------------------------------------- # + states["monday"] = { + "workspaces": [ + {"id": "ws1", "name": "Main Workspace", "icon": "M", "color": "#0073EA", + "boardIds": ["b1"]} + ], + "boards": [ + { + "id": "b1", + "workspaceId": "ws1", + "name": "Campaign Closeout", + "description": "Cross-team campaign closeout board", + "columns": [ + {"id": "c1", "title": "Owner", "type": "person", "width": 120}, + {"id": "c2", "title": "Status", "type": "status", "width": 140, + "settings": {"labels": [ + {"id": "s1", "label": "Done", "color": "#00c875"}, + {"id": "s2", "label": "Working on it", "color": "#fdab3d"}, + {"id": "s3", "label": "Stuck", "color": "#e2445c"}, + {"id": "s4", "label": "Not Started", "color": "#c4c4c4"}, + ]}}, + {"id": "c3", "title": "Due Date", "type": "date", "width": 120}, + {"id": "c4", "title": "Priority", "type": "status", "width": 140, + "settings": {"labels": [ + {"id": "p1", "label": "High", "color": "#401694"}, + {"id": "p2", "label": "Medium", "color": "#579bfc"}, + {"id": "p3", "label": "Low", "color": "#79d5ea"}, + ]}}, + ], + "groups": [ + {"id": "g_done", "title": "Done", "color": "#00c875", "itemIds": []}, + {"id": "g_active", "title": "In Progress", "color": "#fdab3d", "itemIds": []}, + ], + "items": [], + "updates": [], + "activities": [], + } + ], + "currentUser": { + "id": "u1", "name": "Marketing Campaign Mgmt", + "avatar": "https://picsum.photos/100/100?random=u1", + }, + } + + # ----------------------------------------------------------------- # + # 5. Google Docs — no post-mortem doc yet + # ----------------------------------------------------------------- # + states["docs"] = { + "currentUser": { + "id": "user-1", "name": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + "avatar": "https://picsum.photos/100/100?random=user1", + }, + "users": [ + {"id": "user-1", "name": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + "avatar": "https://picsum.photos/100/100?random=user1"}, + ], + "documents": {}, + "comments": [], + "ui": { + "currentDocId": None, + "sidebarOpen": False, + "sidebarTab": "comments", + "shareDialogOpen": False, + "findReplaceOpen": False, + "viewMode": "editing", + "zoom": 100, + "documentListView": "grid", + "searchQuery": "", + }, + } + + # ----------------------------------------------------------------- # + # 6. Slack — #marketing readable/writable, no learnings message + # ----------------------------------------------------------------- # + states["slack"] = { + "currentUser": { + "userId": "user_1", + "fullName": "Marketing Campaign Mgmt", + "displayName": "Marketing", + "email": "marketing@northwindcloud.com", + "avatar": "https://picsum.photos/200/200?random=1", + "status": "active", + "statusMessage": "", + "statusEmoji": "", + "timeZone": "America/New_York", + }, + "workspace": {"workspaceId": "ws_1", "workspaceName": "Northwind Cloud", "icon": ""}, + "users": [ + {"userId": "user_1", "fullName": "Marketing Campaign Mgmt", "displayName": "Marketing", + "email": "marketing@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=1", + "title": "Campaign Manager", "status": "active", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/New_York"}, + {"userId": "user_2", "fullName": "Sales Ops", "displayName": "Sales Ops", + "email": "sales-ops@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=2", + "title": "Sales Operations", "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"], + "createdBy": "user_1", "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0}, + {"channelId": "marketing", "name": "marketing", "description": "Marketing team channel", + "topic": "Campaigns and growth", "isPrivate": False, "isStarred": False, + "members": ["user_1", "user_2"], "createdBy": "user_1", "createdAt": "2026-01-01T10:00:00Z", + "pinnedMessages": [], "unreadCount": 0}, + ], + "messages": { + "general": [ + {"messageId": "msg_seed_1", "senderId": "user_1", + "content": "Welcome to the Northwind Cloud workspace.", "timestamp": "2026-06-30T09:00:00Z", + "threadId": None, "reactions": [], "attachments": [], "isEdited": False}, + ], + "marketing": [ + {"messageId": "msg_seed_2", "senderId": "user_1", + "content": "Q2 is wrapping up — will post the webinar post-mortem here once ready.", + "timestamp": "2026-07-01T15: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": [], + } + + # ----------------------------------------------------------------- # + # 7. Gmail — campaign manager's account, no handoff sent + # ----------------------------------------------------------------- # + states["gmail"] = { + "user": { + "userId": "u1", "username": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + "avatar": "https://picsum.photos/100/100?random=user1", + }, + "emails": [ + { + "id": "email_seed_1", + "threadId": "thread_seed_1", + "from": {"name": "Sales Ops", "email": "sales-ops@northwindcloud.com"}, + "to": [{"name": "Marketing Campaign Mgmt", "email": "marketing@northwindcloud.com"}], + "subject": "Re: Q2 campaign closeout readiness", + "body": "

Let us know when the Q2 webinar leads are ready for handoff.

", + "timestamp": "2026-07-01T11:00:00Z", + "read": False, "starred": False, "important": False, + "labels": [], "category": "primary", "folder": "inbox", "attachments": [], + }, + { + "id": "email_seed_2", + "threadId": "thread_seed_2", + "from": {"name": "HubSpot", "email": "noreply@hubspot.com"}, + "to": [{"name": "Marketing Campaign Mgmt", "email": "marketing@northwindcloud.com"}], + "subject": "Your Q2 Webinar Series performance summary", + "body": "

MQLs: 540, Open Rate: 41.2%, Conversion: 6.3%.

", + "timestamp": "2026-07-02T08:00:00Z", + "read": True, "starred": False, "important": True, + "labels": [], "category": "primary", "folder": "inbox", "attachments": [], + }, + ], + "labels": [ + {"id": "l1", "name": "Work", "color": "#ef4444"}, + {"id": "l2", "name": "Campaigns", "color": "#3b82f6"}, + ], + "drafts": [], + } + + # ----------------------------------------------------------------- # + # 8. Google Calendar — no retro event + # ----------------------------------------------------------------- # + states["calendar"] = { + "user": { + "id": "u1", "username": "Marketing Campaign Mgmt", + "email": "marketing@northwindcloud.com", + "avatar": "https://picsum.photos/100/100?random=user1", + }, + "calendars": [ + {"id": "c1", "name": "Marketing", "color": "#039BE5", "visible": True, + "userId": "u1", "isDefault": True}, + {"id": "c2", "name": "Team", "color": "#33B679", "visible": True, + "userId": "u1", "isDefault": False}, + ], + "events": [ + { + "id": "evt_seed_1", + "calendarId": "c1", + "title": "Weekly Marketing Sync", + "start": "2026-07-06T10:00:00.000Z", + "end": "2026-07-06T10:30:00.000Z", + "allDay": False, "location": "Zoom", + "description": "Standup with the marketing team.", + "guests": ["marketing@northwindcloud.com"], + "color": "#039BE5", "recurring": "weekly", + "reminders": [{"type": "popup", "minutes": 5}], "meetLink": "", "status": "confirmed", + }, + ], + "view": "week", + "currentDate": "2026-07-02T00:00:00.000Z", + "sidebarOpen": True, + "settings": { + "weekStart": 0, "defaultDuration": 60, "defaultView": "week", + "defaultReminder": {"type": "popup", "minutes": 10}, "timeFormat": "12h", + "showWeekNumbers": False, "showDeclinedEvents": False, + }, + } + + return states + + +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 kill_chrome(): + """Kill any running chrome so the client cannot re-merge default state + into the server's current_state after we inject.""" + subprocess.run(["pkill", "-f", "google-chrome"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + time.sleep(1.0) + + +def wait_for_mocks_loaded(mocks, sid, timeout=90.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) — blank/stuck loading') + print(f'[{name}] rendered OK ({len(html)} bytes)') + finally: + page.close() + finally: + browser.close() + + +def main(): + sid = str(uuid.uuid4()) + with open(SID_FILE, "w") as f: + f.write(sid) + + states = build_states() + + # Launch a Chrome window for EVERY mock the task touches FIRST, so the + # environment appears GUI-ready. Then kill Chrome so the client cannot + # re-merge its built-in default state into the server's current_state after + # we inject (the mock client re-POSTs state on load, which would otherwise + # clobber our injected values). The agent launches its own browser later. + for name, url in MOCKS.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.4) + + # Give Chrome a moment to load each mock. + time.sleep(6.0) + kill_chrome() + + for name, url in MOCKS.items(): + # reset first so any prior client-set state is cleared, then set our + # clean initial state (this guarantees initial_state == our injected + # state even if a Chrome client established defaults earlier). + requests.post(f'{url}/post?sid={sid}', + json={"action": "reset"}, timeout=30) + 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}' + + # Kill chrome again to be safe, then re-assert current_state with a final + # set_current so any in-flight client saveState cannot clobber it. + kill_chrome() + time.sleep(2.0) + for name, url in MOCKS.items(): + requests.post( + f'{url}/post?sid={sid}', + json={"action": "set_current", "state": states[name]}, + timeout=30, + ) + + # Final normalization: some mocks enrich/normalize the state server-side + # (e.g. monday injects default users/currentUserId). To guarantee + # initial_state == current_state on the seeded (pre-task) environment, we + # re-read the current_state the server actually produced and write it back + # via `set` (which sets initial_state = current_state = that exact object). + for name, url in MOCKS.items(): + cur = requests.get(f'{url}/go?sid={sid}', timeout=10).json()['current_state'] + requests.post(f'{url}/post?sid={sid}', + json={"action": "reset"}, timeout=30) + resp = requests.post(f'{url}/post?sid={sid}', + json={"action": "set", "state": cur}, + timeout=30) + assert resp.status_code == 200, f'{name} final set failed: {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go['current_state'] == go['initial_state'], \ + f'{name} final current != initial' + print(f'Injected + finalized: {name} (sid={sid})') + + print(f'GUI_READY: all {len(MOCKS)} mocks seeded (sid={sid})') + + +if __name__ == "__main__": + main() diff --git a/legacy/prof16_postmortem_003/reward.py b/legacy/prof16_postmortem_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec8818b00f6f639533ff4f202c7d4d19f380a0a --- /dev/null +++ b/legacy/prof16_postmortem_003/reward.py @@ -0,0 +1,366 @@ +""" +Reward Script: Marketing Campaign Manager Q2 Webinar Series post-mortem closeout +Task ID: prof16_postmortem_003 +Domain: mock_websites (8 mocks: HubSpot, Google Sheets, Airtable, Monday, + Google Docs, Slack, Gmail, Google Calendar) +Scoring: 8 independent components, progressive 0.0-1.0, one per task step. +All checks read LIVE mock state on the VM via HTTP /go?sid=. +""" +import json +import sys +import urllib.request + +# --- Mock endpoint map (from task_config.json canonical URLs) --- +BASE = 'http://28.7.186.212' +PORTS = { + 'hubspot': 8170, + 'sheets': 8165, + 'airtable': 8129, + 'monday': 8185, + 'docs': 8162, + 'slack': 8198, + 'gmail': 8158, + 'calendar': 8161, +} + +SID = None +_STATES = {} + + +def _load_sid(): + """Read the session id written by initial_setup.py. Fail early if missing.""" + global SID + try: + with open('/tmp/task_web_sid') as f: + SID = f.read().strip() + if not SID: + raise ValueError('sid is empty') + except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +def _fetch(name): + """Fetch current_state for a mock by name. Returns dict or None on error.""" + if name in _STATES: + return _STATES[name] + port = PORTS[name] + try: + url = f'{BASE}:{port}/go?sid={SID}' + with urllib.request.urlopen(url, timeout=20) as r: + data = json.loads(r.read()) + cur = data.get('current_state') or {} + _STATES[name] = cur + return cur + except Exception as e: + print(f'ERROR: Cannot fetch {name} (port {port}): {e}') + return None + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, "name": name, "weight": float(weight), + "passed": bool(passed), "score": float(score), + "detail": detail, "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +def _norm(s): + """Normalize a string: lowercase, collapse whitespace, strip punctuation-ish.""" + if s is None: + return '' + return ' '.join(str(s).lower().split()) + + +# --------------------------------------------------------------------------- +# Per-component checks — each scores a task-introduced change. +# --------------------------------------------------------------------------- + +def check_sheets_row4(): + """Google Sheets 'Performance' row 4 populated with the Q2 Webinar Series data. + Pass condition: A4='Q2 Webinar Series', B4=540, C4='41.2%', D4='6.3%', E4='HubSpot' + AND rows 2-3 unchanged (A2/A3 still present).""" + cur = _fetch('sheets') + if not cur: + return False, 0.0, 'sheets state unavailable' + sheets = cur.get('sheets', []) + perf = next((s for s in sheets if s.get('name') == 'Performance' + or s.get('id') == 'sheet_performance'), None) + if not perf: + return False, 0.0, 'Performance sheet not found' + data = perf.get('data', {}) + a4 = data.get('A4', {}).get('value') + b4 = data.get('B4', {}).get('value') + c4 = data.get('C4', {}).get('value') + d4 = data.get('D4', {}).get('value') + e4 = data.get('E4', {}).get('value') + # rows 2-3 must still be there (precondition anchor that the append happened, not overwrite) + a2 = data.get('A2', {}).get('value') + a3 = data.get('A3', {}).get('value') + ok = (a4 == 'Q2 Webinar Series' and str(b4) == '540' + and _norm(c4) == '41.2%' and _norm(d4) == '6.3%' + and _norm(e4) == 'hubspot' and a2 and a3) + if ok: + return True, 0.12, f'A4={a4} B4={b4} C4={c4} D4={d4} E4={e4} (rows 2-3 intact)' + return False, 0.0, f'A4={a4!r} B4={b4!r} C4={c4!r} D4={d4!r} E4={e4!r} A2={a2!r} A3={a3!r}' + + +def check_airtable_record(): + """Airtable 'Campaigns' record 'Q2 Webinar Series' Status='Closed' and + Notes='Top channel: LinkedIn; replay drove 22% of MQLs.'. + Pass condition: matching record has fld_status=='Closed' and notes substring match.""" + cur = _fetch('airtable') + if not cur: + return False, 0.0, 'airtable state unavailable' + tables = cur.get('tables', {}) + tbl = tables.get('tbl_campaigns') or next( + (t for t in tables.values() if t.get('name') == 'Campaigns'), None) + if not tbl: + return False, 0.0, 'Campaigns table not found' + rec = None + for r in tbl.get('records', []): + if _norm(r.get('fields', {}).get('fld_name')) == 'q2 webinar series': + rec = r + break + if not rec: + return False, 0.0, 'Q2 Webinar Series record not found' + status = rec.get('fields', {}).get('fld_status') + notes = rec.get('fields', {}).get('fld_notes', '') or '' + if _norm(status) == 'closed' and 'top channel: linkedin' in _norm(notes) \ + and 'replay drove 22% of mqls' in _norm(notes): + return True, 0.10, f'status={status!r} notes={notes!r}' + return False, 0.0, f'status={status!r} notes={notes!r}' + + +def _monday_boards(cur): + """Return list of board objects regardless of top-level vs nested layout.""" + boards = cur.get('boards') + if isinstance(boards, list): + return boards + if isinstance(boards, dict): + return list(boards.values()) + return [] + + +def _monday_items(cur): + """Collect all items from board-nested 'items' AND top-level 'items'.""" + items = [] + for b in _monday_boards(cur): + items.extend(b.get('items', [])) + top = cur.get('items') + if isinstance(top, dict): + items.extend(top.values()) + elif isinstance(top, list): + items.extend(top) + return items + + +def check_monday_closeout(): + """Monday 'Campaign Closeout' board has item 'Q2 Webinar Series — Closeout' in the + 'Done' group, with a sub-task 'Hand leads to Sales' assigned to Sales Ops due 2026-07-10. + Pass condition: item name match, group title 'Done', subtask name+assignee+due match.""" + cur = _fetch('monday') + if not cur: + return False, 0.0, 'monday state unavailable' + # find the closeout item + target = None + for it in _monday_items(cur): + if _norm(it.get('name')) == 'q2 webinar series — closeout': + target = it + break + if not target: + return False, 0.0, 'closeout item not found' + # group must be the 'Done' group. Group definitions live nested inside each + # board's 'groups' list (the top-level 'groups' dict only holds defaults). + gid = target.get('groupId') + gtitle = None + for b in _monday_boards(cur): + for g in b.get('groups', []): + if g.get('id') == gid: + gtitle = g.get('title') + break + if gtitle: + break + if _norm(gtitle) != 'done': + return False, 0.0, f'item in group {gtitle!r} (expected Done)' + # sub-task check + subs = target.get('subitems', []) or target.get('subitemIds', []) or [] + # subitems may be objects or ids; if ids, resolve against cur.get('subitems') + sub_objs = [] + for s in subs: + if isinstance(s, dict): + sub_objs.append(s) + else: + submap = cur.get('subitems') + if isinstance(submap, dict) and s in submap: + sub_objs.append(submap[s]) + hit = None + for s in sub_objs: + if _norm(s.get('name')) == 'hand leads to sales': + hit = s + break + if not hit: + return False, 0.0, f'no sub-task named "Hand leads to Sales" (subs={[s.get("name") for s in sub_objs]})' + assignee = hit.get('assignee', '') + due = hit.get('due', '') + if _norm(assignee) == 'sales ops' and str(due) == '2026-07-10': + return True, 0.14, f'item in Done group; subtask assignee={assignee!r} due={due!r}' + return False, 0.0, f'subtask assignee={assignee!r} due={due!r} (expected Sales Ops / 2026-07-10)' + + +def check_docs_title(): + """Google Docs has a document titled 'Q2 Webinar Series — Post-Mortem' with H1 heading. + Pass condition: a document whose title normalized matches and content starts with

...Post-Mortem.""" + cur = _fetch('docs') + if not cur: + return False, 0.0, 'docs state unavailable' + docs = cur.get('documents', {}) + if isinstance(docs, list): + docs = {d.get('id'): d for d in docs} + for d in docs.values(): + title = d.get('title', '') + content = d.get('content', '') or '' + if _norm(title) == 'q2 webinar series — post-mortem' and '

' in content \ + and 'post-mortem' in _norm(content[:200]): + return True, 0.08, f'title={title!r}' + return False, 0.0, 'no doc titled "Q2 Webinar Series — Post-Mortem"' + + +def check_docs_sections(): + """The post-mortem doc contains the Results line, the 3 numbered learnings, and the + Recommendations sentence. + Pass condition: content contains the exact metrics line, 'Top 3 Learnings', three 'N)' + items with the specific learnings, and the Recommendations sentence.""" + cur = _fetch('docs') + if not cur: + return False, 0.0, 'docs state unavailable' + docs = cur.get('documents', {}) + if isinstance(docs, list): + docs = {d.get('id'): d for d in docs} + target = None + for d in docs.values(): + if _norm(d.get('title')) == 'q2 webinar series — post-mortem': + target = d + break + if not target: + return False, 0.0, 'post-mortem doc not found' + c = _norm(target.get('content', '')) + results_ok = ('540 mqls' in c and '41.2% open rate' in c and '6.3% conversion' in c + and '842 attendees' in c and '1290 registrants' in c) + learn_ok = ('top 3 learnings' in c and 'linkedin was the highest-quality channel' in c + and 'on-demand replay drove 22% of total mqls' in c + and '10am' in c and 'open rate' in c and '5pts' in c) + rec_ok = ('repeat the webinar format in q3' in c and 'shift 15% of budget to linkedin' in c + and 'publish replay within 24h' in c) + if results_ok and learn_ok and rec_ok: + return True, 0.10, 'Results + Top 3 Learnings + Recommendations all present' + return False, 0.0, f'results_ok={results_ok} learn_ok={learn_ok} rec_ok={rec_ok}' + + +def check_slack_message(): + """Slack #marketing has a new message containing the 3 learnings and a link to the doc. + Pass condition: a marketing message whose content has the 3 learnings and a doc URL.""" + cur = _fetch('slack') + if not cur: + return False, 0.0, 'slack state unavailable' + msgs = cur.get('messages', {}) + mkt = msgs.get('marketing', []) if isinstance(msgs, dict) else [] + for m in mkt: + c = _norm(m.get('content', '')) + has_learnings = ('top 3 learnings' in c and 'linkedin was the highest-quality' in c + and 'on-demand replay drove 22% of mqls' in c and '10am' in c + and '5pts' in c) + has_link = '8162' in (m.get('content', '')) and 'doc-q2-webinar-postmortem' in (m.get('content', '')) + if has_learnings and has_link: + return True, 0.16, 'marketing message with 3 learnings + doc link found' + return False, 0.0, 'no marketing message with 3 learnings + doc link' + + +def check_gmail_handoff(): + """Gmail has a sent email to sales-ops@northwindcloud.com, subject + 'Q2 Webinar Series — Lead Handoff', with the exact body and doc link. + Pass condition: a sent email to that recipient, correct subject, body has 540 MQLs + and the doc link.""" + cur = _fetch('gmail') + if not cur: + return False, 0.0, 'gmail state unavailable' + for e in cur.get('emails', []): + if e.get('folder') != 'sent': + continue + tos = [t.get('email', '').lower() for t in e.get('to', [])] + if 'sales-ops@northwindcloud.com' not in tos: + continue + subj = _norm(e.get('subject')) + if subj != 'q2 webinar series — lead handoff': + continue + body = _norm(e.get('body', '')) + has_mqls = '540 mqls' in body and 'monday closeout item' in body + has_link = 'doc-q2-webinar-postmortem' in (e.get('body', '')) + if has_mqls and has_link: + return True, 0.15, 'sent handoff email to sales-ops with body + doc link' + return False, 0.0, 'no matching sent handoff email' + + +def check_calendar_event(): + """Google Calendar has event 'Q2 Webinar Series Retro' on 2026-07-09 14:00-14:30, + inviting the marketing team, description 'Review post-mortem and Q3 plan.'. + Pass condition: event title match, start/end window, 'marketing' in guests, exact desc.""" + cur = _fetch('calendar') + if not cur: + return False, 0.0, 'calendar state unavailable' + for ev in cur.get('events', []): + if _norm(ev.get('title')) != 'q2 webinar series retro': + continue + start = ev.get('start', '') + end = ev.get('end', '') + if start != '2026-07-09T14:00:00.000Z' or end != '2026-07-09T14:30:00.000Z': + return False, 0.0, f'time mismatch start={start} end={end}' + guests = [g.lower() for g in ev.get('guests', [])] + has_marketing = any('marketing' in g for g in guests) + desc = _norm(ev.get('description')) + if has_marketing and desc == 'review post-mortem and q3 plan.': + return True, 0.15, f'event 14:00-14:30, marketing invited, correct desc' + return False, 0.0, f'guests={guests} desc={ev.get("description")!r}' + return False, 0.0, 'no Q2 Webinar Series Retro event' + + +def verify_task(): + """Verify all 8 post-mortem closeout steps. Returns float 0.0-1.0.""" + total = 0.0 + for idx, name, weight, fn in [ + (1, 'Sheets Performance row 4', 0.12, check_sheets_row4), + (2, 'Airtable record Closed + Notes', 0.10, check_airtable_record), + (3, 'Monday closeout item + subtask', 0.14, check_monday_closeout), + (4, 'Docs title + H1', 0.08, check_docs_title), + (5, 'Docs Results/Learnings/Recs', 0.10, check_docs_sections), + (6, 'Slack #marketing learnings msg', 0.16, check_slack_message), + (7, 'Gmail handoff email', 0.15, check_gmail_handoff), + (8, 'Calendar Retro event', 0.15, check_calendar_event), + ]: + _, score, _ = _run_component(idx, name, weight, fn, ()) + total += score + final = round(min(total, 1.0), 4) + print(f'\nScore: {total}/1.0') + print(f'REWARD: {final}') + return final + + +if __name__ == '__main__': + _load_sid() + verify_task() diff --git a/legacy/prof16_postmortem_003/reward_label.json b/legacy/prof16_postmortem_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..5b0f91689ae6edc86c7b46c4e99954229e925794 --- /dev/null +++ b/legacy/prof16_postmortem_003/reward_label.json @@ -0,0 +1,99 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof16_postmortem_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:17", + "label": { + "task_id": "prof16_postmortem_003", + "domain": "mock_websites", + "summary": "验证营销战役 Q2 网络研讨会事后总结在 8 个模拟 Web 应用中的 8 个独立操作步骤是否完成", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "sheets_mock", + "airtable_mock", + "monday_mock", + "docs_mock", + "slack_mock", + "gmail_mock", + "calendar_mock" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.12, + "description": "Google Sheets Performance 工作表第 4 行填入 Q2 Webinar Series 数据且未覆盖原有行", + "check_logic": "从 sheets_mock 获取状态,定位 Performance 工作表,读取 A4-E4 单元格值,验证 A4='Q2 Webinar Series'、B4='540'、C4='41.2%'、D4='6.3%'、E4='HubSpot',同时确认 A2 和 A3 仍存在(防止覆盖原有数据)", + "pass_condition": "A4-E4 完全匹配指定值且 A2、A3 非空" + }, + { + "name": "Component 2", + "weight": 0.1, + "description": "Airtable Campaigns 记录状态设为 Closed 并填写 Notes", + "check_logic": "从 airtable_mock 获取状态,定位 Campaigns 表,查找 fld_name 归一化后为 'q2 webinar series' 的记录,验证 fld_status 归一化后为 'closed',且 fld_notes 归一化后同时包含 'top channel: linkedin' 和 'replay drove 22% of mqls'", + "pass_condition": "存在匹配记录,状态为 Closed,Notes 包含指定两句话" + }, + { + "name": "Component 3", + "weight": 0.14, + "description": "Monday 创建 Closeout 项目并置于 Done 分组,附带指定子任务", + "check_logic": "从 monday_mock 获取状态,遍历所有 items 查找 name 归一化后为 'q2 webinar series — closeout' 的项目;确认其所在 group 的 title 归一化后为 'done';检查其子任务(支持 subitems 对象列表或 subitemIds 解析)中是否存在 name 归一化后为 'hand leads to sales' 的项,且该项 assignee 归一化后为 'sales ops'、due 等于 '2026-07-10'", + "pass_condition": "Closeout 项目位于 Done 分组,且包含指定名称、负责人和截止日期的子任务" + }, + { + "name": "Component 4", + "weight": 0.08, + "description": "Google Docs 创建指定标题的事后总结文档并包含 H1 标题", + "check_logic": "从 docs_mock 获取状态,遍历所有文档,查找 title 归一化后为 'q2 webinar series — post-mortem' 的文档,并验证其 content 包含 '

' 标签且前 200 字符内包含 'post-mortem'", + "pass_condition": "存在标题匹配的文档且内容以 H1 标题开头" + }, + { + "name": "Component 5", + "weight": 0.1, + "description": "事后总结文档包含 Results 指标、3 条 Learnings 和 Recommendations", + "check_logic": "从 docs_mock 获取状态,定位事后总结文档,将 content 归一化后检查三组文本:Results 行必须包含 '540 mqls'、'41.2% open rate'、'6.3% conversion'、'842 attendees'、'1290 registrants';Top 3 Learnings 必须包含 'top 3 learnings'、'linkedin was the highest-quality channel'、'on-demand replay drove 22% of total mqls'、'10am'、'open rate'、'5pts';Recommendations 必须包含 'repeat the webinar format in q3'、'shift 15% of budget to linkedin'、'publish replay within 24h'", + "pass_condition": "文档内容同时包含 Results 指标、三项 Learnings 和三项 Recommendations 的指定关键词" + }, + { + "name": "Component 6", + "weight": 0.16, + "description": "Slack #marketing 频道发送包含 3 条 learnings 和文档链接的消息", + "check_logic": "从 slack_mock 获取状态,读取 #marketing 频道消息,查找一条消息:归一化内容包含 'top 3 learnings'、'linkedin was the highest-quality'、'on-demand replay drove 22% of mqls'、'10am'、'5pts';且原始内容同时包含 '8162' 和 'doc-q2-webinar-postmortem'", + "pass_condition": "#marketing 频道存在同时包含 3 条 learnings 和文档链接的消息" + }, + { + "name": "Component 7", + "weight": 0.15, + "description": "Gmail 发送给 Sales Ops 的线索移交邮件包含指定正文和文档链接", + "check_logic": "从 gmail_mock 获取状态,遍历 sent 文件夹邮件,筛选收件人包含 'sales-ops@northwindcloud.com' 且 subject 归一化后为 'q2 webinar series — lead handoff' 的邮件;验证归一化正文包含 '540 mqls' 和 'monday closeout item',且原始正文包含 'doc-q2-webinar-postmortem'", + "pass_condition": "发件箱存在发给指定收件人、主题正确、正文包含 MQLs 和文档链接的邮件" + }, + { + "name": "Component 8", + "weight": 0.15, + "description": "Google Calendar 创建指定时间的 Retro 会议并邀请营销团队", + "check_logic": "从 calendar_mock 获取状态,查找 title 归一化后为 'q2 webinar series retro' 的事件;验证 start 为 '2026-07-09T14:00:00.000Z' 且 end 为 '2026-07-09T14:30:00.000Z';guests 列表中至少有一项包含 'marketing';description 归一化后为 'review post-mortem and q3 plan.'", + "pass_condition": "存在指定标题、时间段、包含 marketing 嘉宾且描述正确的日历事件" + } + ], + "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) 提前退出", + "模拟服务 HTTP 请求失败或返回 None:对应组件直接返回 0 分", + "组件检查函数抛出未捕获异常:被 _run_component 捕获后该组件记为 0 分", + "Google Sheets 中 Performance 工作表缺失、A4-E4 数据不匹配或 A2/A3 行丢失", + "Airtable 中 Campaigns 表或 Q2 Webinar Series 记录缺失、状态非 Closed、Notes 字段缺少指定子串", + "Monday 中 Closeout 项目缺失、不在 Done 分组、子任务名称/负责人/截止日期不匹配", + "Google Docs 中事后总结文档标题或 H1 缺失", + "Google Docs 内容缺少 Results 指标、Top 3 Learnings 或 Recommendations 指定文本", + "Slack #marketing 频道消息缺少 3 条 learnings 或文档链接", + "Gmail 发件箱缺少发给 sales-ops@northwindcloud.com 的指定主题邮件、正文缺少 540 MQLs 或文档链接", + "Google Calendar 缺少指定标题/时间/描述/嘉宾的 Retro 会议" + ], + "scoring_logic_explanation": "脚本首先通过 _load_sid() 从 /tmp/task_web_sid 读取会话 ID,若失败则直接输出 REWARD: 0.0 并退出。随后 verify_task() 按顺序执行 8 个独立评分组件。每个组件通过 _fetch() 向对应的模拟服务(Google Sheets、Airtable、Monday、Google Docs、Slack、Gmail、Google Calendar)发送 HTTP 请求获取实时状态,并依据特定业务规则验证数据内容。各组件使用 _run_component() 执行,捕获异常并输出 PASS/FAIL 及结构化 COMPONENT 日志。每个通过检查的组件累加其固定权重分数(0.12、0.10、0.14、0.08、0.10、0.16、0.15、0.15),最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后返回。任一组件失败仅导致该组件得 0 分,不会中断后续组件检查。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. **Task ID**: prof16_postmortem_003(从 docstring 中提取)\n2. **Domain**: mock_websites(从 docstring 中提取)\n3. **Summary**: 这是一个营销战役管理 Q2 网络研讨会系列事后总结收尾任务的评分脚本,检查 8 个独立组件。\n4. **is_placeholder**: false,因为脚本真正检查了多个 mock 服务的状态。\n5. **data_sources**: \n - /tmp/task_web_sid(读取 session id)\n - hubspot (port 8170) - 虽然代码中有定义,但实际检查中似乎没有用到?等等,PORTS 里有 hubspot,但检查函数里没有调用 _fetch('hubspot')。不过 data_sources 应该列出脚本从中获取状态的数据源。脚本定义了这些端口,但实际获取的是 sheets, airtable, monday, docs, slack, gmail, calendar。hubspot 在 PORTS 中定义但没有在检查中使用。我应该列出实际被获取的,还是所有定义的?题目说\"脚本从哪些数据源/mock 服务/文件获取状态\"。既然 hubspot 没有被 fetch,就不应该列?但 PORTS 里定义了。让我再看看检查函数:\n - check_sheets_row4: _fetch('sheets')\n - check_airtable_record: _fetch('airtable')\n - check_monday_closeout: _fetch('monday')\n - check_docs_title: _fetch('docs')\n - check_docs_sections: _fetch('docs')\n - check_slack_message: _fetch('slack')\n - check_gmail_handoff: _fetch('gmail')\n - check_calendar_event: _fetch('calendar')\n 所以实际获取的是:sheets, airtable, monday, docs, slack, gmail, calendar。还有 /tmp/task_web_sid。\n 但是 docstring 说 \"8 mocks: HubSpot, Google Sheets, Airtable, Monday, Google Docs, Slack, Gmail, Google Calendar\"。虽然 hubspot 没用到,但 PORTS 里定义了。data_sources 应该列出脚本获取状态的地方。我会列出实际被获取的 mock 服务和 sid 文件。\n\n6. **scoring_components**: 8 个组件,权重在 verify_task 中明确定义:\n - Component 1: Sheets Performance row 4, weight 0.12\n - Component 2: Airtable record Closed + Notes, weight 0.10\n - Component 3: Monday closeout item + subtask, weight 0.14\n - Component 4: Docs title + H1, weight 0.08\n - Component 5: Docs Results/Learnings/Recs, weight 0.10\n - Component 6: Slack #marketing learnings msg, weight 0.16\n - Component 7: Gmail handoff email, weight 0.15\n - Component 8: Calendar Retro event, weight 0.15\n\n 让我详细描述每个组件的检查逻辑和通过条件:\n\n **Component 1**: check_sheets_row4\n - 获取 sheets 状态\n - 找到 Performance sheet\n - 检查 A4='Q2 Webinar Series', B4=540, C4='41.2%', D4='6.3%', E4='HubSpot'\n - 检查 A2 和 A3 仍然存在(未被覆盖)\n - 通过则返回 True, 0.12\n\n **Component 2**: check_airtable_record\n - 获取 airtable 状态\n - 找到 Campaigns 表(tbl_campaigns 或 name=='Campaigns')\n - 找到 fld_name 为 'Q2 Webinar Series' 的记录\n - 检查 fld_status 为 'Closed'\n - 检查 fld_notes 包含 'top channel: linkedin' 和 'replay drove 22% of mqls'\n - 通过则返回 True, 0.10\n\n **Component 3**: check_monday_closeout\n - 获取 monday 状态\n - 找到 name 为 'Q2 Webinar Series — Closeout' 的 item\n - 检查该 item 所在 group 的 title 为 'Done'\n - 检查 sub-task 中有 name 为 'Hand leads to Sales' 的项\n - 检查该 sub-task assignee 为 'Sales Ops',due 为 '2026-07-10'\n - 通过则返回 True, 0.14\n\n **Component 4**: check_docs_title\n - 获取 docs 状态\n - 找到 title normalized 为 'q2 webinar series — post-mortem' 的文档\n - 检查 content 包含 '

' 且前 200 字符内包含 'post-mortem'\n - 通过则返回 True, 0.08\n\n **Component 5**: check_docs_sections\n - 获取 docs 状态\n - 找到 post-mortem 文档\n - 检查 content 包含:\n - Results: '540 mqls', '41.2% open rate', '6.3% conversion', '842 attendees', '1290 registrants'\n - Learnings: 'top 3 learnings', 'linkedin was the highest-quality channel', 'on-demand replay drove 22% of total mqls', '10am', 'open rate', '5pts'\n - Recommendations: 'repeat the webinar format in q3', 'shift 15% of budget to linkedin', 'publish replay within 24h'\n - 通过则返回 True, 0.10\n\n **Component 6**: check_slack_message\n - 获取 slack 状态\n - 检查 #marketing 频道消息\n - 消息内容包含 3 个 learnings('top 3 learnings', 'linkedin was the highest-quality', 'on-demand replay drove 22% of mqls', '10am', '5pts')\n - 消息内容包含 doc 链接('8162' 和 'doc-q2-webinar-postmortem')\n - 通过则返回 True, 0.16\n\n **Component 7**: check_gmail_handoff\n - 获取 gmail 状态\n - 找到 sent 文件夹的邮件\n - 收件人包含 'sales-ops@northwindcloud.com'\n - subject normalized 为 'q2 webinar series — lead handoff'\n - body 包含 '540 mqls' 和 'monday closeout item'\n - body 包含 'doc-q2-webinar-postmortem'\n - 通过则返回 True, 0.15\n\n **Component 8**: check_calendar_event\n - 获取 calendar 状态\n - 找到 title normalized 为 'q2 webinar series retro' 的事件\n - start 为 '2026-07-09T14:00:00.000Z',end 为 '2026-07-09T14:30:00.000Z'\n - guests 中有包含 'marketing' 的项\n - description normalized 为 'review post-mortem and q3 plan.'\n - 通过则返回 True, 0.15\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后取 min(total, 1.0) 并四舍五入到 4 位小数。权重总和 = 0.12+0.10+0.14+0.08+0.10+0.16+0.15+0.15 = 1.00。所以是累加后钳制到 1.0。\n9. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL,输出 REWARD: 0.0,sys.exit(0)\n - 任何 mock 状态获取失败(_fetch 返回 None):对应组件返回 False, 0.0\n - 各组件内部检查失败:返回 False, 0.0\n - 注意:一个组件失败不会导致提前退出,会继续检查其他组件。只有 sid 读取失败会提前退出。\n - 另外,_run_component 中如果 fn 抛出异常,会捕获并返回 False, 0.0\n\n10. **scoring_logic_explanation**: \n - 首先 _load_sid() 从 /tmp/task_web_sid 读取 session ID,失败则直接退出并返回 0.0。\n - verify_task() 依次执行 8 个独立组件检查。\n - 每个组件通过 _fetch() 从对应的 mock 服务(通过 HTTP /go?sid=)获取实时状态。\n - 每个组件有独立的检查函数,验证特定的业务规则和数据内容。\n - 每个组件通过 _run_component 执行,输出 PASS/FAIL 和 COMPONENT JSON 行。\n - 各组件得分按权重累加到 total。\n - 最后计算 final = round(min(total, 1.0), 4),打印 Score 和 REWARD。\n - 因为权重总和为 1.0,通常不需要钳制,但作为安全措施仍有 min 操作。\n\n11. **confidence**: 1.0(源码完整,逻辑清晰)\n\n让我再检查一下权重总和:0.12+0.10=0.22, +0.14=0.36, +0.08=0.44, +0.10=0.54, +0.16=0.70, +0.15=0.85, +0.15=1.00。是的,正好 1.0。\n\n关于 data_sources,我应该列出:\n- /tmp/task_web_sid\n- sheets_mock (port 8165)\n- airtable_mock (port 8129)\n- monday_mock (port 8185)\n- docs_mock (port 8162)\n- slack_mock (port 8198)\n- gmail_mock (port 8158)\n- calendar_mock (port 8161)\n\n或者直接用代码中的名字:sheets, airtable, monday, docs, slack, gmail, calendar。题目示例用了 slack_mock、github_mock 等。我会用代码中的 key 名,或者加上 _mock。看示例:\"如 slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid 等\"。我会用代码中的名字对应的服务名,比如 google_sheets_mock、airtable_mock 等,或者直接 sheets、airtable。为了符合示例风格,我用 \"sheets_mock\"、\"airtable_mock\" 等,并保留 /tmp/task_web_sid。\n\n等等,PORTS 里定义了 hubspot 但没用到。data_sources 只应包含实际获取的。我会列出实际获取的。\n\n再仔细看 check_docs_title 和 check_docs_sections:它们都 fetch docs,但 _STATES 有缓存,所以第二次不会重复 HTTP 请求。\n\n再仔细看 check_monday_closeout 的 sub-task 检查:\n```python\nsubs = target.get('subitems', []) or target.get('subitemIds', []) or []\nsub_objs = []\nfor s in subs:\n if isinstance(s, dict):\n sub_objs.append(s)\n else:\n submap = cur.get('subitems')\n if isinstance(submap, dict) and s in submap:\n sub_objs.append(submap[s])\n```\n这里检查 sub-task name 为 'hand leads to sales',assignee 为 'sales ops',due 为 '2026-07-10'。\n\ncheck_calendar_event 中,如果时间不匹配,会直接 return False, 0.0,而不是继续搜索其他事件。这是值得注意的逻辑。\n\ncheck_gmail_handoff 中,has_link 检查的是原始 body(未 normalized)包含 'doc-q2-webinar-postmortem',而 has_mqls 检查的是 normalized body。这也是细节。\n\n现在构建 JSON。确保:\n- 只输出 JSON,没有 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- 不要额外解释\n\n让我组织中文描述:\n\nsummary: \"验证营销战役 Q2 网络研讨会事后总结在 8 个模拟 Web 应用中的 8 个独立操作步骤是否完成\"\n\nscoring_logic_explanation: \"脚本首先通过 _load_sid() 从 /tmp/task_web_sid 读取会话 ID,若失败则直接输出 REWARD: 0.0 并退出。随后 verify_task() 按顺序执行 8 个独立评分组件。每个组件通过 _fetch() 向对应的模拟服务(Google Sheets、Airtable、Monday、Google Docs、Slack、Gmail、Google Calendar)发送 HTTP 请求获取实时状态,并依据特定业务规则验证数据内容。各组件使用 _run_component() 执行,捕获异常并输出 PASS/FAIL 及结构化 COMPONENT 日志。每个通过检查的组件累加其固定权重分数(0.12、0.10、0.14、0.08、0.10、0.16、0.15、0.15),最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后返回。任一组件失败仅导致该组件得 0 分,不会中断后续组件检查。\"\n\nfailure_modes:\n- \"读取 /tmp/task_web_sid 失败或为空:脚本打印 CRITICAL 错误,输出 REWARD: 0.0 并调用 sys.exit(0) 提前退出\"\n- \"模拟服务 HTTP 请求失败或返回 None:对应组件直接返回 0 分\"\n- \"组件检查函数抛出未捕获异常:被 _run_component 捕获后该组件记为 0 分\"\n- \"Google Sheets 中 Performance 工作表缺失、A4-E4 数据不匹配或 A2/A3 行丢失\"\n- \"Airtable 中 Campaigns 表或 Q2 Webinar Series 记录缺失、状态非 Closed、Notes 字段缺少指定子串\"\n- \"Monday 中 Closeout 项目缺失、不在 Done 分组、子任务名称/负责人/截止日期不匹配\"\n- \"Google Docs 中事后总结文档标题或 H1 缺失\"\n- \"Google Docs 内容缺少 Results 指标、Top 3 Learnings 或 Recommendations 指定文本\"\n- \"Slack #marketing 频道消息缺少 3 条 learnings 或文档链接\"\n- \"Gmail 发件箱缺少发给 sales-ops@northwindcloud.com 的指定主题邮件、正文缺少 540 MQLs 或文档链接\"\n- \"Google Calendar 缺少指定标题/时间/描述/嘉宾的 Retro 会议\"\n\n等等,failure_modes 应该列出会导致提前退出、返回 0.0 或扣分的异常/失败路径。我上面的列表可以。\n\n现在确认每个组件的 check_logic 和 pass_condition:\n\nComponent 1:\ncheck_logic: \"从 sheets_mock 获取状态,定位 Performance 工作表,读取 A4-E4 单元格值,验证 A4='Q2 Webinar Series'、B4='540'、C4='41.2%'、D4='6.3%'、E4='HubSpot',同时确认 A2 和 A3 仍存在(防止覆盖原有数据)\"\npass_condition: \"A4-E4 完全匹配指定值且 A2、A3 非空\"\n\nComponent 2:\ncheck_logic: \"从 airtable_mock 获取状态,定位 Campaigns 表,查找 fld_name 归一化后为 'q2 webinar series' 的记录,验证 fld_status 归一化后为 'closed',且 fld_notes 归一化后同时包含 'top channel: linkedin' 和 'replay drove 22% of mqls'\"\npass_condition: \"存在匹配记录,状态为 Closed,Notes 包含指定两句话\"\n\nComponent 3:\ncheck_logic: \"从 monday_mock 获取状态,遍历所有 items 查找 name 归一化后为 'q2 webinar series — closeout' 的项目;确认其所在 group 的 title 归一化后为 'done';检查其子任务(支持 subitems 对象列表或 subitemIds 解析)中是否存在 name 归一化后为 'hand leads to sales' 的项,且该项 assignee 归一化后为 'sales ops'、due 等于 '2026-07-10'\"\npass_condition: \"Closeout 项目位于 Done 分组,且包含指定名称、负责人和截止日期的子任务\"\n\nComponent 4:\ncheck_logic: \"从 docs_mock 获取状态,遍历所有文档,查找 title 归一化后为 'q2 webinar series — post-mortem' 的文档,并验证其 content 包含 '

' 标签且前 200 字符内包含 'post-mortem'\"\npass_condition: \"存在标题匹配的文档且内容以 H1 标题开头\"\n\nComponent 5:\ncheck_logic: \"从 docs_mock 获取状态,定位事后总结文档,将 content 归一化后检查三组文本:Results 行必须包含 '540 mqls'、'41.2% open rate'、'6.3% conversion'、'842 attendees'、'1290 registrants';Top 3 Learnings 必须包含 'top 3 learnings'、'linkedin was the highest-quality channel'、'on-demand replay drove 22% of total mqls'、'10am'、'open rate'、'5pts';Recommendations 必须包含 'repeat the webinar format in q3'、'shift 15% of budget to linkedin'、'publish replay within 24h'\"\npass_condition: \"文档内容同时包含 Results 指标、三项 Learnings 和三项 Recommendations 的指定关键词\"\n\nComponent 6:\ncheck_logic: \"从 slack_mock 获取状态,读取 #marketing 频道消息,查找一条消息:归一化内容包含 'top 3 learnings'、'linkedin was the highest-quality'、'on-demand replay drove 22% of mqls'、'10am'、'5pts';且原始内容同时包含 '8162' 和 'doc-q2-webinar-postmortem'\"\npass_condition: \"#marketing 频道存在同时包含 3 条 learnings 和文档链接的消息\"\n\nComponent 7:\ncheck_logic: \"从 gmail_mock 获取状态,遍历 sent 文件夹邮件,筛选收件人包含 'sales-ops@northwindcloud.com' 且 subject 归一化后为 'q2 webinar series — lead handoff' 的邮件;验证归一化正文包含 '540 mqls' 和 'monday closeout item',且原始正文包含 'doc-q2-webinar-postmortem'\"\npass_condition: \"发件箱存在发给指定收件人、主题正确、正文包含 MQLs 和文档链接的邮件\"\n\nComponent 8:\ncheck_logic: \"从 calendar_mock 获取状态,查找 title 归一化后为 'q2 webinar series retro' 的事件;验证 start 为 '2026-07-09T14:00:00.000Z' 且 end 为 '2026-07-09T14:30:00.000Z';guests 列表中至少有一项包含 'marketing';description 归一化后为 'review post-mortem and q3 plan.'\"\npass_condition: \"存在指定标题、时间段、包含 marketing 嘉宾且描述正确的日历事件\"\n\n注意:check_calendar_event 中,如果找到标题匹配但时间不匹配,会立即返回失败,不会继续搜索其他事件。这是一个细节。\n\n现在确认 JSON 格式。所有字符串必须是中文,除了保留的标识符。\n\n让我再检查一下 domain。docstring 说 \"Domain: mock_websites (8 mocks: ...)\",所以 domain 是 mock_websites。\n\nis_placeholder: false\n\nconfidence: 1.0\n\n确保没有 markdown 代码块,没有思考过程,没有额外文字。输出必须严格以 { 开头,以 } 结尾。\n\nJSON 字段顺序不重要,但内容要完整。\n\n让我再仔细看看是否有任何占位特征。脚本有完整的 8 个组件检查,每个都有具体的业务逻辑,不是占位脚本。\n\n关于 data_sources,我会写:\n[\"/tmp/task_web_sid\", \"sheets_mock\", \"airtable_mock\", \"monday_mock\", \"docs_mock\", \"slack_mock\", \"gmail_mock\", \"calendar_mock\"]\n\n或者按照 docstring 的命名:HubSpot, Google Sheets 等。但示例用了技术名。我用技术名加 _mock。\n\n等等,PORTS 定义了 BASE 和各个端口。BASE 是 'http://28.7.186.212'。这算数据源吗?不算,这是基础 URL。数据源是各个 mock 服务。\n\n现在写最终的 JSON。 {\"task_id\":\"prof16_postmortem_003\",\"domain\":\"mock_websites\",\"summary\":\"验证营销战役 Q2 网络研讨会事后总结在 8 个模拟 Web 应用中的 8 个独立操作步骤是否完成\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"sheets_mock\",\"airtable_mock\",\"monday_mock\",\"docs_mock\",\"slack_mock\",\"gmail_mock\",\"calendar_mock\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.12,\"description\":\"Google Sheets Performance 工作表第 4 行填入 Q2 Webinar Series 数据且未覆盖原有行\",\"check_logic\":\"从 sheets_mock 获取状态,定位 Performance 工作表,读取 A4-E4 单元格值,验证 A4='Q2 Webinar Series'、B4='540'、C4='41.2%'、D4='6.3%'、E4='HubSpot',同时确认 A2 和 A3 仍存在(防止覆盖原有数据)\",\"pass_condition\":\"A4-E4 完全匹配指定值且 A2、A3 非空\"},{\"name\":\"Component 2\",\"weight\":0.10,\"description\":\"Airtable Campaigns 记录状态设为 Closed 并填写 Notes\",\"check_logic\":\"从 airtable_mock 获取状态,定位 Campaigns 表,查找 fld_name 归一化后为 'q2 webinar series' 的记录,验证 fld_status 归一化后为 'closed',且 fld_notes 归一化后同时包含 'top channel: linkedin' 和 'replay drove 22% of mqls'\",\"pass_condition\":\"存在匹配记录,状态为 Closed,Notes 包含指定两句话\"},{\"name\":\"Component 3\",\"weight\":0.14,\"description\":\"Monday 创建 Closeout 项目并置于 Done 分组,附带指定子任务\",\"check_logic\":\"从 monday_mock 获取状态,遍历所有 items 查找 name 归一化后为 'q2 webinar series — closeout' 的项目;确认其所在 group 的 title 归一化后为 'done';检查其子任务(支持 subitems 对象列表或 subitemIds 解析)中是否存在 name 归一化后为 'hand leads to sales' 的项,且该项 assignee 归一化后为 'sales ops'、due 等于 '2026-07-10'\",\"pass_condition\":\"Closeout 项目位于 Done 分组,且包含指定名称、负责人和截止日期的子任务\"},{\"name\":\"Component 4\",\"weight\":0.08,\"description\":\"Google Docs 创建指定标题的事后总结文档并包含 H1 标题\",\"check_logic\":\"从 docs_mock 获取状态,遍历所有文档,查找 title 归一化后为 'q2 webinar series — post-mortem' 的文档,并验证其 content 包含 '

' 标签且前 200 字符内包含 'post-mortem'\",\"pass_condition\":\"存在标题匹配的文档且内容以 H1 标题开头\"},{\"name\":\"Component 5\",\"weight\":0.10,\"description\":\"事后总结文档包含 Results 指标、3 条 Learnings 和 Recommendations\",\"check_logic\":\"从 docs_mock 获取状态,定位事后总结文档,将 content 归一化后检查三组文本:Results 行必须包含 '540 mqls'、'41.2% open rate'、'6.3% conversion'、'842 attendees'、'1290 registrants';Top 3 Learnings 必须包含 'top 3 learnings'、'linkedin was the highest-quality channel'、'on-demand replay drove 22% of total mqls'、'10am'、'open rate'、'5pts';Recommendations 必须包含 'repeat the webinar format in q3'、'shift 15% of budget to linkedin'、'publish replay within 24h'\",\"pass_condition\":\"文档内容同时包含 Results 指标、三项 Learnings 和三项 Recommendations 的指定关键词\"},{\"name\":\"Component 6\",\"weight\":0.16,\"description\":\"Slack #marketing 频道发送包含 3 条 learnings 和文档链接的消息\",\"check_logic\":\"从 slack_mock 获取状态,读取 #marketing 频道消息,查找一条消息:归一化内容包含 'top 3 learnings'、'linkedin was the highest-quality'、'on-demand replay drove 22% of mqls'、'10am'、'5pts';且原始内容同时包含 '8162' 和 'doc-q2-webinar-postmortem'\",\"pass_condition\":\"#marketing 频道存在同时包含 3 条 learnings 和文档链接的消息\"},{\"name\":\"Component 7\",\"weight\":0.15,\"description\":\"Gmail 发送给 Sales Ops 的线索移交邮件包含指定正文和文档链接\",\"check_logic\":\"从 gmail_mock 获取状态,遍历 sent 文件夹邮件,筛选收件人包含 'sales-ops@northwindcloud.com' 且 subject 归一化后为 'q2 webinar series — lead handoff' 的邮件;验证归一化正文包含 '540 mqls' 和 'monday closeout item',且原始正文包含 'doc-q2-webinar-postmortem'\",\"pass_condition\":\"发件箱存在发给指定收件人、主题正确、正文包含 MQLs 和文档链接的邮件\"},{\"name\":\"Component 8\",\"weight\":0.15,\"description\":\"Google Calendar 创建指定时间的 Retro 会议并邀请营销团队\",\"check_logic\":\"从 calendar_mock 获取状态,查找 title 归一化后为 'q2 webinar series retro' 的事件;验证 start 为 '2026-07-09T14:00:00.000Z' 且 end 为 '2026-07-09T14:30:00.000Z';guests 列表中至少有一项包含 'marketing';description 归一化后为 'review post-mortem and q3 plan.'\",\"pass_condition\":\"存在指定标题、时间段、包含 marketing 嘉宾且描述正确的日历事件\"}],\"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) 提前退出\",\"模拟服务 HTTP 请求失败或返回 None:对应组件直接返回 0 分\",\"组件检查函数抛出未捕获异常:被 _run_component 捕获后该组件记为 0 分\",\"Google Sheets 中 Performance 工作表缺失、A4-E4 数据不匹配或 A2/A3 行丢失\",\"Airtable 中 Campaigns 表或 Q2 Webinar Series 记录缺失、状态非 Closed、Notes 字段缺少指定子串\",\"Monday 中 Closeout 项目缺失、不在 Done 分组、子任务名称/负责人/截止日期不匹配\",\"Google Docs 中事后总结文档标题或 H1 缺失\",\"Google Docs 内容缺少 Results 指标、Top 3 Learnings 或 Recommendations 指定文本\",\"Slack #marketing 频道消息缺少 3 条 learnings 或文档链接\",\"Gmail 发件箱缺少发给 sales-ops@northwindcloud.com 的指定主题邮件、正文缺少 540 MQLs 或文档链接\",\"Google Calendar 缺少指定标题/时间/描述/嘉宾的 Retro 会议\"],\"scoring_logic_explanation\":\"脚本首先通过 _load_sid() 从 /tmp/task_web_sid 读取会话 ID,若失败则直接输出 REWARD: 0.0 并退出。随后 verify_task() 按顺序执行 8 个独立评分组件。每个组件通过 _fetch() 向对应的模拟服务(Google Sheets、Airtable、Monday、Google Docs、Slack、Gmail、Google Calendar)发送 HTTP 请求获取实时状态,并依据特定业务规则验证数据内容。各组件使用 _run_component() 执行,捕获异常并输出 PASS/FAIL 及结构化 COMPONENT 日志。每个通过检查的组件累加其固定权重分数(0.12、0.10、0.14、0.08、0.10、0.16、0.15、0.15),最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后返回。任一组件失败仅导致该组件得 0 分,不会中断后续组件检查。\",\"confidence\":1.0}" +} diff --git a/legacy/prof26_integration_audit_003/_cua_gym_vm_bridge.sh b/legacy/prof26_integration_audit_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/prof26_integration_audit_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/prof26_integration_audit_003/initial_setup.py b/legacy/prof26_integration_audit_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e89c867d910dcf84d030e37cbbf6e6e1b5808495 --- /dev/null +++ b/legacy/prof26_integration_audit_003/initial_setup.py @@ -0,0 +1,669 @@ +""" +Initial Setup: Meridian Labs monthly cross-system integration audit +Task ID: prof26_integration_audit_003 +Domain: mock_websites +Mocks: jira_mock, workday_mock, gusto_mock, salesforce_mock, + google_docs_mock, slack_mock, google_sheets_mock, microsoft_teams_mock + +This script establishes the EXACT initial state described in the task context. +It does NOT apply any of the target (golden) changes. The agent must perform +those changes during the task. +""" + +import json +import os +import shlex +import subprocess +import time +import uuid + +import requests + +# --------------------------------------------------------------------------- +# Mock URLs (per task_config.json — host 28.7.186.212) +# --------------------------------------------------------------------------- +MOCKS = { + "jira_mock": "http://28.7.186.212:8173", + "workday_mock": "http://28.7.186.212:8212", + "gusto_mock": "http://28.7.186.212:8218", + "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", + "google_sheets_mock": "http://28.7.186.212:8165", + "microsoft_teams_mock": "http://28.7.186.212:8182", +} + +# --------------------------------------------------------------------------- +# Session IDs — the initial_env and golden_env use DISTINCT sids. The mock +# server stores state PER-SID. The initial_env (sid ..._initial) must expose +# ONLY the pre-task (initial) snapshot in its current_state, so the reward +# script returns ~0.0 when scoring the initial environment. golden_patch.py +# uses a SEPARATE sid (..._golden) that it will then transform with +# action:"set_current" to carry the post-task (golden) changes, scoring 1.0. +# The two sids must never match. +# +# initial_setup.py seeds BOTH sids with the identical pre-task state: the +# _initial sid stays as-is (pre-task), and the _golden sid is seeded so that +# golden_patch.py can read its initial_state and apply the golden set_current +# diff against it. +# --------------------------------------------------------------------------- +SID_INITIAL = "prof26_integration_audit_003_initial" +SID_GOLDEN = "prof26_integration_audit_003_golden" +# The sid this script "owns" (used for /tmp/task_web_sid and the browser URL) +sid = SID_INITIAL +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +# =========================================================================== +# JIRA (jira_mock) — IT Access Requests project 'IAR' with 4 OPEN tickets +# =========================================================================== +def build_jira_state(): + users = [ + {"id": "u_sys", "name": "Sys Admin", "email": "sysadmin@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Sys+Admin&background=0875E1&color=fff&size=128"}, + {"id": "u_daniel", "name": "Daniel Okafor", "email": "daniel.okafor@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Daniel+Okafor&background=7C3AED&color=fff&size=128"}, + {"id": "u_sara", "name": "Sara Kim", "email": "sara.kim@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Sara+Kim&background=0E8A16&color=fff&size=128"}, + ] + projects = [ + {"id": "p_iar", "key": "IAR", "name": "IT Access Requests", "leadId": "u_sys", + "category": "IT Operations", + "icon": "https://ui-avatars.com/api/?name=IAR&background=0875E1&color=fff&size=64"}, + ] + # 4 open tickets. None are yet processed. + issues = [ + { + "id": "iar-401", "key": "IAR-401", "projectId": "p_iar", + "summary": "Salesforce Edit access for Grace Liu", + "description": "Grace Liu (grace.liu@meridianlabs.io) requests Salesforce Edit access. Manager approval: Approved by Daniel Okafor.", + "type": "Task", "status": "Open", "priority": "High", "storyPoints": 1, + "reporterId": "u_sys", "assigneeId": "u_sys", "sprintId": None, "epicId": None, + "labels": ["access-request", "salesforce"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-07-06T08:00:00.000Z", "updatedAt": "2026-07-06T08:00:00.000Z", + }, + { + "id": "iar-402", "key": "IAR-402", "projectId": "p_iar", + "summary": "HubSpot Edit access for Henry Park", + "description": "Henry Park (henry.park@meridianlabs.io) requests HubSpot Edit access. Manager approval: Approved by Sara Kim.", + "type": "Task", "status": "Open", "priority": "High", "storyPoints": 1, + "reporterId": "u_sys", "assigneeId": "u_sys", "sprintId": None, "epicId": None, + "labels": ["access-request", "hubspot"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-07-06T08:05:00.000Z", "updatedAt": "2026-07-06T08:05:00.000Z", + }, + { + "id": "iar-403", "key": "IAR-403", "projectId": "p_iar", + "summary": "Workday Admin access for Ivy Brooks", + "description": "Ivy Brooks (ivy.brooks@meridianlabs.io) requests Workday Admin access. Manager approval: Approved by Sara Kim.", + "type": "Task", "status": "Open", "priority": "Medium", "storyPoints": 1, + "reporterId": "u_sys", "assigneeId": "u_sys", "sprintId": None, "epicId": None, + "labels": ["access-request", "workday"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-07-06T08:10:00.000Z", "updatedAt": "2026-07-06T08:10:00.000Z", + }, + { + "id": "iar-404", "key": "IAR-404", "projectId": "p_iar", + "summary": "Salesforce Read-only access for Jack Reid", + "description": "Jack Reid (jack.reid@meridianlabs.io) requests Salesforce Read-only access. Manager approval: PENDING.", + "type": "Task", "status": "Open", "priority": "Low", "storyPoints": 1, + "reporterId": "u_sys", "assigneeId": "u_sys", "sprintId": None, "epicId": None, + "labels": ["access-request", "salesforce"], "subtasks": [], "linkedIssueIds": [], + "createdAt": "2026-07-06T08:15:00.000Z", "updatedAt": "2026-07-06T08:15:00.000Z", + }, + ] + return { + "currentUser": users[0], + "users": users, + "projects": projects, + "issues": issues, + "sprints": [], + "comments": [], + "workflows": [{ + "id": "w1", "name": "IT Access Workflow", + "transitions": [ + {"from": "Open", "to": ["In Progress", "Done", "Rejected"]}, + {"from": "In Progress", "to": ["Done", "Rejected", "Open"]}, + {"from": "Done", "to": ["Open"]}, + {"from": "Rejected", "to": ["Open"]}, + ], + }], + "notifications": [], + } + + +# =========================================================================== +# WORKDAY (workday_mock) — 3 employees with dept/status +# =========================================================================== +def build_workday_state(): + current = { + "id": "emp_sys", "name": "Sys Admin", "email": "sysadmin@meridianlabs.io", + "phone": "+1 (415) 555-0100", "role": "Administrator", "department": "IT", + "departmentId": "dept_it", "avatar": "", "managerId": None, + "title": "Business Systems Administrator", "location": "Remote", + "joinDate": "2022-01-10", "employeeType": "Full-Time", "birthday": "1990-01-01", + "workAnniversary": "2022-01-10", + } + employees = [ + { + "id": "emp001", "name": "Grace Liu", "email": "grace.liu@meridianlabs.io", + "phone": "+1 (415) 555-0201", "role": "Employee", "department": "Sales Operations", + "departmentId": "dept_salesops", "avatar": "", "managerId": "emp_sys", + "title": "Sales Operations Analyst", "location": "Remote", "joinDate": "2023-03-12", + "employeeType": "Active", "birthday": "1992-05-20", "workAnniversary": "2023-03-12", + }, + { + "id": "emp002", "name": "Henry Park", "email": "henry.park@meridianlabs.io", + "phone": "+1 (415) 555-0202", "role": "Employee", "department": "Marketing", + "departmentId": "dept_mktg", "avatar": "", "managerId": "emp_sys", + "title": "Marketing Specialist", "location": "Remote", "joinDate": "2023-06-01", + "employeeType": "Active", "birthday": "1991-09-14", "workAnniversary": "2023-06-01", + }, + { + "id": "emp003", "name": "Ivy Brooks", "email": "ivy.brooks@meridianlabs.io", + "phone": "+1 (415) 555-0203", "role": "Employee", "department": "HR", + "departmentId": "dept_hr", "avatar": "", "managerId": "emp_sys", + "title": "HR Generalist", "location": "Remote", "joinDate": "2022-11-08", + "employeeType": "Terminated", "birthday": "1990-12-02", "workAnniversary": "2022-11-08", + }, + ] + departments = [ + {"id": "dept_it", "name": "IT", "headcount": 1, "managerId": None}, + {"id": "dept_salesops", "name": "Sales Operations", "headcount": 1, "managerId": "emp_sys"}, + {"id": "dept_mktg", "name": "Marketing", "headcount": 1, "managerId": "emp_sys"}, + {"id": "dept_hr", "name": "HR", "headcount": 1, "managerId": "emp_sys"}, + ] + return { + "currentUser": current, + "employees": employees, + "departments": departments, + "timeEntries": [], "timeOffRequests": [], + "timeOffBalance": {"vacation": 120, "sick": 40, "personal": 16}, + "payroll": [], "benefits": {"employeeId": "emp_sys", "enrollmentStatus": "Complete", + "plans": [], "dependents": []}, + "reviews": [], "goals": [], "tasks": [], "announcements": [], "notifications": [], + "contactDrafts": [], "clockStatus": {"isClockedIn": False, "startTime": None}, + } + + +# =========================================================================== +# GUSTO (gusto_mock) — payroll status for 3 employees +# =========================================================================== +def build_gusto_state(): + current = { + "id": "emp_sys", "firstName": "Sys", "lastName": "Admin", + "email": "sysadmin@meridianlabs.io", "personalEmail": "sysadmin.personal@example.com", + "phone": "(415) 555-0100", "dateOfBirth": "1990-01-01", "ssn": "***-**-0000", + "address": {"street1": "1 Corp Way", "street2": "", "city": "San Francisco", + "state": "CA", "zip": "94105"}, + "department": "IT", "departmentId": "dept_it", "jobTitle": "Business Systems Administrator", + "managerId": None, "managerName": None, "employmentType": "Full-time", + "compensation": {"type": "Salary", "amount": 130000, "per": "Year"}, + "startDate": "2022-01-10", "status": "Active", "location": "HQ - San Francisco", + "locationId": "loc_1", "payMethod": "Direct Deposit", + "federalFilingStatus": "Single", "stateFilingStatus": "Single", "allowances": 0, + "benefits": [], + } + employees = [ + dict(current, id="E-20501", firstName="Grace", lastName="Liu", + email="grace.liu@meridianlabs.io", department="Sales Operations", + departmentId="dept_salesops", jobTitle="Sales Operations Analyst", + compensation={"type": "Salary", "amount": 95000, "per": "Year"}, + startDate="2023-03-12", status="Active"), + dict(current, id="E-20502", firstName="Henry", lastName="Park", + email="henry.park@meridianlabs.io", department="Marketing", + departmentId="dept_mktg", jobTitle="Marketing Specialist", + compensation={"type": "Salary", "amount": 88000, "per": "Year"}, + startDate="2023-06-01", status="Active"), + dict(current, id="E-20503", firstName="Ivy", lastName="Brooks", + email="ivy.brooks@meridianlabs.io", department="HR", + departmentId="dept_hr", jobTitle="HR Generalist", + compensation={"type": "Salary", "amount": 92000, "per": "Year"}, + startDate="2022-11-08", status="Terminated"), + ] + return { + "company": {"name": "Meridian Labs", "ein": "12-3456789", "state": "CA"}, + "currentUser": current, + "employees": employees, + "contractors": [], "payrolls": [], "timeEntries": [], "timeOffRequests": [], + "benefitPlans": [], "taxForms": [], "documents": [], "todoItems": [], + "onboardingChecklists": [], "performanceReviews": [], "companyHolidays": [], + "notifications": [], "reportHistory": [], "referrals": [], + } + + +# =========================================================================== +# SALESFORCE (salesforce_mock) — grace.liu profile w/ Access Level = Read-only +# =========================================================================== +def build_salesforce_state(): + user_grace = { + "userId": "user-grace", "firstName": "Grace", "lastName": "Liu", + "email": "grace.liu@meridianlabs.io", "phone": "(415) 555-0201", + "title": "Sales Operations Analyst", "department": "Sales Operations", + "role": "Read-only", "avatar": "https://i.pravatar.cc/150?u=user-grace", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + } + user_sys = { + "userId": "user-sys", "firstName": "Sys", "lastName": "Admin", + "email": "sysadmin@meridianlabs.io", "phone": "(415) 555-0100", + "title": "Business Systems Administrator", "department": "IT", + "role": "Administrator", "avatar": "https://i.pravatar.cc/150?u=user-sys", + "timezone": "America/New_York", "locale": "en-US", "theme": "lightning", + } + return { + "user": user_sys, + "users": [user_sys, user_grace], + "leads": [], "accounts": [], "contacts": [], "opportunities": [], "cases": [], + "activities": [], "chatterPosts": [], "files": [], "following": [], + "recentlyViewed": [], "dismissedNotifications": [], "dashboards": [], + "emailDrafts": [], "reportSnapshots": [], "partners": [], + } + + +# =========================================================================== +# GOOGLE SHEETS (google_sheets_mock) +# Workbook "Access Control Register": sheets "Approvals" (rows 2-4 filled, +# 5-7 empty) and "Change Log" (rows 2-5 filled, row 6 empty). +# =========================================================================== +def cell(value, bold=False, bg=None, align=None): + c = {"value": 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 + + +def build_sheets_state(): + # ---- Approvals sheet ---- + approvals = {} + headers_a = ["Request ID", "Date", "Requester", "System", "Access Level", + "Department", "Manager Approval", "Access Decision", "Notes"] + for i, h in enumerate(headers_a): + col = chr(ord('A') + i) + approvals[f"{col}1"] = cell(h, bold=True, bg="#E8EAED", align="center") + # rows 2-4 (existing, prior audit) + prior = [ + ["IAR-309", "2026-06-26", "Felix Tan", "Google Sheets", "Edit", + "Finance", "Approved", "Approved", "Active in Workday + Gusto. Policy ok."], + ["IAR-310", "2026-06-28", "Nora Vega", "Salesforce", "Read-only", + "Sales", "Approved", "Approved", "Active in Workday + Gusto. Policy ok."], + ["IAR-311", "2026-06-30", "Omar Said", "HubSpot", "Edit", + "Marketing", "Approved", "Approved", "Active in Workday + Gusto. Policy ok."], + ] + for r, row in enumerate(prior, start=2): + for c, val in enumerate(row): + col = chr(ord('A') + c) + approvals[f"{col}{r}"] = cell(val) + # rows 5-7 intentionally EMPTY (left for the agent / golden) + + approvals_sheet = { + "id": "sheet_approvals", "name": "Approvals", "rowCount": 100, "colCount": 26, + "frozenRows": 1, "frozenCols": 0, "tabColor": "#1A73E8", "isHidden": False, + "columnWidths": {"0": 120, "1": 110, "2": 140, "3": 120, "4": 120, + "5": 150, "6": 150, "7": 150, "8": 320}, + "data": approvals, + } + + # ---- Change Log sheet ---- + changelog = {} + headers_c = ["Change ID", "Date", "System", "Object", "Description", + "Approved By", "Status"] + for i, h in enumerate(headers_c): + col = chr(ord('A') + i) + changelog[f"{col}1"] = cell(h, bold=True, bg="#E8EAED", align="center") + prior_changes = [ + ["CHG-2026-0626", "2026-06-26", "Google Sheets", "Finance shared workbook", + "Granted Edit to Felix Tan", "Daniel Okafor", "Completed"], + ["CHG-2026-0627", "2026-06-27", "Salesforce", "User profile nora.vega", + "Set Read-only access", "Daniel Okafor", "Completed"], + ["CHG-2026-0628", "2026-06-28", "HubSpot", "Marketing seat", + "Provisioned seat for Nora Vega", "Sara Kim", "Completed"], + ["CHG-2026-0629", "2026-06-29", "Workday", "Onboarding Omar Said", + "Created employee record", "Sara Kim", "Completed"], + ] + for r, row in enumerate(prior_changes, start=2): + for c, val in enumerate(row): + col = chr(ord('A') + c) + changelog[f"{col}{r}"] = cell(val) + # row 6 intentionally EMPTY + + changelog_sheet = { + "id": "sheet_changelog", "name": "Change Log", "rowCount": 100, "colCount": 26, + "frozenRows": 1, "frozenCols": 0, "tabColor": "#0F9D58", "isHidden": False, + "columnWidths": {"0": 140, "1": 110, "2": 120, "3": 260, "4": 360, + "5": 140, "6": 110}, + "data": changelog, + } + + return { + "id": "workbook_acr", "title": "Access Control Register", + "activeSheetId": "sheet_approvals", "selectedCell": "A1", "selectionRange": None, + "clipboard": None, "isDragging": False, "undoStack": [], "redoStack": [], + "namedRanges": [], "conditionalFormats": [], "charts": [], "showGridlines": True, + "showFormulas": False, "zoom": 100, + "sheets": [approvals_sheet, changelog_sheet], + } + + +# =========================================================================== +# GOOGLE DOCS (google_docs_mock) +# "Integration Audit Log" (doc_aud_01): has 'June 2026' heading, NO 'July 2026'. +# =========================================================================== +def build_docs_state(): + current = { + "id": "user-sys", "name": "Sys Admin", "email": "sysadmin@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Sys+Admin&background=0875E1&color=fff&size=128", + } + users = [current, { + "id": "user-grace", "name": "Grace Liu", "email": "grace.liu@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Grace+Liu&background=0E8A16&color=fff&size=128", + }] + doc_content = ( + "

Integration Audit Log

" + "

June 2026

" + "

Monthly cross-system integration audit for June 2026. " + "Three access requests processed (IAR-306, IAR-307, IAR-308). " + "All approved and logged in the Access Control Register.

" + ) + documents = { + "doc_aud_01": { + "id": "doc_aud_01", "title": "Integration Audit Log", + "content": doc_content, "ownerId": "user-sys", "starred": True, + "created": "2026-06-01T09:00:00Z", "updated": "2026-06-30T17:00:00Z", + "sharedWith": [{"userId": "user-grace", "permission": "editor"}], + "linkSharing": {"enabled": False, "permission": "viewer"}, + } + } + return { + "currentUser": current, + "users": users, + "documents": documents, + "comments": [], + "ui": { + "currentDocId": "doc_aud_01", "sidebarOpen": False, "sidebarTab": "comments", + "shareDialogOpen": False, "findReplaceOpen": False, "viewMode": "editing", + "zoom": 100, "documentListView": "grid", "searchQuery": "", + }, + } + + +# =========================================================================== +# SLACK (slack_mock) — #sysadmin-updates channel with Grace/Henry/Ivy members +# =========================================================================== +def build_slack_state(): + current = { + "userId": "user-sys", "fullName": "Sys Admin", "displayName": "Sys Admin", + "email": "sysadmin@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Sys+Admin&background=0875E1&color=fff&size=200", + "status": "active", "statusMessage": "", "statusEmoji": "", + "timeZone": "America/New_York", + } + users = [ + current, + {"userId": "u_grace", "fullName": "Grace Liu", "displayName": "Grace", + "email": "grace.liu@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Grace+Liu&background=0E8A16&color=fff&size=200", + "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "u_henry", "fullName": "Henry Park", "displayName": "Henry", + "email": "henry.park@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Henry+Park&background=4285F4&color=fff&size=200", + "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + {"userId": "u_ivy", "fullName": "Ivy Brooks", "displayName": "Ivy", + "email": "ivy.brooks@meridianlabs.io", + "avatar": "https://ui-avatars.com/api/?name=Ivy+Brooks&background=DB4437&color=fff&size=200", + "status": "away", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}, + ] + channels = [ + { + "channelId": "sysadmin-updates", "name": "sysadmin-updates", + "description": "Systems administration updates and audit notifications", + "topic": "IT access audit notifications", "isPrivate": False, "isStarred": False, + "members": ["user-sys", "u_grace", "u_henry", "u_ivy"], "createdBy": "user-sys", + "createdAt": "2026-01-15T10:00:00Z", "pinnedMessages": [], "unreadCount": 0, + } + ] + return { + "currentUser": current, + "workspace": {"workspaceId": "ws_meridian", "workspaceName": "Meridian Labs", "icon": ""}, + "users": users, + "channels": channels, + "messages": {"sysadmin-updates": []}, + "threads": {}, "dms": [], "bookmarkedMessages": [], "callHistory": [], + "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", + "showAvatars": True, "use24Hour": False}, + "invitations": [], "notifications": [], + } + + +# =========================================================================== +# MICROSOFT TEAMS (microsoft_teams_mock) +# Team 'Systems Admin' (sysadmin-team) with 'General' channel (general) +# =========================================================================== +def build_teams_state(): + current = { + "userId": "user-sys", "displayName": "Sys Admin", "firstName": "Sys", + "lastName": "Admin", "email": "sysadmin@meridianlabs.io", + "avatar": "https://i.pravatar.cc/150?u=user-sys", "jobTitle": "Business Systems Administrator", + "department": "IT", "location": "Remote", "phone": "+1 (415) 555-0100", + "presence": "available", "statusMessage": "", "statusEmoji": "", + "outOfOffice": False, "timezone": "America/New_York", + } + users = [ + current, + {"userId": "u_grace", "displayName": "Grace Liu", "firstName": "Grace", "lastName": "Liu", + "email": "grace.liu@meridianlabs.io", "avatar": "https://i.pravatar.cc/150?u=u-grace", + "jobTitle": "Sales Operations Analyst", "department": "Sales Operations", "location": "Remote", + "phone": "+1 (415) 555-0201", "presence": "available", "statusMessage": "", "statusEmoji": "", + "outOfOffice": False, "timezone": "America/New_York"}, + {"userId": "u_henry", "displayName": "Henry Park", "firstName": "Henry", "lastName": "Park", + "email": "henry.park@meridianlabs.io", "avatar": "https://i.pravatar.cc/150?u=u-henry", + "jobTitle": "Marketing Specialist", "department": "Marketing", "location": "Remote", + "phone": "+1 (415) 555-0202", "presence": "available", "statusMessage": "", "statusEmoji": "", + "outOfOffice": False, "timezone": "America/New_York"}, + {"userId": "u_ivy", "displayName": "Ivy Brooks", "firstName": "Ivy", "lastName": "Brooks", + "email": "ivy.brooks@meridianlabs.io", "avatar": "https://i.pravatar.cc/150?u=u-ivy", + "jobTitle": "HR Generalist", "department": "HR", "location": "Remote", + "phone": "+1 (415) 555-0203", "presence": "away", "statusMessage": "", "statusEmoji": "", + "outOfOffice": False, "timezone": "America/New_York"}, + ] + teams = [ + { + "teamId": "sysadmin-team", "displayName": "Systems Admin", + "description": "Systems administration team", "avatar": "", "avatarColor": "#4A90D9", + "avatarInitials": "SA", "visibility": "private", "isArchived": False, "isFavorite": True, + "createdDateTime": "2026-01-10T10:00:00Z", + "members": ["user-sys", "u_grace", "u_henry", "u_ivy"], "owners": ["user-sys"], + "channels": ["general"], + "settings": {"allowMemberCreateChannels": True, "allowMemberDeleteMessages": True, + "allowGiphy": True, "allowStickers": True, "allowMemes": True}, + } + ] + channels = [ + { + "channelId": "general", "teamId": "sysadmin-team", "displayName": "General", + "description": "General systems admin discussion", "membershipType": "standard", + "isFavoriteByDefault": True, "isPinned": False, "isMuted": False, "unreadCount": 0, + "lastMessagePreview": "", "lastMessageTimestamp": "2026-07-06T09:00:00.000Z", + "createdDateTime": "2026-01-10T10:00:00Z", "members": [], + "tabs": [{"tabId": "tab_posts_general", "displayName": "Posts", "type": "posts", "isDefault": True}], + "pinnedMessages": [], + } + ] + return { + "currentUser": current, + "users": users, + "teams": teams, + "channels": channels, + "chats": [], "messages": {"general": []}, "meetings": [], "calls": [], "files": [], + "activity": [], "activeCall": None, + "notifications": [], + "settings": { + "theme": "light", "language": "en-US", + "notifications": {"showMessagePreviews": True, "playSound": True, "showBadgeCount": True, + "muteAll": False, "quietHoursEnabled": False, + "quietHoursStart": "22:00", "quietHoursEnd": "07:00"}, + "privacy": {"readReceipts": True, "showPresence": True}, + "display": {"density": "comfortable", "showChannelPreview": True}, + }, + "ui": {"activeView": "teams", "activeTeamId": "sysadmin-team", "activeChannelId": "general", + "activeChatId": None, "activeThreadMessageId": None, "isThreadPanelOpen": False, + "isDetailsPanelOpen": False, "searchQuery": "", "searchResults": None}, + } + + +# =========================================================================== +# Inject all states +# =========================================================================== +STATE_BUILDERS = { + "jira_mock": build_jira_state, + "workday_mock": build_workday_state, + "gusto_mock": build_gusto_state, + "salesforce_mock": build_salesforce_state, + "google_docs_mock": build_docs_state, + "slack_mock": build_slack_state, + "google_sheets_mock": build_sheets_state, + "microsoft_teams_mock": build_teams_state, +} + + +def inject_all(): + for target_sid in (SID_INITIAL, SID_GOLDEN): + for name, url in MOCKS.items(): + # Reset any stale state from prior runs of this sid, then inject fresh. + try: + requests.post(f'{url}/post?sid={target_sid}', + json={'action': 'reset'}, timeout=30) + except Exception: + pass + state = STATE_BUILDERS[name]() + _inject_with_retry(name, url, state, target_sid) + + +def _inject_with_retry(name, url, state, target_sid, max_retries=5): + """POST action:'set' and verify the server stored the essential fields. + Workaround for a transient server-side normalization that can drop the + workday employee 'status' field on a fast sequential inject.""" + for attempt in range(max_retries): + resp = requests.post( + f'{url}/post?sid={target_sid}', + json={'action': 'set', 'state': state}, + timeout=30, + ) + if resp.status_code != 200: + raise RuntimeError(f'{name} set failed: {resp.text}') + # Verify critical fields survived server-side normalization + ok = True + try: + go = requests.get(f'{url}/go?sid={target_sid}', timeout=10).json() + cur = go.get('current_state', {}) + if name == 'workday_mock': + emps = cur.get('employees', []) + if not emps or any('employeeType' not in e for e in emps): + ok = False + else: + print(f' [debug] workday emps employeeType: ' + f'{[e.get("employeeType") for e in emps]}') + except Exception: + ok = False + if ok: + print(f' [set] {name} (sid={target_sid}): OK') + return + time.sleep(0.5) + raise RuntimeError(f'{name}: failed to persist required fields after {max_retries} retries') + + +# =========================================================================== +# Browser launch + readiness +# =========================================================================== +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=90.0, render_timeout=15.0): + """Block until every mock serves injected state AND the page 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: + raise RuntimeError(f'Mocks not ready within {timeout}s: {list(pending)}') + # Phase 2: browser render check + try: + from playwright.sync_api import sync_playwright + except ImportError: + print('WARN: playwright not installed; skipping render check') + _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 > 50", + timeout=int(render_timeout * 1000)) + html = page.content() + if len(html) < 1500: + raise RuntimeError(f'[{name}] rendered DOM too small ({len(html)} bytes)') + print(f' [render] {name}: OK ({len(html)} bytes)') + finally: + page.close() + finally: + browser.close() + + +def main(): + print(f'Session ID (initial_env): {sid}') + print(f'Seeding both sids: {SID_INITIAL} (pre-task) and {SID_GOLDEN} (pre-task, for golden_patch)') + inject_all() + # Debug: check workday right after all injects (before browser) + try: + wd = requests.get(f'{MOCKS["workday_mock"]}/go?sid={sid}', timeout=10).json() + ets = [e.get('employeeType') for e in wd.get('current_state', {}).get('employees', [])] + print(f' [pre-browser] workday employeeType: {ets}') + except Exception as ex: + print(f' [pre-browser] workday err: {ex}') + # Launch a Chrome window for every mock (using the initial_env sid) + for name, url in MOCKS.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.4) + wait_for_mocks_loaded(MOCKS, sid) + # The mock frontends re-serialize their state on page load (localStorage + # round-trip) and can overwrite the server state with stale/default data. + # Re-inject ALL mock states AFTER the browser has loaded so the server holds + # the correct canonical data for the agent (and reward) to read. Re-inject + # into BOTH sids so the golden_env sid also has a correct initial_state. + for target_sid in (SID_INITIAL, SID_GOLDEN): + for name, url in MOCKS.items(): + state = STATE_BUILDERS[name]() + requests.post(f'{url}/post?sid={target_sid}', + json={'action': 'set', 'state': state}, timeout=30) + print(f' [final] re-injected all {len(MOCKS)} mock states post-browser (both sids)') + print(f'GUI_READY: all {len(MOCKS)} mocks launched and verified (sid={sid})') + + +if __name__ == '__main__': + main() diff --git a/legacy/prof26_integration_audit_003/reward.py b/legacy/prof26_integration_audit_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..ac01656d03a7be8f21b50ec0ec1fcf26dcc21406 --- /dev/null +++ b/legacy/prof26_integration_audit_003/reward.py @@ -0,0 +1,234 @@ +""" +Reward Script: Monthly cross-system integration audit (prof26_integration_audit_003) +Task ID: prof26_integration_audit_003 +Domain: mock_websites +Scoring: 6 independent components verifying task-introduced changes across 6 mocks. + Component 1 (0.15): Salesforce grace.liu role == 'Edit' + Component 2 (0.25): Google Sheets Approvals rows 5/6/7 = IAR-401/402/403 + Component 3 (0.15): Google Sheets Change Log row 6 = CHG-2026-0706 + Component 4 (0.15): Google Docs 'July 2026' heading + bullet + Component 5 (0.15): Slack #sysadmin-updates audit message + Component 6 (0.15): Microsoft Teams 'Systems Admin'/'General' audit message +""" +import json +import sys + +import requests + +# --- Read sid from the VM (setup-gen writes this) --- +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 (from task_config.json apps list) +MOCKS = { + 'salesforce': 'http://28.7.186.212:8195', + 'google_sheets': 'http://28.7.186.212:8165', + 'google_docs': 'http://28.7.186.212:8162', + 'slack': 'http://28.7.186.212:8198', + 'microsoft_teams': 'http://28.7.186.212:8182', +} + + +def _fetch(mock_name): + """Fetch current_state for a mock by sid. Returns dict or {} on error.""" + try: + resp = requests.get(f'{MOCKS[mock_name]}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + return data.get('current_state', {}) or {} + except Exception as e: + print(f'ERROR: Cannot fetch {mock_name}: {e}') + return {} + + +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 + + +# --- Helper: get cell value from a sheet by name --- +def _sheet_cell(sheets, sheet_name, cell_id): + for sheet in sheets: + if sheet.get('name') == sheet_name: + return sheet.get('data', {}).get(cell_id, {}).get('value') + return None + + +# --- Per-component checks (one function per sub-objective) --- + +def check_component_1_salesforce(current): + """Salesforce: grace.liu@meridianlabs.io 'role' field == 'Edit', and no other user role changed. + Pass condition: the user with email grace.liu@meridianlabs.io has role 'Edit'. + """ + users = current.get('users', []) + grace = None + for u in users: + if u.get('email') == 'grace.liu@meridianlabs.io': + grace = u + break + if grace is None: + return False, 0.0, 'grace.liu@meridianlabs.io user not found in Salesforce' + role = grace.get('role') + if role == 'Edit': + return True, 0.15, f"grace.liu role = 'Edit' (correct)" + return False, 0.0, f"grace.liu role = {role!r}, expected 'Edit'" + + +def check_component_2_approvals(current): + """Google Sheets 'Approvals' sheet rows 5/6/7 = IAR-401 (Approved), IAR-402 (Approved), IAR-403 (Rejected). + Pass condition: row5 A=IAR-401/H=Approved, row6 A=IAR-402/H=Approved, row7 A=IAR-403/H=Rejected. + """ + sheets = current.get('sheets', []) + checks = [ + (5, 'IAR-401', 'Approved'), + (6, 'IAR-402', 'Approved'), + (7, 'IAR-403', 'Rejected'), + ] + ok = True + details = [] + for row, exp_id, exp_decision in checks: + actual_id = _sheet_cell(sheets, 'Approvals', f'A{row}') + actual_decision = _sheet_cell(sheets, 'Approvals', f'H{row}') + if actual_id == exp_id and actual_decision == exp_decision: + details.append(f'row{row}={exp_id}/{exp_decision}') + else: + ok = False + details.append(f'row{row}: got A={actual_id!r}/H={actual_decision!r}, expected {exp_id}/{exp_decision}') + if ok: + return True, 0.25, '; '.join(details) + return False, 0.0, '; '.join(details) + + +def check_component_3_changelog(current): + """Google Sheets 'Change Log' sheet row 6 = CHG-2026-0706 (Salesforce / grace.liu / Edit / Daniel Okafor / Completed). + Pass condition: A6='CHG-2026-0706', C6='Salesforce', F6='Daniel Okafor', G6='Completed'. + """ + sheets = current.get('sheets', []) + a6 = _sheet_cell(sheets, 'Change Log', 'A6') + c6 = _sheet_cell(sheets, 'Change Log', 'C6') + f6 = _sheet_cell(sheets, 'Change Log', 'F6') + g6 = _sheet_cell(sheets, 'Change Log', 'G6') + if a6 == 'CHG-2026-0706' and c6 == 'Salesforce' and f6 == 'Daniel Okafor' and g6 == 'Completed': + return True, 0.15, f'row6: {a6}/{c6}/.../{f6}/{g6}' + return False, 0.0, f'row6: A={a6!r} C={c6!r} F={f6!r} G={g6!r}, expected CHG-2026-0706/Salesforce/Daniel Okafor/Completed' + + +def check_component_4_docs(current): + """Google Docs 'Integration Audit Log' has 'July 2026' heading (h2) with a bullet naming + IAR-401, IAR-402, IAR-403, CHG-2026-0706, and noting IAR-404 skipped. + Pass condition: content contains 'July 2026' as h2 AND bullet text contains IAR-401, IAR-402, + IAR-403, CHG-2026-0706, and IAR-404 skipped. + """ + docs = current.get('documents', {}) + content = '' + for docid, doc in docs.items(): + if doc.get('title') == 'Integration Audit Log': + content = doc.get('content', '') or '' + break + if not content: + return False, 0.0, 'Integration Audit Log document not found' + # Check for July 2026 heading (h2) + has_july_heading = '

July 2026

' in content + # Check bullet contains required tokens + required = ['IAR-401', 'IAR-402', 'IAR-403', 'CHG-2026-0706', 'IAR-404'] + missing = [t for t in required if t not in content] + if has_july_heading and not missing: + return True, 0.15, "'July 2026' heading present; all required tokens found" + detail = [] + if not has_july_heading: + detail.append("'July 2026' h2 heading missing") + if missing: + detail.append(f"missing tokens: {missing}") + return False, 0.0, '; '.join(detail) + + +def check_component_5_slack(current): + """Slack: one audit-summary message in #sysadmin-updates naming IAR-401 (Approved), + IAR-402 (Approved), IAR-403 (Rejected), IAR-404 (skipped). + Pass condition: #sysadmin-updates has >=1 message containing IAR-401, IAR-402, IAR-403, IAR-404. + """ + msgs = current.get('messages', {}).get('sysadmin-updates', []) + if not msgs: + return False, 0.0, 'no messages in #sysadmin-updates' + # Concatenate all message contents + combined = ' '.join(m.get('content', '') for m in msgs) + required = ['IAR-401', 'IAR-402', 'IAR-403', 'IAR-404'] + missing = [t for t in required if t not in combined] + if not missing: + return True, 0.15, f'{len(msgs)} message(s) in #sysadmin-updates with all required IAR tokens' + return False, 0.0, f'missing tokens in #sysadmin-updates: {missing}' + + +def check_component_6_teams(current): + """Microsoft Teams: one audit-summary message in 'Systems Admin'/'General' channel naming + IAR-401 (Approved), IAR-402 (Approved), IAR-403 (Rejected), IAR-404 (skipped). + Pass condition: 'general' channel (under sysadmin-team) has >=1 message containing IAR-401, + IAR-402, IAR-403, IAR-404. + """ + msgs = current.get('messages', {}) + # The general channel is keyed by channelId 'general' + general_msgs = msgs.get('general', []) + if not general_msgs: + return False, 0.0, "no messages in 'general' channel" + combined = ' '.join(m.get('content', '') for m in general_msgs) + required = ['IAR-401', 'IAR-402', 'IAR-403', 'IAR-404'] + missing = [t for t in required if t not in combined] + if not missing: + return True, 0.15, f'{len(general_msgs)} message(s) in General channel with all required IAR tokens' + return False, 0.0, f'missing tokens in General channel: {missing}' + + +def verify_task(): + """Verify task completion by fetching each mock's current_state and checking task changes.""" + # Fetch all mock states + states = {name: _fetch(name) for name in MOCKS} + + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'Salesforce grace.liu role=Edit', 0.15, check_component_1_salesforce, (states['salesforce'],)), + (2, 'Sheets Approvals rows 5/6/7', 0.25, check_component_2_approvals, (states['google_sheets'],)), + (3, 'Sheets Change Log row 6', 0.15, check_component_3_changelog, (states['google_sheets'],)), + (4, 'Docs July 2026 heading+bullet', 0.15, check_component_4_docs, (states['google_docs'],)), + (5, 'Slack #sysadmin-updates message', 0.15, check_component_5_slack, (states['slack'],)), + (6, 'Teams General message', 0.15, check_component_6_teams, (states['microsoft_teams'],)), + ]: + _, 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/legacy/prof26_integration_audit_003/reward_label.json b/legacy/prof26_integration_audit_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..5d47c9ea5c5c1f5a641d55b9147a6b9a22c62eb6 --- /dev/null +++ b/legacy/prof26_integration_audit_003/reward_label.json @@ -0,0 +1,79 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof26_integration_audit_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:31:09", + "label": { + "task_id": "prof26_integration_audit_003", + "domain": "mock_websites", + "summary": "验证跨系统集成审计任务在6个mock服务中引入的更改是否正确完成", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "salesforce_mock", + "google_sheets_mock", + "google_docs_mock", + "slack_mock", + "microsoft_teams_mock" + ], + "scoring_components": [ + { + "name": "Component 1: Salesforce grace.liu role=Edit", + "weight": 0.15, + "description": "检查 Salesforce 中 grace.liu@meridianlabs.io 用户的 role 字段是否为 'Edit'", + "check_logic": "遍历 current.get('users', []),查找 email 为 'grace.liu@meridianlabs.io' 的用户,检查其 role 是否等于 'Edit'", + "pass_condition": "grace.liu@meridianlabs.io 存在且 role == 'Edit'" + }, + { + "name": "Component 2: Sheets Approvals rows 5/6/7", + "weight": 0.25, + "description": "检查 Google Sheets 'Approvals' 工作表第5-7行的 IAR 编号和审批状态", + "check_logic": "使用 _sheet_cell 获取 'Approvals' 工作表的 A5/H5、A6/H6、A7/H7,分别检查是否等于 IAR-401/Approved、IAR-402/Approved、IAR-403/Rejected", + "pass_condition": "A5=IAR-401 且 H5=Approved;A6=IAR-402 且 H6=Approved;A7=IAR-403 且 H7=Rejected" + }, + { + "name": "Component 3: Sheets Change Log row 6", + "weight": 0.15, + "description": "检查 Google Sheets 'Change Log' 工作表第6行的变更记录内容", + "check_logic": "使用 _sheet_cell 获取 'Change Log' 工作表的 A6、C6、F6、G6,检查是否分别等于 'CHG-2026-0706'、'Salesforce'、'Daniel Okafor'、'Completed'", + "pass_condition": "A6='CHG-2026-0706' 且 C6='Salesforce' 且 F6='Daniel Okafor' 且 G6='Completed'" + }, + { + "name": "Component 4: Docs July 2026 heading+bullet", + "weight": 0.15, + "description": "检查 Google Docs 'Integration Audit Log' 文档是否包含 'July 2026' h2 标题及包含特定 token 的项目符号", + "check_logic": "查找 title 为 'Integration Audit Log' 的文档,检查 content 是否包含 '

July 2026

',以及是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'CHG-2026-0706'、'IAR-404'", + "pass_condition": "文档存在,content 包含 '

July 2026

',且包含所有必需的 token" + }, + { + "name": "Component 5: Slack #sysadmin-updates message", + "weight": 0.15, + "description": "检查 Slack #sysadmin-updates 频道是否有包含指定 IAR token 的审计摘要消息", + "check_logic": "获取 'sysadmin-updates' 频道的所有消息,拼接 content,检查是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'IAR-404'", + "pass_condition": "#sysadmin-updates 频道至少有一条消息,且所有消息拼接后的文本包含全部4个 required token" + }, + { + "name": "Component 6: Teams General message", + "weight": 0.15, + "description": "检查 Microsoft Teams 'general' 频道是否有包含指定 IAR token 的审计摘要消息", + "check_logic": "获取 'general' 频道的所有消息,拼接 content,检查是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'IAR-404'", + "pass_condition": "'general' 频道至少有一条消息,且所有消息拼接后的文本包含全部4个 required token" + } + ], + "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 服务获取失败:对应组件检查失败得 0.0 分,但不影响其他组件", + "Salesforce 中找不到 grace.liu@meridianlabs.io 用户:Component 1 失败", + "Google Sheets 单元格值不匹配预期:Component 2/3 失败", + "Google Docs 找不到 'Integration Audit Log' 文档或内容缺少标题/token:Component 4 失败", + "Slack #sysadmin-updates 无消息或缺少 token:Component 5 失败", + "Teams 'general' 频道无消息或缺少 token:Component 6 失败" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接返回 0.0。随后从 5 个 mock 服务(salesforce、google_sheets、google_docs、slack、microsoft_teams)拉取 current_state。接着依次执行 6 个独立组件检查:Component 1 验证 Salesforce 用户角色;Component 2 和 3 分别验证 Google Sheets 的两个工作表特定单元格;Component 4 验证 Google Docs 文档标题和正文内容;Component 5 和 6 分别验证 Slack 和 Teams 特定频道的消息内容。每个组件通过时获得对应权重分数,失败则得 0。所有组件分数累加得到 total_score,最终通过 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: prof26_integration_audit_003(从 docstring 中明确提取)\n - Domain: mock_websites(从 docstring 中明确提取)\n\n2. **脚本功能概述**:\n - 这是一个跨系统集成审计任务,验证 6 个独立的 mock 服务中的更改。\n\n3. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - `salesforce` mock: `http://28.7.186.212:8195`\n - `google_sheets` mock: `http://28.7.186.212:8165`\n - `google_docs` mock: `http://28.7.186.212:8162`\n - `slack` mock: `http://28.7.186.212:8198`\n - `microsoft_teams` mock: `http://28.7.186.212:8182`\n\n4. **评分组件**:\n - Component 1 (0.15): Salesforce 中 grace.liu@meridianlabs.io 的 role 是否为 'Edit'\n - Component 2 (0.25): Google Sheets 'Approvals' 工作表的第 5/6/7 行是否为 IAR-401/402/403 及对应状态\n - Component 3 (0.15): Google Sheets 'Change Log' 工作表第 6 行是否为 CHG-2026-0706 等特定值\n - Component 4 (0.15): Google Docs 'Integration Audit Log' 是否有 'July 2026' h2 标题及包含特定 token 的 bullet\n - Component 5 (0.15): Slack #sysadmin-updates 频道是否有包含 IAR-401/402/403/404 的消息\n - Component 6 (0.15): Microsoft Teams 'general' 频道是否有包含 IAR-401/402/403/404 的消息\n\n5. **分数汇总**:\n - 各组件分数相加(total_score += score)\n - 最终分数 = round(min(total_score, 1.0), 4)\n - 总分上限 1.0\n\n6. **失败模式**:\n - 读取 `/tmp/task_web_sid` 失败或为空:打印 CRITICAL,REWARD: 0.0,sys.exit(0)\n - 任何 mock 获取失败:_fetch 返回 {},可能导致对应组件失败(但不会提前退出)\n - 各组件检查失败:对应组件得 0.0 分\n\n7. **is_placeholder**:\n - false,因为脚本有完整的检查逻辑。\n\n8. **confidence**:\n - 1.0,因为代码逻辑清晰完整。\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"prof26_integration_audit_003\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证跨系统集成审计任务在6个mock服务中引入的更改是否正确完成\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"salesforce_mock\", \"google_sheets_mock\", \"google_docs_mock\", \"slack_mock\", \"microsoft_teams_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1: Salesforce grace.liu role=Edit\",\n \"weight\": 0.15,\n \"description\": \"检查 Salesforce 中 grace.liu@meridianlabs.io 用户的 role 字段是否为 'Edit'\",\n \"check_logic\": \"遍历 users 列表,查找 email 为 'grace.liu@meridianlabs.io' 的用户,检查其 role 是否等于 'Edit'\",\n \"pass_condition\": \"grace.liu@meridianlabs.io 存在且 role == 'Edit'\"\n },\n {\n \"name\": \"Component 2: Sheets Approvals rows 5/6/7\",\n \"weight\": 0.25,\n \"description\": \"检查 Google Sheets 'Approvals' 工作表第5-7行的 IAR 编号和审批状态\",\n \"check_logic\": \"使用 _sheet_cell 获取 'Approvals' 工作表的 A5/H5、A6/H6、A7/H7,分别检查是否等于 IAR-401/Approved、IAR-402/Approved、IAR-403/Rejected\",\n \"pass_condition\": \"A5=IAR-401 且 H5=Approved;A6=IAR-402 且 H6=Approved;A7=IAR-403 且 H7=Rejected\"\n },\n {\n \"name\": \"Component 3: Sheets Change Log row 6\",\n \"weight\": 0.15,\n \"description\": \"检查 Google Sheets 'Change Log' 工作表第6行的变更记录内容\",\n \"check_logic\": \"使用 _sheet_cell 获取 'Change Log' 工作表的 A6、C6、F6、G6,检查是否分别等于 'CHG-2026-0706'、'Salesforce'、'Daniel Okafor'、'Completed'\",\n \"pass_condition\": \"A6='CHG-2026-0706' 且 C6='Salesforce' 且 F6='Daniel Okafor' 且 G6='Completed'\"\n },\n {\n \"name\": \"Component 4: Docs July 2026 heading+bullet\",\n \"weight\": 0.15,\n \"description\": \"检查 Google Docs 'Integration Audit Log' 文档是否包含 'July 2026' h2 标题及包含特定 token 的项目符号\",\n \"check_logic\": \"查找 title 为 'Integration Audit Log' 的文档,检查 content 是否包含 '

July 2026

',以及是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'CHG-2026-0706'、'IAR-404'\",\n \"pass_condition\": \"文档存在,content 包含 '

July 2026

',且包含所有必需的 token\"\n },\n {\n \"name\": \"Component 5: Slack #sysadmin-updates message\",\n \"weight\": 0.15,\n \"description\": \"检查 Slack #sysadmin-updates 频道是否有包含指定 IAR token 的审计摘要消息\",\n \"check_logic\": \"获取 'sysadmin-updates' 频道的所有消息,拼接 content,检查是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'IAR-404'\",\n \"pass_condition\": \"#sysadmin-updates 频道至少有一条消息,且所有消息拼接后的文本包含全部4个 required token\"\n },\n {\n \"name\": \"Component 6: Teams General message\",\n \"weight\": 0.15,\n \"description\": \"检查 Microsoft Teams 'general' 频道是否有包含指定 IAR token 的审计摘要消息\",\n \"check_logic\": \"获取 'general' 频道的所有消息,拼接 content,检查是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'IAR-404'\",\n \"pass_condition\": \"'general' 频道至少有一条消息,且所有消息拼接后的文本包含全部4个 required token\"\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 服务获取失败:对应组件检查失败得 0.0 分,但不影响其他组件\",\n \"Salesforce 中找不到 grace.liu@meridianlabs.io 用户:Component 1 失败\",\n \"Google Sheets 单元格值不匹配预期:Component 2/3 失败\",\n \"Google Docs 找不到 'Integration Audit Log' 文档或内容缺少标题/token:Component 4 失败\",\n \"Slack #sysadmin-updates 无消息或缺少 token:Component 5 失败\",\n \"Teams 'general' 频道无消息或缺少 token:Component 6 失败\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接返回 0.0。随后并行(字典推导)从 5 个 mock 服务(salesforce、google_sheets、google_docs、slack、microsoft_teams)拉取 current_state。接着依次执行 6 个独立组件检查:Component 1 验证 Salesforce 用户角色;Component 2 和 3 分别验证 Google Sheets 的两个工作表特定单元格;Component 4 验证 Google Docs 文档标题和正文内容;Component 5 和 6 分别验证 Slack 和 Teams 特定频道的消息内容。每个组件通过时获得对应权重分数,失败则得 0。所有组件分数累加得到 total_score,最终通过 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON 对象,不要 Markdown 代码块标记\n- 不要额外解释,不要思考过程,不要 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n- weight 填写代码中显式给出的分值\n\n确认 data_sources 的写法:代码中是从 MOCKS 字典对应的 URL 获取,可以写为 mock 服务名称或 URL。根据示例,写 mock 服务名更合适。\n\n确认 total_max_score:1.0\n\n确认 score_aggregation:代码中是 total_score += score,然后 final_score = round(min(total_score, 1.0), 4)\n\n确认 is_placeholder:false\n\n确认 confidence:1.0\n\n一切看起来正确。 {\"task_id\":\"prof26_integration_audit_003\",\"domain\":\"mock_websites\",\"summary\":\"验证跨系统集成审计任务在6个mock服务中引入的更改是否正确完成\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"salesforce_mock\",\"google_sheets_mock\",\"google_docs_mock\",\"slack_mock\",\"microsoft_teams_mock\"],\"scoring_components\":[{\"name\":\"Component 1: Salesforce grace.liu role=Edit\",\"weight\":0.15,\"description\":\"检查 Salesforce 中 grace.liu@meridianlabs.io 用户的 role 字段是否为 'Edit'\",\"check_logic\":\"遍历 current.get('users', []),查找 email 为 'grace.liu@meridianlabs.io' 的用户,检查其 role 是否等于 'Edit'\",\"pass_condition\":\"grace.liu@meridianlabs.io 存在且 role == 'Edit'\"},{\"name\":\"Component 2: Sheets Approvals rows 5/6/7\",\"weight\":0.25,\"description\":\"检查 Google Sheets 'Approvals' 工作表第5-7行的 IAR 编号和审批状态\",\"check_logic\":\"使用 _sheet_cell 获取 'Approvals' 工作表的 A5/H5、A6/H6、A7/H7,分别检查是否等于 IAR-401/Approved、IAR-402/Approved、IAR-403/Rejected\",\"pass_condition\":\"A5=IAR-401 且 H5=Approved;A6=IAR-402 且 H6=Approved;A7=IAR-403 且 H7=Rejected\"},{\"name\":\"Component 3: Sheets Change Log row 6\",\"weight\":0.15,\"description\":\"检查 Google Sheets 'Change Log' 工作表第6行的变更记录内容\",\"check_logic\":\"使用 _sheet_cell 获取 'Change Log' 工作表的 A6、C6、F6、G6,检查是否分别等于 'CHG-2026-0706'、'Salesforce'、'Daniel Okafor'、'Completed'\",\"pass_condition\":\"A6='CHG-2026-0706' 且 C6='Salesforce' 且 F6='Daniel Okafor' 且 G6='Completed'\"},{\"name\":\"Component 4: Docs July 2026 heading+bullet\",\"weight\":0.15,\"description\":\"检查 Google Docs 'Integration Audit Log' 文档是否包含 'July 2026' h2 标题及包含特定 token 的项目符号\",\"check_logic\":\"查找 title 为 'Integration Audit Log' 的文档,检查 content 是否包含 '

July 2026

',以及是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'CHG-2026-0706'、'IAR-404'\",\"pass_condition\":\"文档存在,content 包含 '

July 2026

',且包含所有必需的 token\"},{\"name\":\"Component 5: Slack #sysadmin-updates message\",\"weight\":0.15,\"description\":\"检查 Slack #sysadmin-updates 频道是否有包含指定 IAR token 的审计摘要消息\",\"check_logic\":\"获取 'sysadmin-updates' 频道的所有消息,拼接 content,检查是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'IAR-404'\",\"pass_condition\":\"#sysadmin-updates 频道至少有一条消息,且所有消息拼接后的文本包含全部4个 required token\"},{\"name\":\"Component 6: Teams General message\",\"weight\":0.15,\"description\":\"检查 Microsoft Teams 'general' 频道是否有包含指定 IAR token 的审计摘要消息\",\"check_logic\":\"获取 'general' 频道的所有消息,拼接 content,检查是否同时包含 'IAR-401'、'IAR-402'、'IAR-403'、'IAR-404'\",\"pass_condition\":\"'general' 频道至少有一条消息,且所有消息拼接后的文本包含全部4个 required token\"}],\"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 服务获取失败:对应组件检查失败得 0.0 分,但不影响其他组件\",\"Salesforce 中找不到 grace.liu@meridianlabs.io 用户:Component 1 失败\",\"Google Sheets 单元格值不匹配预期:Component 2/3 失败\",\"Google Docs 找不到 'Integration Audit Log' 文档或内容缺少标题/token:Component 4 失败\",\"Slack #sysadmin-updates 无消息或缺少 token:Component 5 失败\",\"Teams 'general' 频道无消息或缺少 token:Component 6 失败\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,若失败则直接返回 0.0。随后从 5 个 mock 服务(salesforce、google_sheets、google_docs、slack、microsoft_teams)拉取 current_state。接着依次执行 6 个独立组件检查:Component 1 验证 Salesforce 用户角色;Component 2 和 3 分别验证 Google Sheets 的两个工作表特定单元格;Component 4 验证 Google Docs 文档标题和正文内容;Component 5 和 6 分别验证 Slack 和 Teams 特定频道的消息内容。每个组件通过时获得对应权重分数,失败则得 0。所有组件分数累加得到 total_score,最终通过 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/prof35_escalate_overdue_001/_cua_gym_vm_bridge.sh b/legacy/prof35_escalate_overdue_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/prof35_escalate_overdue_001/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/prof35_escalate_overdue_001/initial_setup.py b/legacy/prof35_escalate_overdue_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4bc2fe4f63dfc3d4b28639113eb47327759999 --- /dev/null +++ b/legacy/prof35_escalate_overdue_001/initial_setup.py @@ -0,0 +1,357 @@ +""" +Initial Setup: prof35_escalate_overdue_001 +Task: Open Google Sheets 'Evidence Tracker' (tab 'Control Status'), find the 3 +'Overdue' rows, set Status -> 'Escalated', and post a Slack message to +#compliance-audit for each naming the Owner + Control ID. + +Domain: mock_websites (google_sheets_mock + slack_mock) + +This script sets up the PRE-TASK initial state in the INITIAL environment. + +CRITICAL — backend host & port discovery: + The reward script (reward.py) talks to the mock backend at host '172.17.0.1' + and discovers the Google Sheets / Slack mocks by SCANNING ports 8000-9001 for + their schema signatures. In this deployment the sheets mock is NOT at the + registry's 8145 and Slack is NOT at 8178 — they live on different ports of + '172.17.0.1' (e.g. sheets ~8120, slack ~8198). To stay consistent with the + reward script, this script uses the SAME host ('172.17.0.1') and discovers the + correct ports at runtime by scanning, rather than hardcoding any port number. +""" + +import os +import shlex +import subprocess +import time +import uuid +import json +import urllib.request +import urllib.error + +# --- Config: match the reward script's backend host exactly --- +MOCK_HOST = '172.17.0.1' +PORT_SCAN_START = 8000 +PORT_SCAN_END = 9001 +REQUEST_TIMEOUT = 3 + +# Generate a dedicated sid for THIS environment (initial_env) and persist it. +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +# --------------------------------------------------------------------------- +# Low-level HTTP helpers +# --------------------------------------------------------------------------- +def _http(method, port, path, payload=None): + url = f'http://{MOCK_HOST}:{port}{path}' + data = json.dumps(payload).encode() if payload is not None else None + req = urllib.request.Request( + url, data=data, method=method, + headers={'Content-Type': 'application/json'}) + try: + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as r: + return r.status, r.read().decode() + except urllib.error.HTTPError as e: + return e.code, e.read().decode() + except Exception as e: + return None, str(e) + + +def _get_state(port, s): + code, body = _http('GET', port, f'/go?sid={s}') + if code != 200: + return None + try: + return json.loads(body) + except Exception: + return None + + +# --------------------------------------------------------------------------- +# Runtime port discovery (mirrors reward.py's discovery logic) +# --------------------------------------------------------------------------- +def discover_slack_port(): + """Find the Slack mock: a state with channels + messages + currentUser. + Returns the lowest matching port, or None.""" + for port in range(PORT_SCAN_START, PORT_SCAN_END): + st, _ = _http('GET', port, f'/go?sid=_discovery_{port}') + if st != 200: + continue + d = _get_state(port, f'_discovery_{port}') + if not d: + continue + cs = d.get('initial_state') or {} + if not cs: + continue + if ('channels' in cs and 'messages' in cs and 'currentUser' in cs): + chans = cs.get('channels', []) + if isinstance(chans, list) and chans and isinstance(chans[0], dict): + return port + return None + + +def discover_sheets_port(): + """Find the Google Sheets mock. It returns empty default state, so we detect + it by a trial 'set' of a minimal sheets-shaped state, then reset it. + Returns the lowest matching port, or None.""" + trial_sid = '___setupgen_sheets_probe___' + for port in range(PORT_SCAN_START, PORT_SCAN_END): + st, _ = _http('POST', port, f'/post?sid={trial_sid}', { + 'action': 'set', + 'state': { + 'id': 'wb_probe', 'title': 'probe', + 'sheets': [{'id': 's1', 'name': 'Control Status', + 'data': {'A1': {'value': 'Control ID', 'formula': 'Control ID'}}, + 'rowCount': 10, 'colCount': 5}]}}) + if st != 200: + continue + d = _get_state(port, trial_sid) + if d and (d.get('initial_state') or {}).get('sheets'): + _http('POST', port, f'/post?sid={trial_sid}', {'action': 'reset'}) + return port + return None + + +# --------------------------------------------------------------------------- +# Google Sheets initial state +# --------------------------------------------------------------------------- +def build_sheets_state(): + rows = [ + ('CTRL-001', 'Access Control Policy', 'A. Park', 'Quarterly', '2026-04-01', 'On Track', 'drive://ev/ctrl001'), + ('CTRL-004', 'Password Rotation', 'K. Brown', 'Monthly', '2026-04-10', 'On Track', 'drive://ev/ctrl004'), + ('CTRL-007', 'Log Monitoring', 'S. Iyer', 'Monthly', '2026-04-18', 'In Review', 'drive://ev/ctrl007'), + ('CTRL-009', 'Asset Inventory', 'P. Nguyen', 'Quarterly', '2026-04-22', 'On Track', 'drive://ev/ctrl009'), + ('CTRL-011', 'Backup Verification', 'T. Roberts', 'Weekly', '2026-04-29', 'In Review', 'drive://ev/ctrl011'), + ('CTRL-014', 'MFA Enforcement', 'R. Mehta', 'Quarterly', '2026-05-12', 'Overdue', 'drive://ev/ctrl014'), + ('CTRL-018', 'Encryption at Rest', 'L. Wong', 'Quarterly', '2026-05-03', 'On Track', 'drive://ev/ctrl018'), + ('CTRL-021', 'Incident Logging', 'D. Cole', 'Monthly', '2026-05-08', 'In Review', 'drive://ev/ctrl021'), + ('CTRL-023', 'Phishing Training', 'M. Silva', 'Annual', '2026-05-15', 'On Track', 'drive://ev/ctrl023'), + ('CTRL-027', 'Data Retention Policy', 'J. Okafor', 'Annual', '2026-05-20', 'Overdue', 'drive://ev/ctrl027'), + ('CTRL-029', 'Network Segmentation', 'B. Ahmed', 'Quarterly', '2026-05-24', 'On Track', 'drive://ev/ctrl029'), + ('CTRL-031', 'Vulnerability Scanning', 'E. Tan', 'Weekly', '2026-05-26', 'In Review', 'drive://ev/ctrl031'), + ('CTRL-033', 'Vendor Access Review', 'L. Sato', 'Quarterly', '2026-05-28', 'Overdue', 'drive://ev/ctrl033'), + ('CTRL-035', 'DLP Configuration', 'C. Morales', 'Quarterly', '2026-06-02', 'On Track', 'drive://ev/ctrl035'), + ] + + headers = ['Control ID', 'Control Name', 'Owner', 'Review Cycle', + 'Due Date', 'Status', 'Evidence Link'] + header_style = {'bold': True, 'bg': '#E8EAED', 'align': 'center'} + + data = {} + for c, h in enumerate(headers): + col = chr(ord('A') + c) + data[f'{col}1'] = {'value': h, 'formula': h, 'style': header_style} + for i, row in enumerate(rows): + r = i + 2 + for c, val in enumerate(row): + col = chr(ord('A') + c) + data[f'{col}{r}'] = {'value': val, 'formula': val} + + sheet = { + 'id': 'sheet_1', + 'name': 'Control Status', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {'0': 110, '1': 180, '2': 130, '3': 120, '4': 120, '5': 110, '6': 200}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None, + 'data': data, + } + + return { + 'id': 'workbook_1', + 'title': 'Evidence Tracker', + 'activeSheetId': 'sheet_1', + 'selectedCell': 'A1', + 'selectionRange': None, + 'clipboard': None, + 'isDragging': False, + 'undoStack': [], + 'redoStack': [], + 'namedRanges': [], + 'conditionalFormats': [], + 'charts': [], + 'showGridlines': True, + 'showFormulas': False, + 'zoom': 100, + 'sheets': [sheet], + } + + +# --------------------------------------------------------------------------- +# Slack initial state +# --------------------------------------------------------------------------- +def build_slack_state(): + current_user = { + 'userId': 'user_1', + 'fullName': 'John Smith', + 'displayName': 'John', + 'email': 'john.smith@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Security Compliance Coordinator', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York', + } + + users = [ + current_user, + {'userId': 'user_2', 'fullName': 'Sarah Johnson', 'displayName': 'Sarah', + 'email': 'sarah.johnson@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Audit Lead', + 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'R. Mehta', 'displayName': 'R. Mehta', + 'email': 'r.mehta@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'IT Security', + 'status': 'active', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_4', 'fullName': 'J. Okafor', 'displayName': 'J. Okafor', + 'email': 'j.okafor@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Data Governance', + 'status': 'active', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_5', 'fullName': 'L. Sato', 'displayName': 'L. Sato', + 'email': 'l.sato@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=5', 'title': 'Vendor Risk', + 'status': 'active', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_6', 'fullName': 'P. Nguyen', 'displayName': 'P. Nguyen', + 'email': 'p.nguyen@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=6', 'title': 'Asset Mgmt', + 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_7', 'fullName': 'D. Cole', 'displayName': 'D. Cole', + 'email': 'd.cole@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=7', 'title': 'SOC Analyst', + 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_8', 'fullName': 'Rachel Lee', 'displayName': 'Rachel', + 'email': 'rachel.lee@acmecorp.com', + 'avatar': 'https://picsum.photos/200/200?random=8', 'title': 'Compliance Mgr', + 'status': 'online', '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', 'user_4', 'user_5', 'user_6', 'user_7', 'user_8'], + 'createdBy': 'user_1', 'createdAt': '2026-01-05T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'compliance-audit', 'name': 'compliance-audit', + 'description': 'SOX / security control evidence and audit coordination', + 'topic': 'Evidence Tracker reviews', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3', 'user_4', 'user_5', 'user_6', 'user_7', 'user_8'], + 'createdBy': 'user_1', 'createdAt': '2026-01-08T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'engineering', 'name': 'engineering', 'description': 'Eng team', + 'topic': '', 'isPrivate': False, 'isStarred': False, + 'members': ['user_1', 'user_2', 'user_3', 'user_7'], + 'createdBy': 'user_2', 'createdAt': '2026-01-05T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ] + + prior_messages = [ + {'messageId': 'msg_ca_1', 'senderId': 'user_8', + 'content': 'Reminder: Q2 control evidence collection opens next Monday. Please have your owners ready.', + 'timestamp': '2026-05-30T13:05:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_ca_2', 'senderId': 'user_2', + 'content': 'Audit schedule is posted in the drive. Control owners should review their due dates.', + 'timestamp': '2026-05-31T09:20:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_ca_3', 'senderId': 'user_1', + 'content': 'Thanks all. I will be following up on any controls still marked Overdue after the window closes.', + 'timestamp': '2026-06-01T10:00:00Z', 'threadId': None, 'reactions': [], + 'attachments': [], 'isEdited': False}, + ] + + messages = { + 'general': [ + {'messageId': 'msg_g_1', 'senderId': 'user_8', + 'content': 'Welcome to the new quarter everyone.', 'timestamp': '2026-06-01T08:00:00Z', + 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'compliance-audit': prior_messages, + 'engineering': [], + } + + 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(): + # Discover the correct ports on the reward script's backend host. + sheets_port = discover_sheets_port() + slack_port = discover_slack_port() + assert sheets_port, 'Could not discover Google Sheets mock port on 172.17.0.1' + assert slack_port, 'Could not discover Slack mock port on 172.17.0.1' + print(f'Discovered: sheets_port={sheets_port}, slack_port={slack_port} (host={MOCK_HOST})') + + sheets_url = f'http://{MOCK_HOST}:{sheets_port}' + slack_url = f'http://{MOCK_HOST}:{slack_port}' + + # Inject initial state into BOTH mocks. + sheets_state = build_sheets_state() + r, body = _http('POST', sheets_port, f'/post?sid={sid}', + {'action': 'set', 'state': sheets_state}) + assert r == 200, f'Sheets set failed ({r}): {body}' + print(f'Injected Google Sheets state: sid={sid}') + + slack_state = build_slack_state() + r, body = _http('POST', slack_port, f'/post?sid={sid}', + {'action': 'set', 'state': slack_state}) + assert r == 200, f'Slack set failed ({r}): {body}' + print(f'Injected Slack state: sid={sid}') + + # Verify the injected state is present and current==initial (pre-task). + sg = _get_state(sheets_port, sid) + sl = _get_state(slack_port, sid) + assert sg and sg['initial_state'], 'sheets initial_state is None' + assert sl and sl['initial_state'], 'slack initial_state is None' + assert not sg['state_diff'], 'sheets state_diff should be empty at init' + assert not sl['state_diff'], 'slack state_diff should be empty at init' + print('Verified: both initial states set; current==initial (pre-task)') + + # Launch Chrome for both mocks so the agent can interact with them. + launch_gui(f'google-chrome "{sheets_url}/?sid={sid}"', delay_sec=1.0) + launch_gui(f'google-chrome "{slack_url}/?sid={sid}"', delay_sec=1.0) + + # Wait for the mocks to serve the injected state (server-side readiness). + deadline = time.time() + 60.0 + pending = {'sheets': sheets_port, 'slack': slack_port} + while pending and time.time() < deadline: + for name, port in list(pending.items()): + try: + d = _get_state(port, sid) + if d and d.get('initial_state'): + del pending[name] + except Exception: + pass + if pending: + time.sleep(1.0) + print(f'GUI_READY: launched and verified Chrome for both mocks (sid={sid})') + + +if __name__ == '__main__': + main() diff --git a/legacy/prof35_escalate_overdue_001/reward.py b/legacy/prof35_escalate_overdue_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..1aadbec556c69882948c4df65e0c3315c087eb8a --- /dev/null +++ b/legacy/prof35_escalate_overdue_001/reward.py @@ -0,0 +1,308 @@ +""" +Reward Script: Escalate overdue controls in Google Sheets + post Slack messages +Task ID: prof35_escalate_overdue_001 +Domain: mock_websites (Google Sheets + Slack) +Scoring (progressive, 4 components summing to 1.0): + - Component 1 (0.3): 3 target rows CTRL-014, CTRL-027, CTRL-033 have Status exactly 'Escalated' + - Component 2 (0.3): Exactly 3 rows are 'Escalated' (distractors CTRL-009/CTRL-021 unchanged) + - Component 3 (0.2): #compliance-audit has exactly 3 new messages vs initial state + - Component 4 (0.2): Each new message names its Owner + Control ID + 'Escalated' + references overdue + +Verification is driven by TASK REQUIREMENTS: the reward script discovers the Google +Sheets mock (a sheet whose cell data contains 'CTRL-014') and the Slack mock (a +channel named 'compliance-audit') by scanning mock ports for their schema signatures. +It does NOT hardcode port numbers or success values. +""" +import json +import sys + +import requests + +# Mock servers are reached via the docker bridge gateway from inside the container. +MOCK_HOST = '172.17.0.1' +PORT_SCAN_START = 8000 +PORT_SCAN_END = 9001 +REQUEST_TIMEOUT = 3 + +# Target rows that must become 'Escalated' (from task instruction) +TARGET_ROWS = { + 'CTRL-014': 'R. Mehta', + 'CTRL-027': 'J. Okafor', + 'CTRL-033': 'L. Sato', +} +# Distractor rows that must NOT be escalated +DISTRACTOR_ROWS = {'CTRL-009', 'CTRL-021'} + + +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 + + +# ---------------------------------------------------------------------------- +# Mock discovery (driven by task requirements, not hardcoded ports) +# ---------------------------------------------------------------------------- + +def _fetch_state(port): + """Fetch current_state from a mock at the given port. Returns dict or None.""" + try: + resp = requests.get( + f'http://{MOCK_HOST}:{port}/go?sid={SID}', timeout=REQUEST_TIMEOUT) + resp.raise_for_status() + return resp.json().get('current_state', {}) + except Exception: + return None + + +def _find_google_sheets_port(): + """Locate the Google Sheets mock by schema signature. + The Evidence Tracker spreadsheet contains a cell with value 'CTRL-014'. + Returns the port, or None if not found. + """ + for port in range(PORT_SCAN_START, PORT_SCAN_END): + cs = _fetch_state(port) + if not cs or 'sheets' not in cs: + continue + for sheet in cs.get('sheets', []): + data = sheet.get('data', {}) + for cell in data.values(): + if isinstance(cell, dict) and cell.get('value') == 'CTRL-014': + return port + return None + + +def _find_slack_port(): + """Locate the Slack mock by schema signature. + The task requires a channel named 'compliance-audit'. + Returns the port, or None if not found. + """ + for port in range(PORT_SCAN_START, PORT_SCAN_END): + cs = _fetch_state(port) + if not cs or 'channels' not in cs or 'messages' not in cs: + continue + chans = cs.get('channels', []) + if isinstance(chans, list): + names = [c.get('name') for c in chans] + if 'compliance-audit' in names: + return port + return None + + +# ---------------------------------------------------------------------------- +# Google Sheets parsing +# ---------------------------------------------------------------------------- + +def _get_sheet_rows(cs): + """Parse the 'Control Status' sheet into a list of row dicts. + + Returns a list of {'control_id', 'owner', 'status'} for each data row. + """ + if not cs: + return [] + sheets = cs.get('sheets', []) + target = None + for sheet in sheets: + if sheet.get('name') == 'Control Status': + target = sheet + break + if target is None and sheets: + target = sheets[0] + if target is None: + return [] + data = target.get('data', {}) + + # Header row (row 1) -> column letter map + col_for = {} + for col in 'ABCDEFG': + cell = data.get(f'{col}1') + if cell and cell.get('value'): + col_for[str(cell.get('value')).strip().lower()] = col + + ctrl_col = col_for.get('control id') or col_for.get('control id ') + owner_col = None + status_col = None + for name, col in col_for.items(): + if 'owner' in name: + owner_col = col + elif 'status' in name: + status_col = col + if not ctrl_col or not status_col: + return [] + + rows = [] + for r in range(2, 100): + ctrl_cell = data.get(f'{ctrl_col}{r}') + if not ctrl_cell or not ctrl_cell.get('value'): + continue + ctrl_val = str(ctrl_cell.get('value')).strip() + owner_val = '' + if owner_col: + oc = data.get(f'{owner_col}{r}') + owner_val = str(oc.get('value')).strip() if oc and oc.get('value') else '' + status_val = '' + sc = data.get(f'{status_col}{r}') + status_val = str(sc.get('value')).strip() if sc and sc.get('value') else '' + rows.append({'control_id': ctrl_val, 'owner': owner_val, 'status': status_val}) + return rows + + +# ---------------------------------------------------------------------------- +# Per-component checks +# ---------------------------------------------------------------------------- + +def check_component_1(sheets_cs): + """3 target rows CTRL-014, CTRL-027, CTRL-033 each have Status exactly 'Escalated'. + Pass condition: all 3 target rows present with status == 'Escalated' (exact, case-sensitive). + """ + if not sheets_cs: + return False, 0.0, 'Google Sheets mock not found / no state' + rows = _get_sheet_rows(sheets_cs) + if not rows: + return False, 0.0, 'Control Status sheet not found or empty' + by_id = {row['control_id']: row for row in rows} + missing = [cid for cid in TARGET_ROWS if cid not in by_id] + if missing: + return False, 0.0, f'missing target rows: {missing}' + wrong = [f"{cid}={by_id[cid]['status']}" for cid in TARGET_ROWS + if by_id[cid]['status'] != 'Escalated'] + if wrong: + return False, 0.0, f'rows not exactly "Escalated": {wrong}' + return True, 0.3, 'All 3 target rows (CTRL-014, CTRL-027, CTRL-033) have Status exactly "Escalated"' + + +def check_component_2(sheets_cs): + """Exactly 3 rows are 'Escalated' and distractors CTRL-009/CTRL-021 are unchanged. + Pass condition: count of 'Escalated' rows == 3 AND no distractor row is 'Escalated'. + """ + if not sheets_cs: + return False, 0.0, 'Google Sheets mock not found / no state' + rows = _get_sheet_rows(sheets_cs) + if not rows: + return False, 0.0, 'Control Status sheet not found or empty' + escalated = [row['control_id'] for row in rows if row['status'] == 'Escalated'] + if len(escalated) != 3: + return False, 0.0, f'{len(escalated)} rows Escalated, expected exactly 3: {escalated}' + by_id = {row['control_id']: row for row in rows} + bad = [cid for cid in DISTRACTOR_ROWS + if cid in by_id and by_id[cid]['status'] == 'Escalated'] + if bad: + return False, 0.0, f'distractor row(s) incorrectly Escalated: {bad}' + return True, 0.3, 'Exactly 3 rows Escalated; distractors CTRL-009/CTRL-021 unchanged' + + +def check_component_3(new_msgs): + """#compliance-audit has exactly 3 new messages vs the initial state. + Pass condition: len(new_msgs) == 3. + """ + if new_msgs is None: + return False, 0.0, 'Slack mock / #compliance-audit not found' + if len(new_msgs) != 3: + return False, 0.0, f'{len(new_msgs)} new messages in #compliance-audit, expected exactly 3' + return True, 0.2, 'Exactly 3 new messages posted in #compliance-audit' + + +def check_component_4(new_msgs): + """Each of the 3 new messages names its Owner + Control ID + 'Escalated' + references overdue. + Pass condition: 3 new messages, and the union of matched Control IDs covers all 3 targets, + each message containing its Owner, Control ID, 'Escalated', and 'overdue'. + """ + if new_msgs is None: + return False, 0.0, 'Slack mock / #compliance-audit not found' + if len(new_msgs) != 3: + return False, 0.0, 'requires exactly 3 new messages (see component 3)' + matched_ids = set() + bad = [] + for msg in new_msgs: + content = (msg.get('content', '') if isinstance(msg, dict) else str(msg)).lower() + matched = None + for cid, owner in TARGET_ROWS.items(): + if (cid.lower() in content and owner.lower() in content + and 'escalated' in content and 'overdue' in content): + matched = cid + break + if matched: + matched_ids.add(matched) + else: + bad.append(content[:70]) + if matched_ids != set(TARGET_ROWS.keys()): + return False, 0.0, (f'matched Control IDs {sorted(matched_ids)} != all targets; ' + f'invalid msgs: {bad}') + return True, 0.2, 'All 3 messages name Owner+Control ID+"Escalated"+"overdue" covering CTRL-014/027/033' + + +# ---------------------------------------------------------------------------- +# Main +# ---------------------------------------------------------------------------- + +def verify_task(): + gs_port = _find_google_sheets_port() + slack_port = _find_slack_port() + + sheets_cs = _fetch_state(gs_port) if gs_port else None + slack_cs = _fetch_state(slack_port) if slack_port else None + + # Compute new Slack messages (#compliance-audit) by comparing current vs initial + new_msgs = None + if slack_port: + try: + resp = requests.get( + f'http://{MOCK_HOST}:{slack_port}/go?sid={SID}', timeout=REQUEST_TIMEOUT).json() + cur = resp.get('current_state', {}).get('messages', {}).get('compliance-audit', []) + init = resp.get('initial_state', {}).get('messages', {}).get('compliance-audit', []) + if len(cur) >= len(init): + new_msgs = cur[len(init):] + else: + new_msgs = [] + except Exception: + new_msgs = None + + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, '3 target rows Escalated', 0.3, check_component_1, (sheets_cs,)), + (2, 'Exactly 3 Escalated (distractors safe)', 0.3, check_component_2, (sheets_cs,)), + (3, '3 new Slack messages', 0.2, check_component_3, (new_msgs,)), + (4, 'Messages name Owner+CtrlID+Escalated+overdue', 0.2, check_component_4, (new_msgs,)), + ]: + _, 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 + + +def main(): + global 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) + verify_task() + + +if __name__ == '__main__': + main() diff --git a/legacy/prof35_escalate_overdue_001/reward_label.json b/legacy/prof35_escalate_overdue_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..4defd4b1a44c04d138df5469a32318b6a5901d5c --- /dev/null +++ b/legacy/prof35_escalate_overdue_001/reward_label.json @@ -0,0 +1,64 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof35_escalate_overdue_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:48", + "label": { + "task_id": "prof35_escalate_overdue_001", + "domain": "mock_websites", + "summary": "验证在 Google Sheets 中将 3 个目标控制行状态设为 Escalated,并在 Slack #compliance-audit 频道发布 3 条包含负责人、控制 ID、Escalated 及 overdue 的新消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "Google Sheets mock(通过端口扫描依据 CTRL-014 单元格发现)", + "Slack mock(通过端口扫描依据 compliance-audit 频道发现)" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.3, + "description": "3 个目标行 CTRL-014、CTRL-027、CTRL-033 的状态必须恰好为 Escalated", + "check_logic": "解析 Control Status 工作表,按 control_id 索引,检查 TARGET_ROWS 中 3 个控制 ID 对应的 status 字段是否均精确等于 'Escalated'(区分大小写)", + "pass_condition": "3 个目标行均存在且 status 精确等于 'Escalated'" + }, + { + "name": "Component 2", + "weight": 0.3, + "description": "恰好有 3 行的状态为 Escalated,且干扰行未被修改", + "check_logic": "遍历所有行统计 status == 'Escalated' 的数量,并检查 DISTRACTOR_ROWS(CTRL-009、CTRL-021)的状态不是 Escalated", + "pass_condition": "Escalated 行数恰好为 3,且干扰行状态未被设为 Escalated" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "Slack #compliance-audit 频道相比初始状态恰好新增 3 条消息", + "check_logic": "比较 Slack mock 返回的 current_state 与 initial_state 中 compliance-audit 频道的消息列表,取差值 cur[len(init):],检查长度是否等于 3", + "pass_condition": "新消息数量恰好为 3" + }, + { + "name": "Component 4", + "weight": 0.2, + "description": "每条新消息都包含对应负责人、控制 ID、Escalated 和 overdue", + "check_logic": "遍历 3 条新消息,将 content 转小写后检查是否同时包含对应控制 ID、对应负责人(Owner)、'escalated' 和 'overdue',且 3 条消息合起来覆盖全部 3 个目标控制 ID", + "pass_condition": "3 条消息分别覆盖 CTRL-014/027/033,且每条都包含其 Owner、Control ID、'Escalated' 和 'overdue'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数累加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 SID 时脚本返回 0.0 并提前退出", + "端口扫描未找到 Google Sheets mock 或 Slack mock", + "Control Status 工作表未找到或为空", + "目标控制行(CTRL-014/027/033)缺失", + "目标行状态不是精确等于 Escalated", + "Escalated 行总数不等于恰好 3", + "干扰行 CTRL-009/CTRL-021 被错误设为 Escalated", + "Slack #compliance-audit 新消息数量不是恰好 3", + "消息内容缺少对应的 Owner、Control ID、Escalated 或 overdue 关键词" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID;然后通过扫描 8000-9001 端口自动发现 Google Sheets mock(依据包含 CTRL-014 单元格的 schema 签名)和 Slack mock(依据包含 compliance-audit 频道的 schema 签名)。接着拉取两者的 current_state,并计算 Slack #compliance-audit 频道当前消息与初始消息的差值得到 new_msgs。之后依次执行 4 个评分组件:组件 1 验证 3 个目标行状态均为 Escalated;组件 2 验证全表恰好只有 3 行 Escalated 且干扰行未被改动;组件 3 验证 Slack 频道恰好新增 3 条消息;组件 4 验证这 3 条消息的内容分别包含对应负责人、控制 ID、Escalated 和 overdue 关键词,且覆盖全部 3 个目标控制 ID。每个组件通过时获得对应权重分数,最终总分累加后通过 min(total_score, 1.0) 钳制并四舍五入到 4 位小数输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: prof35_escalate_overdue_001\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (Google Sheets + Slack)\"\n3. **summary**: 一句话概括:验证在 Google Sheets 中将指定 3 行状态改为 Escalated,并在 Slack #compliance-audit 频道发布 3 条包含负责人、控制ID、Escalated 和 overdue 的新消息。\n4. **is_placeholder**: false,因为脚本有完整的检查逻辑。\n5. **data_sources**: \n - /tmp/task_web_sid (读取 SID)\n - Google Sheets mock (通过端口扫描发现,包含 'CTRL-014' 的 sheet)\n - Slack mock (通过端口扫描发现,包含 'compliance-audit' 频道)\n6. **scoring_components**:\n - Component 1: weight 0.3, 检查 3 个目标行 (CTRL-014, CTRL-027, CTRL-033) 的状态是否为 'Escalated'\n - Component 2: weight 0.3, 检查恰好有 3 行是 'Escalated',且干扰行 (CTRL-009, CTRL-021) 未被修改\n - Component 3: weight 0.2, 检查 #compliance-audit 频道恰好有 3 条新消息\n - Component 4: weight 0.2, 检查每条新消息都包含其负责人、控制ID、\"Escalated\" 和 \"overdue\"\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 - 找不到 Google Sheets mock 或 Slack mock\n - Control Status sheet 未找到或为空\n - 目标行缺失\n - 目标行状态不是 \"Escalated\"\n - Escalated 行数不是恰好 3 个\n - 干扰行被错误地设为 Escalated\n - Slack 新消息数量不是恰好 3 条\n - 消息内容不匹配要求(缺少负责人、控制ID、Escalated 或 overdue)\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 从 /tmp/task_web_sid 读取 SID\n - 扫描 8000-9000 端口发现 Google Sheets mock(通过包含 CTRL-014 的单元格)和 Slack mock(通过 compliance-audit 频道)\n - 获取两个 mock 的 current_state\n - 计算 Slack 新消息数(current_state.messages.compliance-audit 与 initial_state 对比)\n - 依次运行 4 个组件检查:\n 1. 目标行状态是否为 Escalated\n 2. 恰好 3 行 Escalated 且干扰行未变\n 3. 恰好 3 条新 Slack 消息\n 4. 消息内容包含负责人、控制ID、Escalated、overdue\n - 各组件分数累加,上限 1.0,四舍五入到 4 位小数\n11. **confidence**: 1.0,因为代码逻辑清晰完整。\n\n现在构建 JSON,确保:\n- 只输出 JSON,没有 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- weight 使用代码中显式给出的分值\n\n让我再仔细检查一下各个字段:\n\ntask_id: \"prof35_escalate_overdue_001\"\ndomain: \"mock_websites\"\nsummary: \"验证在 Google Sheets 中将 3 个目标控制行状态设为 Escalated,并在 Slack #compliance-audit 频道发布 3 条包含负责人、控制 ID、Escalated 及 overdue 的新消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"Google Sheets mock\", \"Slack mock\"]\n\nscoring_components:\n1. name: \"Component 1\", weight: 0.3, description: \"3 个目标行 CTRL-014、CTRL-027、CTRL-033 的状态必须恰好为 Escalated\", check_logic: \"解析 Control Status 工作表,检查 TARGET_ROWS 中 3 个控制 ID 对应的 status 字段是否均等于 'Escalated'(区分大小写)\", pass_condition: \"3 个目标行均存在且 status 精确等于 'Escalated'\"\n2. name: \"Component 2\", weight: 0.3, description: \"恰好有 3 行的状态为 Escalated,且干扰行未被修改\", check_logic: \"统计所有 status == 'Escalated' 的行数,并检查 DISTRACTOR_ROWS(CTRL-009、CTRL-021)的状态不是 Escalated\", pass_condition: \"Escalated 行数恰好为 3,且干扰行状态未被设为 Escalated\"\n3. name: \"Component 3\", weight: 0.2, description: \"Slack #compliance-audit 频道相比初始状态恰好新增 3 条消息\", check_logic: \"比较 current_state 与 initial_state 中 compliance-audit 频道的消息列表,取差值 len(cur) - len(init),检查是否等于 3\", pass_condition: \"新消息数量恰好为 3\"\n4. name: \"Component 4\", weight: 0.2, description: \"每条新消息都包含对应负责人、控制 ID、Escalated 和 overdue\", check_logic: \"遍历 3 条新消息,将 content 转小写后检查是否同时包含对应控制 ID、对应负责人、'escalated' 和 'overdue',且 3 条消息合起来覆盖全部 3 个目标控制 ID\", pass_condition: \"3 条消息分别覆盖 CTRL-014/027/033,且每条都包含其 Owner、Control ID、'Escalated' 和 'overdue'\"\n\nscore_aggregation: \"各组件分数累加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\"\n\nfailure_modes:\n- \"无法从 /tmp/task_web_sid 读取 SID 时脚本返回 0.0 并退出\"\n- \"端口扫描未找到 Google Sheets mock 或 Slack mock\"\n- \"Control Status 工作表未找到或为空\"\n- \"目标控制行缺失\"\n- \"目标行状态不是精确等于 Escalated\"\n- \"Escalated 行总数不等于恰好 3\"\n- \"干扰行 CTRL-009/CTRL-021 被错误设为 Escalated\"\n- \"Slack #compliance-audit 新消息数量不是恰好 3\"\n- \"消息内容缺少对应的 Owner、Control ID、Escalated 或 overdue 关键词\"\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID;然后通过扫描 8000-9001 端口自动发现 Google Sheets mock(依据包含 CTRL-014 单元格的 schema 签名)和 Slack mock(依据包含 compliance-audit 频道的 schema 签名)。接着拉取两者的 current_state,并计算 Slack #compliance-audit 频道当前消息与初始消息的差值得到 new_msgs。之后依次执行 4 个评分组件:组件 1 验证 3 个目标行状态均为 Escalated;组件 2 验证全表恰好只有 3 行 Escalated 且干扰行未被改动;组件 3 验证 Slack 频道恰好新增 3 条消息;组件 4 验证这 3 条消息的内容分别包含对应负责人、控制 ID、Escalated 和 overdue 关键词,且覆盖全部 3 个目标控制 ID。每个组件通过时获得对应权重分数,最终总分累加后通过 min(total_score, 1.0) 钳制并四舍五入到 4 位小数输出。\"\n\nconfidence: 1.0\n\n确保 JSON 格式正确,没有多余内容。 {\"task_id\":\"prof35_escalate_overdue_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Google Sheets 中将 3 个目标控制行状态设为 Escalated,并在 Slack #compliance-audit 频道发布 3 条包含负责人、控制 ID、Escalated 及 overdue 的新消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"Google Sheets mock(通过端口扫描依据 CTRL-014 单元格发现)\",\"Slack mock(通过端口扫描依据 compliance-audit 频道发现)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.3,\"description\":\"3 个目标行 CTRL-014、CTRL-027、CTRL-033 的状态必须恰好为 Escalated\",\"check_logic\":\"解析 Control Status 工作表,按 control_id 索引,检查 TARGET_ROWS 中 3 个控制 ID 对应的 status 字段是否均精确等于 'Escalated'(区分大小写)\",\"pass_condition\":\"3 个目标行均存在且 status 精确等于 'Escalated'\"},{\"name\":\"Component 2\",\"weight\":0.3,\"description\":\"恰好有 3 行的状态为 Escalated,且干扰行未被修改\",\"check_logic\":\"遍历所有行统计 status == 'Escalated' 的数量,并检查 DISTRACTOR_ROWS(CTRL-009、CTRL-021)的状态不是 Escalated\",\"pass_condition\":\"Escalated 行数恰好为 3,且干扰行状态未被设为 Escalated\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"Slack #compliance-audit 频道相比初始状态恰好新增 3 条消息\",\"check_logic\":\"比较 Slack mock 返回的 current_state 与 initial_state 中 compliance-audit 频道的消息列表,取差值 cur[len(init):],检查长度是否等于 3\",\"pass_condition\":\"新消息数量恰好为 3\"},{\"name\":\"Component 4\",\"weight\":0.2,\"description\":\"每条新消息都包含对应负责人、控制 ID、Escalated 和 overdue\",\"check_logic\":\"遍历 3 条新消息,将 content 转小写后检查是否同时包含对应控制 ID、对应负责人(Owner)、'escalated' 和 'overdue',且 3 条消息合起来覆盖全部 3 个目标控制 ID\",\"pass_condition\":\"3 条消息分别覆盖 CTRL-014/027/033,且每条都包含其 Owner、Control ID、'Escalated' 和 'overdue'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 SID 时脚本返回 0.0 并提前退出\",\"端口扫描未找到 Google Sheets mock 或 Slack mock\",\"Control Status 工作表未找到或为空\",\"目标控制行(CTRL-014/027/033)缺失\",\"目标行状态不是精确等于 Escalated\",\"Escalated 行总数不等于恰好 3\",\"干扰行 CTRL-009/CTRL-021 被错误设为 Escalated\",\"Slack #compliance-audit 新消息数量不是恰好 3\",\"消息内容缺少对应的 Owner、Control ID、Escalated 或 overdue 关键词\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID;然后通过扫描 8000-9001 端口自动发现 Google Sheets mock(依据包含 CTRL-014 单元格的 schema 签名)和 Slack mock(依据包含 compliance-audit 频道的 schema 签名)。接着拉取两者的 current_state,并计算 Slack #compliance-audit 频道当前消息与初始消息的差值得到 new_msgs。之后依次执行 4 个评分组件:组件 1 验证 3 个目标行状态均为 Escalated;组件 2 验证全表恰好只有 3 行 Escalated 且干扰行未被改动;组件 3 验证 Slack 频道恰好新增 3 条消息;组件 4 验证这 3 条消息的内容分别包含对应负责人、控制 ID、Escalated 和 overdue 关键词,且覆盖全部 3 个目标控制 ID。每个组件通过时获得对应权重分数,最终总分累加后通过 min(total_score, 1.0) 钳制并四舍五入到 4 位小数输出。\",\"confidence\":1.0}" +} diff --git a/legacy/prof45_roster_invite_001/_cua_gym_vm_bridge.sh b/legacy/prof45_roster_invite_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/prof45_roster_invite_001/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/prof45_roster_invite_001/initial_setup.py b/legacy/prof45_roster_invite_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b78732ae53783736c24ace8af62169372774d7ee --- /dev/null +++ b/legacy/prof45_roster_invite_001/initial_setup.py @@ -0,0 +1,270 @@ +""" +Initial Setup: Q3 Data Literacy Cohort roster invite +Task ID: prof45_roster_invite_001 +Domain: mock_websites +Mock: google_sheets_mock (http://28.7.186.212:8165) + +This script establishes the PRE-TASK state: + - A Google Sheets workbook titled 'Q3 Data Literacy Cohort' + - A 'Roster' sheet with header row (A:H) and exactly 4 existing rows (rows 2-5) + - Row 6 is intentionally EMPTY (the agent must add it) + - 'Sessions' and 'Materials' sheets with supporting content (must not be altered) + +It injects the state via action:"set" (creates initial_state + current_state) +under a deterministic sid (task_id), launches Chrome, and waits for render. +The sid is NOT written to /tmp/task_web_sid — reward.py falls back to the +same deterministic sid when the temp file is absent (see reward.py). +""" + +import os +import shlex +import subprocess +import time + +import requests + +# --- Config --- +BASE_URL = "http://28.7.186.212:8165" +TASK_ID = "prof45_roster_invite_001" + +# The mock server is SHARED external state (not per-VM). Both initial_env and +# golden_env operate on the same workbook, so they MUST use the SAME sid. +# We derive a deterministic sid from the task_id so both scripts agree without +# needing to share a temp file across separate VMs. +sid = f"prof45_roster_invite_001" + +# --------------------------------------------------------------------------- +# Build the full initial workbook state +# --------------------------------------------------------------------------- +ROSTER_HEADERS = { + "A1": "Employee ID", + "B1": "Name", + "C1": "Department", + "D1": "Session", + "E1": "Enrolled", + "F1": "Prep Sent", + "G1": "Completion", + "H1": "Feedback Score", +} +HEADER_STYLE = {"bold": True, "bg": "#E8EAED", "align": "center"} + + +def cell(value, fmt=None, style=None): + """Construct a minimal CellData dict matching the schema.""" + cd = {"value": value, "formula": value} + if fmt is not None: + cd["format"] = fmt + if style is not None: + cd["style"] = style + return cd + + +# The 4 existing roster rows (rows 2-5), byte-for-byte preserved in golden. +roster_rows = { + 2: ["EMP-2047", "Marcus Lee", "Sales", "Session A (Aug 07)", "Yes", "Yes", "Completed", 4], + 3: ["EMP-2048", "Priya Nair", "Engineering", "Session A (Aug 07)", "Yes", "Yes", "Completed", 5], + 4: ["EMP-2049", "Tom Becker", "Finance", "Session B (Aug 14)", "Yes", "No", "Pending", ""], + 5: ["EMP-2050", "Sara Kim", "Marketing", "Session B (Aug 14)", "Yes", "No", "Pending", ""], +} + +roster_data = {} +# Header row +for col, h in ROSTER_HEADERS.items(): + roster_data[col] = cell(h, style=HEADER_STYLE) +# Existing 4 rows +for r, vals in roster_rows.items(): + for ci, (col_letter, v) in enumerate(zip("ABCDEFGH", vals)): + key = f"{col_letter}{r}" + fmt = "number" if col_letter == "H" and isinstance(v, int) else None + roster_data[key] = cell(v, fmt=fmt) + +# Row 6 is intentionally NOT present in the initial state. + +roster_sheet = { + "id": "sheet_1", + "name": "Roster", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": None, + "isHidden": False, + "columnWidths": {"0": 130, "1": 150, "2": 150, "3": 180, "4": 100, "5": 100, "6": 110, "7": 130}, + "rowHeights": {}, + "filterRange": None, + "filterCriteria": {}, + "sortColumn": None, + "sortDirection": None, + "data": roster_data, +} + +# Sessions sheet (supporting content, must not be altered) +sessions_data = { + "A1": cell("Session", {"bold": True, "bg": "#E8EAED"}), + "B1": cell("Date", {"bold": True, "bg": "#E8EAED"}), + "C1": cell("Room", {"bold": True, "bg": "#E8EAED"}), + "D1": cell("Instructor", {"bold": True, "bg": "#E8EAED"}), + "A2": cell("Session A (Aug 07)"), + "B2": cell("2025-08-07"), + "C2": cell("Conf Room 3"), + "D2": cell("Dr. Alan Reyes"), + "A3": cell("Session B (Aug 14)"), + "B3": cell("2025-08-14"), + "C3": cell("Conf Room 5"), + "D3": cell("Dr. Alan Reyes"), +} +sessions_sheet = { + "id": "sheet_2", + "name": "Sessions", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": "#1A73E8", + "isHidden": False, + "columnWidths": {"0": 180, "1": 120, "2": 120, "3": 160}, + "rowHeights": {}, + "filterRange": None, + "filterCriteria": {}, + "sortColumn": None, + "sortDirection": None, + "data": sessions_data, +} + +# Materials sheet (supporting content, must not be altered) +materials_data = { + "A1": cell("Item", {"bold": True, "bg": "#E8EAED"}), + "B1": cell("Link", {"bold": True, "bg": "#E8EAED"}), + "A2": cell("Pre-Course Survey"), + "B2": cell("forms.northwind/survey-q3"), + "A3": cell("Data Literacy Handbook"), + "B3": cell("drive.northwind/handbook-q3"), + "A4": cell("Practice Dataset"), + "B4": cell("drive.northwind/dataset-q3"), +} +materials_sheet = { + "id": "sheet_3", + "name": "Materials", + "rowCount": 100, + "colCount": 26, + "frozenRows": 1, + "frozenCols": 0, + "tabColor": "#0F9D58", + "isHidden": False, + "columnWidths": {"0": 200, "1": 280}, + "rowHeights": {}, + "filterRange": None, + "filterCriteria": {}, + "sortColumn": None, + "sortDirection": None, + "data": materials_data, +} + +state = { + "id": "workbook_1", + "title": "Q3 Data Literacy Cohort", + "activeSheetId": "sheet_1", + "selectedCell": "A1", + "selectionRange": None, + "clipboard": None, + "isDragging": False, + "undoStack": [], + "redoStack": [], + "namedRanges": [], + "conditionalFormats": [], + "charts": [], + "showGridlines": True, + "showFormulas": False, + "zoom": 100, + "sheets": [roster_sheet, sessions_sheet, materials_sheet], +} + +# --------------------------------------------------------------------------- +# Inject initial 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" +assert go["initial_state"]["title"] == "Q3 Data Literacy Cohort" +print("Verified: initial_state and current_state are set") + +# --------------------------------------------------------------------------- +# Launch browser + wait for render +# --------------------------------------------------------------------------- +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) + + +def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0): + """Block until the 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) — blank/stuck loading" + ) + print(f"[{name}] rendered OK ({len(html)} bytes)") + finally: + page.close() + finally: + browser.close() + + +wait_for_mocks_loaded({"primary": BASE_URL}, sid) +print(f"GUI_READY: launched and verified browser at {BASE_URL}/?sid={sid}") diff --git a/legacy/prof45_roster_invite_001/reward.py b/legacy/prof45_roster_invite_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..da7ac285030338dabfffa2f1262633e927694bff --- /dev/null +++ b/legacy/prof45_roster_invite_001/reward.py @@ -0,0 +1,227 @@ +""" +Reward Script: Add a new roster row to the 'Roster' sheet of 'Q3 Data Literacy Cohort' +Task ID: prof45_roster_invite_001 +Domain: mock_websites +Mock: google_sheets_mock (http://28.7.186.212:8165) +Scoring: Verify Row 6 of the 'Roster' sheet contains the exact required values + (EMP-2051 / Dana Whitfield / Customer Success / Session B (Aug 14) / + Yes / No / Pending / blank), and that the 4 pre-existing rows (2-5) + are preserved unchanged. +""" +import json + +import requests + +BASE_URL = 'http://28.7.186.212:8165' + +# Deterministic sid matching initial_setup.py — the setup script injects state +# under this sid and intentionally does NOT write /tmp/task_web_sid (see +# initial_setup.py comment: "derive a deterministic sid from the task_id so +# both scripts agree without needing to share a temp file across separate VMs"). +DETERMINISTIC_SID = 'prof45_roster_invite_001' + +# Expected Row 6 values per task_config.json context (ground truth) +EXPECTED_ROW6 = { + 'A': 'EMP-2051', + 'B': 'Dana Whitfield', + 'C': 'Customer Success', + 'D': 'Session B (Aug 14)', + 'E': 'Yes', + 'F': 'No', + 'G': 'Pending', + 'H': '', # blank / empty +} + +# Expected rows 2-5 (must remain byte-for-byte unchanged) +EXPECTED_ROWS_2_5 = { + 2: ['EMP-2047', 'Marcus Lee', 'Sales', 'Session A (Aug 07)', 'Yes', 'Yes', 'Completed', 4], + 3: ['EMP-2048', 'Priya Nair', 'Engineering', 'Session A (Aug 07)', 'Yes', 'Yes', 'Completed', 5], + 4: ['EMP-2049', 'Tom Becker', 'Finance', 'Session B (Aug 14)', 'Yes', 'No', 'Pending', ''], + 5: ['EMP-2050', 'Sara Kim', 'Marketing', 'Session B (Aug 14)', 'Yes', 'No', 'Pending', ''], +} + + +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility. + + Parsed by the evaluator to report which sub-objectives passed/failed + instead of only a single aggregate float. Format: ``COMPONENT: ``. + """ + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check function, emit PASS/FAIL + COMPONENT line. + + Args: + idx: component id (1-based). + name: short component name. + weight: max points for this component. + fn: a ``check_component_N`` function returning (passed, score, detail). + args: tuple of positional args for fn. + + Returns: + (passed, score, detail) — score is 0.0 on exception. + """ + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +def _find_roster_sheet(state): + """Return the 'Roster' sheet dict from a workbook state, or None.""" + if not state: + return None + for s in state.get('sheets', []): + if s.get('name') == 'Roster': + return s + return None + + +def _cell_value(sheet, col, row): + """Return the normalized cell value for a given column+row, or None if absent.""" + if not sheet: + return None + cell = sheet.get('data', {}).get(f'{col}{row}') + if not cell: + return None + return cell.get('value') + + +def check_component_1(roster): + """Row 6 has Employee ID 'EMP-2051' in A6 and Name 'Dana Whitfield' in B6. + Pass condition: A6 == 'EMP-2051' AND B6 == 'Dana Whitfield' (both present and exact). + """ + a6 = _cell_value(roster, 'A', 6) + b6 = _cell_value(roster, 'B', 6) + if a6 == 'EMP-2051' and b6 == 'Dana Whitfield': + return True, 0.3, f'A6={a6!r}, B6={b6!r}' + return False, 0.0, f'expected A6=EMP-2051, B6=Dana Whitfield; found A6={a6!r}, B6={b6!r}' + + +def check_component_2(roster): + """Row 6 has Department 'Customer Success' in C6 and Session 'Session B (Aug 14)' in D6. + Pass condition: C6 == 'Customer Success' AND D6 == 'Session B (Aug 14)'. + """ + c6 = _cell_value(roster, 'C', 6) + d6 = _cell_value(roster, 'D', 6) + if c6 == 'Customer Success' and d6 == 'Session B (Aug 14)': + return True, 0.3, f'C6={c6!r}, D6={d6!r}' + return False, 0.0, f'expected C6=Customer Success, D6=Session B (Aug 14); found C6={c6!r}, D6={d6!r}' + + +def check_component_3(roster, initial_roster): + """Row 6 has Enrolled='Yes', Prep Sent='No', Completion='Pending' in E6/G6, + Feedback Score blank in H6, AND the 4 pre-existing rows (2-5) are unchanged + from initial_state. + Pass condition: E6=='Yes', F6=='No', G6=='Pending', H6 is blank/empty, + and rows 2-5 match EXPECTED_ROWS_2_5 exactly. + """ + e6 = _cell_value(roster, 'E', 6) + f6 = _cell_value(roster, 'F', 6) + g6 = _cell_value(roster, 'G', 6) + h6 = _cell_value(roster, 'H', 6) + # H6 must be blank: normalize None and '' to empty + h6_blank = (h6 is None or h6 == '') + + fields_ok = (e6 == 'Yes' and f6 == 'No' and g6 == 'Pending' and h6_blank) + if not fields_ok: + return False, 0.0, ( + f'expected E6=Yes, F6=No, G6=Pending, H6=blank; ' + f'found E6={e6!r}, F6={f6!r}, G6={g6!r}, H6={h6!r}' + ) + + # Verify rows 2-5 are preserved unchanged (anti-tamper). + # We compare against the EXPECTED_ROWS_2_5 ground truth (which equals initial_state). + for row in (2, 3, 4, 5): + actual = [_cell_value(roster, c, row) for c in 'ABCDEFGH'] + expected = EXPECTED_ROWS_2_5[row] + if actual != expected: + return False, 0.0, ( + f'row {row} was modified (expected {expected}, found {actual})' + ) + + return True, 0.4, 'E6/G6/F6/H6 correct and rows 2-5 preserved unchanged' + + +def verify_task(): + """Verify task completion against the mock server state. + + Returns: float between 0.0 and 1.0 + """ + # --- Read sid --- + # Prefer /tmp/task_web_sid when present (generic template contract); fall + # back to the deterministic sid that initial_setup.py injects under. + # Without this fallback, reward always returns 0.0 because the setup script + # never writes the temp file. + sid = None + try: + with open('/tmp/task_web_sid') as f: + sid = f.read().strip() + except FileNotFoundError: + pass + if not sid: + sid = DETERMINISTIC_SID + print(f'WARN: /tmp/task_web_sid missing; using deterministic sid={sid!r}') + + # --- Fetch state from the 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') + initial_state = data.get('initial_state') + + if not current_state: + print('CRITICAL: current_state is empty for this sid') + print('REWARD: 0.0') + return 0.0 + + roster = _find_roster_sheet(current_state) + initial_roster = _find_roster_sheet(initial_state) + + if roster is None: + print('CRITICAL: No "Roster" sheet found in current_state') + print('REWARD: 0.0') + return 0.0 + + total_score = 0.0 + + # Independent components: dispatch via a table. + for idx, name, weight, fn, args in [ + (1, 'Row 6 Employee ID + Name', 0.3, check_component_1, (roster,)), + (2, 'Row 6 Department + Session', 0.3, check_component_2, (roster,)), + (3, 'Row 6 Enrolled/Prep/Completion/Feedback + rows 2-5 preserved', 0.4, + check_component_3, (roster, initial_roster)), + ]: + _, 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/legacy/prof45_roster_invite_001/reward_label.json b/legacy/prof45_roster_invite_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..3052a1bd9722dba9f393a56318ebba7b31f4da34 --- /dev/null +++ b/legacy/prof45_roster_invite_001/reward_label.json @@ -0,0 +1,52 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof45_roster_invite_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": "prof45_roster_invite_001", + "domain": "mock_websites", + "summary": "验证在 Google Sheets 的 'Roster' 工作表第 6 行添加了指定的新员工数据,且原有第 2-5 行未被修改", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "google_sheets_mock (http://28.7.186.212:8165)" + ], + "scoring_components": [ + { + "name": "Row 6 Employee ID + Name", + "weight": 0.3, + "description": "检查第 6 行的员工编号和姓名是否正确", + "check_logic": "调用 _cell_value(roster, 'A', 6) 和 _cell_value(roster, 'B', 6),判断 A6 是否等于 'EMP-2051' 且 B6 是否等于 'Dana Whitfield'", + "pass_condition": "A6 == 'EMP-2051' 且 B6 == 'Dana Whitfield',两者必须同时完全匹配" + }, + { + "name": "Row 6 Department + Session", + "weight": 0.3, + "description": "检查第 6 行的部门和会话信息是否正确", + "check_logic": "调用 _cell_value(roster, 'C', 6) 和 _cell_value(roster, 'D', 6),判断 C6 是否等于 'Customer Success' 且 D6 是否等于 'Session B (Aug 14)'", + "pass_condition": "C6 == 'Customer Success' 且 D6 == 'Session B (Aug 14)',两者必须同时完全匹配" + }, + { + "name": "Row 6 Enrolled/Prep/Completion/Feedback + rows 2-5 preserved", + "weight": 0.4, + "description": "检查第 6 行剩余字段是否正确,并验证原有第 2-5 行未被篡改", + "check_logic": "依次读取 E6、F6、G6、H6,判断 E6=='Yes'、F6=='No'、G6=='Pending'、H6 为空白(None 或 '');然后遍历第 2-5 行,将每一行的 A-H 列实际值与 EXPECTED_ROWS_2_5 中的预期列表进行完全相等比较", + "pass_condition": "E6=='Yes'、F6=='No'、G6=='Pending'、H6 为空,且第 2、3、4、5 行的 A-H 列值与 EXPECTED_ROWS_2_5 完全一致" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制上限,并四舍五入保留 4 位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 sid 或 sid 为空,打印 CRITICAL 并返回 0.0", + "无法从 google_sheets_mock 获取状态(网络错误或超时),打印 CRITICAL 并返回 0.0", + "current_state 为空,打印 CRITICAL 并返回 0.0", + "current_state 中未找到名为 'Roster' 的工作表,打印 CRITICAL 并返回 0.0", + "组件检查中任一条件不匹配,该组件得 0.0 分(不会提前退出,继续检查后续组件)" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向 google_sheets_mock 发送 GET 请求拉取 current_state 和 initial_state。接着在 current_state 中查找名为 'Roster' 的工作表。随后依次执行 3 个独立组件:组件 1(0.3 分)验证 A6 和 B6 是否为 'EMP-2051' 和 'Dana Whitfield';组件 2(0.3 分)验证 C6 和 D6 是否为 'Customer Success' 和 'Session B (Aug 14)';组件 3(0.4 分)验证 E6/F6/G6/H6 是否为 'Yes'/'No'/'Pending'/空白,并逐行比对第 2-5 行是否与 EXPECTED_ROWS_2_5 完全一致。各组件得分累加后,通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数,输出最终 REWARD。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: prof45_roster_invite_001(从 docstring 中明确提取)\n2. **Domain**: mock_websites(从 docstring 中明确提取)\n3. **Summary**: 验证在 Google Sheets 的 'Roster' 工作表中新增的第 6 行包含指定的员工信息,且原有第 2-5 行未被修改。\n4. **is_placeholder**: false(这是一个真正的评分脚本,有详细的检查逻辑)\n5. **data_sources**: \n - `/tmp/task_web_sid`(读取 sid)\n - `google_sheets_mock`(通过 http://28.7.186.212:8165 访问)\n6. **Scoring components**:\n - Component 1: weight 0.3,检查 A6='EMP-2051' 且 B6='Dana Whitfield'\n - Component 2: weight 0.3,检查 C6='Customer Success' 且 D6='Session B (Aug 14)'\n - Component 3: weight 0.4,检查 E6='Yes', F6='No', G6='Pending', H6 为空,且第 2-5 行与预期完全一致\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,然后取 min(total_score, 1.0) 并四舍五入到 4 位小数\n9. **failure_modes**:\n - 无法从 /tmp/task_web_sid 读取 sid → 0.0\n - 无法从 mock 服务器获取状态 → 0.0\n - current_state 为空 → 0.0\n - 找不到 'Roster' 工作表 → 0.0\n - 各组件检查失败会返回 0.0 分(但不会提前退出,继续检查其他组件)\n10. **scoring_logic_explanation**: 按执行顺序:\n - 从 /tmp/task_web_sid 读取会话 ID\n - 向 google_sheets_mock 发送 GET 请求获取 current_state 和 initial_state\n - 从 current_state 中找到名为 'Roster' 的工作表\n - 依次执行 3 个独立组件检查:\n 1. 检查第 6 行的 A、B 列是否为指定值(0.3 分)\n 2. 检查第 6 行的 C、D 列是否为指定值(0.3 分)\n 3. 检查第 6 行的 E、F、G、H 列是否为指定值,且第 2-5 行与 EXPECTED_ROWS_2_5 完全一致(0.4 分)\n - 各组件得分相加,上限钳制到 1.0,四舍五入保留 4 位小数作为最终 REWARD\n11. **confidence**: 1.0(代码逻辑非常清晰)\n\n需要确保:\n- 只输出 JSON,没有 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- JSON 格式正确\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"prof45_roster_invite_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Google Sheets 的 'Roster' 工作表第 6 行添加了指定的新员工数据,且原有第 2-5 行未被修改\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google_sheets_mock (http://28.7.186.212:8165)\"],\n \"scoring_components\": [\n {\n \"name\": \"Row 6 Employee ID + Name\",\n \"weight\": 0.3,\n \"description\": \"检查第 6 行的员工编号和姓名是否正确\",\n \"check_logic\": \"调用 _cell_value(roster, 'A', 6) 和 _cell_value(roster, 'B', 6),判断 A6 是否等于 'EMP-2051' 且 B6 是否等于 'Dana Whitfield'\",\n \"pass_condition\": \"A6 == 'EMP-2051' 且 B6 == 'Dana Whitfield',两者必须同时完全匹配\"\n },\n {\n \"name\": \"Row 6 Department + Session\",\n \"weight\": 0.3,\n \"description\": \"检查第 6 行的部门和会话信息是否正确\",\n \"check_logic\": \"调用 _cell_value(roster, 'C', 6) 和 _cell_value(roster, 'D', 6),判断 C6 是否等于 'Customer Success' 且 D6 是否等于 'Session B (Aug 14)'\",\n \"pass_condition\": \"C6 == 'Customer Success' 且 D6 == 'Session B (Aug 14)',两者必须同时完全匹配\"\n },\n {\n \"name\": \"Row 6 Enrolled/Prep/Completion/Feedback + rows 2-5 preserved\",\n \"weight\": 0.4,\n \"description\": \"检查第 6 行剩余字段是否正确,并验证原有第 2-5 行未被篡改\",\n \"check_logic\": \"依次读取 E6、F6、G6、H6,判断 E6=='Yes'、F6=='No'、G6=='Pending'、H6 为空白(None 或 '');然后遍历第 2-5 行,将每一行的 A-H 列实际值与 EXPECTED_ROWS_2_5 中的预期列表进行完全相等比较\",\n \"pass_condition\": \"E6=='Yes'、F6=='No'、G6=='Pending'、H6 为空,且第 2、3、4、5 行的 A-H 列值与 EXPECTED_ROWS_2_5 完全一致\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total_score, 1.0) 钳制上限,并四舍五入保留 4 位小数\",\n \"failure_modes\": [\n \"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空,打印 CRITICAL 并返回 0.0\",\n \"无法从 google_sheets_mock 获取状态(网络错误或超时),打印 CRITICAL 并返回 0.0\",\n \"current_state 为空,打印 CRITICAL 并返回 0.0\",\n \"current_state 中未找到名为 'Roster' 的工作表,打印 CRITICAL 并返回 0.0\",\n \"组件检查中任一条件不匹配,该组件得 0.0 分(不会提前退出,继续检查后续组件)\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向 google_sheets_mock 发送 GET 请求拉取 current_state 和 initial_state。接着在 current_state 中查找名为 'Roster' 的工作表。随后依次执行 3 个独立组件:组件 1(0.3 分)验证 A6 和 B6 是否为 'EMP-2051' 和 'Dana Whitfield';组件 2(0.3 分)验证 C6 和 D6 是否为 'Customer Success' 和 'Session B (Aug 14)';组件 3(0.4 分)验证 E6/F6/G6/H6 是否为 'Yes'/'No'/'Pending'/空白,并逐行比对第 2-5 行是否与 EXPECTED_ROWS_2_5 完全一致。各组件得分累加后,通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数,输出最终 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查是否符合要求:\n- 没有 markdown 代码块标记\n- 第一个字符是 {,最后一个字符是 }\n- 没有额外解释\n- 没有 thinking 标签\n- task_id 和 domain 从 docstring 提取正确\n- is_placeholder 为 false\n- weight 与代码中一致(0.3, 0.3, 0.4)\n- 所有 value 字符串为中文,代码标识符保留原样\n\n看起来没问题。 {\"task_id\":\"prof45_roster_invite_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Google Sheets 的 'Roster' 工作表第 6 行添加了指定的新员工数据,且原有第 2-5 行未被修改\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock (http://28.7.186.212:8165)\"],\"scoring_components\":[{\"name\":\"Row 6 Employee ID + Name\",\"weight\":0.3,\"description\":\"检查第 6 行的员工编号和姓名是否正确\",\"check_logic\":\"调用 _cell_value(roster, 'A', 6) 和 _cell_value(roster, 'B', 6),判断 A6 是否等于 'EMP-2051' 且 B6 是否等于 'Dana Whitfield'\",\"pass_condition\":\"A6 == 'EMP-2051' 且 B6 == 'Dana Whitfield',两者必须同时完全匹配\"},{\"name\":\"Row 6 Department + Session\",\"weight\":0.3,\"description\":\"检查第 6 行的部门和会话信息是否正确\",\"check_logic\":\"调用 _cell_value(roster, 'C', 6) 和 _cell_value(roster, 'D', 6),判断 C6 是否等于 'Customer Success' 且 D6 是否等于 'Session B (Aug 14)'\",\"pass_condition\":\"C6 == 'Customer Success' 且 D6 == 'Session B (Aug 14)',两者必须同时完全匹配\"},{\"name\":\"Row 6 Enrolled/Prep/Completion/Feedback + rows 2-5 preserved\",\"weight\":0.4,\"description\":\"检查第 6 行剩余字段是否正确,并验证原有第 2-5 行未被篡改\",\"check_logic\":\"依次读取 E6、F6、G6、H6,判断 E6=='Yes'、F6=='No'、G6=='Pending'、H6 为空白(None 或 '');然后遍历第 2-5 行,将每一行的 A-H 列实际值与 EXPECTED_ROWS_2_5 中的预期列表进行完全相等比较\",\"pass_condition\":\"E6=='Yes'、F6=='No'、G6=='Pending'、H6 为空,且第 2、3、4、5 行的 A-H 列值与 EXPECTED_ROWS_2_5 完全一致\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total_score, 1.0) 钳制上限,并四舍五入保留 4 位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空,打印 CRITICAL 并返回 0.0\",\"无法从 google_sheets_mock 获取状态(网络错误或超时),打印 CRITICAL 并返回 0.0\",\"current_state 为空,打印 CRITICAL 并返回 0.0\",\"current_state 中未找到名为 'Roster' 的工作表,打印 CRITICAL 并返回 0.0\",\"组件检查中任一条件不匹配,该组件得 0.0 分(不会提前退出,继续检查后续组件)\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后向 google_sheets_mock 发送 GET 请求拉取 current_state 和 initial_state。接着在 current_state 中查找名为 'Roster' 的工作表。随后依次执行 3 个独立组件:组件 1(0.3 分)验证 A6 和 B6 是否为 'EMP-2051' 和 'Dana Whitfield';组件 2(0.3 分)验证 C6 和 D6 是否为 'Customer Success' 和 'Session B (Aug 14)';组件 3(0.4 分)验证 E6/F6/G6/H6 是否为 'Yes'/'No'/'Pending'/空白,并逐行比对第 2-5 行是否与 EXPECTED_ROWS_2_5 完全一致。各组件得分累加后,通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数,输出最终 REWARD。\",\"confidence\":1.0}" +} diff --git a/legacy/recruit_offer_001/_cua_gym_vm_bridge.sh b/legacy/recruit_offer_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/recruit_offer_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://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/recruit_offer_001/initial_setup.py b/legacy/recruit_offer_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f724808fbfc3454d2ca003a4c7ea2d1e85048419 --- /dev/null +++ b/legacy/recruit_offer_001/initial_setup.py @@ -0,0 +1,261 @@ +""" +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.186.212:8166' +OUTLOOK_URL = 'http://28.7.186.212:8188' +SLACK_URL = 'http://28.7.186.212:8198' + +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": [], + } + + +# ===================================================================== +# 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/legacy/recruit_offer_001/reward.py b/legacy/recruit_offer_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..ff34c883776d6bb8fdef5f1ebf98fc406ff36dd3 --- /dev/null +++ b/legacy/recruit_offer_001/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.186.212:8166' +OUTLOOK_URL = 'http://28.7.186.212:8188' +SLACK_URL = 'http://28.7.186.212:8198' + +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/legacy/recruit_offer_001/reward_label.json b/legacy/recruit_offer_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..ec8c060108224f47409e4064f93d3e0cc1f733a2 --- /dev/null +++ b/legacy/recruit_offer_001/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/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:36", + "label": { + "task_id": "recruit_offer_001", + "domain": "mock_websites", + "summary": "验证是否通过 Greenhouse、Outlook 和 Slack 三个 mock 服务完成向 Sofia Rossi(Marketing Manager)发送录用通知的完整流程,且 Slack 公告不包含薪资信息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "greenhouse_mock", + "outlook_mock", + "slack_mock" + ], + "scoring_components": [ + { + "name": "Component 1a — GREENHOUSE stage move", + "weight": 0.15, + "description": "检查 Sofia Rossi 的申请是否从初始阶段移动到了 Greenhouse 的 Offer 阶段", + "check_logic": "通过 jobStages 获取 name 为 'offer' 的阶段 ID 集合;在 candidates 中通过邮箱 sofia.rossi@gmail.com 找到 candidateId,再在 applications 中找到对应申请;比较初始状态 init_stage 和当前状态 cur_stage 的 currentStageId;通过条件为 cur_stage 属于 offer 阶段且 init_stage 不属于 offer 阶段", + "pass_condition": "Sofia 的 currentStageId 从非 Offer 阶段变为 Offer 阶段" + }, + { + "name": "Component 1b — GREENHOUSE offer record", + "weight": 0.25, + "description": "检查是否为 Sofia 创建了新的 offer 记录,且薪资为 120000、开始日期为 2026-08-03", + "check_logic": "在 offers 列表中筛选 id 不在 init_offer_ids 中的新记录,且 candidateId 或 applicationId 匹配 Sofia;检查 salary 字段通过 salary_matches 匹配 120000(数值误差 ≤1 或文本包含 120000/120k),且 startDate 字符串包含 2026-08-03", + "pass_condition": "存在新的 offer 记录,salary 匹配 120000 且 startDate 包含 2026-08-03" + }, + { + "name": "Component 2 — OUTLOOK email", + "weight": 0.3, + "description": "检查是否向 Sofia 发送了新的录用邮件,且邮件内容包含 Marketing Manager 和 offer 关键词", + "check_logic": "遍历当前 emails,筛选 folderId 为 'sent' 且 id 不在 init_ids 中的新邮件;检查收件人信息中包含 sofia.rossi@gmail.com;将邮件 subject 与去 HTML 后的 body 拼接转小写后,判断是否同时包含 marketing manager 和 offer", + "pass_condition": "存在新的已发送邮件,收件人为 Sofia,且主题/正文同时包含 marketing manager 和 offer" + }, + { + "name": "Component 3 — SLACK message", + "weight": 0.3, + "description": "检查是否在 Slack #hiring 频道发布了新的录用公告,且消息不包含薪资数字", + "check_logic": "定位 hiring 频道,获取其中 messageId 不在初始集合中的新消息;检查消息内容小写后同时包含 sofia rossi、marketing manager、offer;通过 has_salary_figure 检查内容是否包含 120000、120k 或单词边界匹配的 120;若公告匹配但包含薪资,直接返回 0.0", + "pass_condition": "存在新的 #hiring 消息,包含 Sofia Rossi、marketing manager、offer,且不包含任何薪资数字(120000/120k/120)" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "读取 /tmp/task_web_sid 失败或为空,脚本提前退出并返回 0.0", + "Greenhouse/Outlook/Slack 任一服务请求失败或返回 None,对应组件得 0.0", + "Greenhouse 中 Sofia 的申请未移动到 Offer 阶段,Component 1a 不得分", + "Greenhouse 中无新 offer 记录,或 salary/startDate 不匹配,Component 1b 不得分", + "Outlook 中无新的 sent 邮件,或收件人/关键词不匹配,Component 2 得 0.0", + "Slack #hiring 中无新公告,或关键词不匹配,Component 3 得 0.0", + "Slack 公告消息匹配主题但包含薪资数字(120000/120k/120),Component 3 直接得 0.0", + "各组件内部发生异常时,返回当前已累积分数或 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识 sid;若读取失败则直接输出 REWARD: 0.0 并退出。随后脚本向三个 mock 服务(Greenhouse、Outlook、Slack)分别请求 initial_state 和 current_state,所有评分均基于状态差量(delta)进行。\n1. Greenhouse(0.40):先通过 jobStages 解析出名为 offer 的阶段 ID。查找 Sofia Rossi(邮箱 sofia.rossi@gmail.com)在初始和当前状态中的申请记录。1a(0.15)判断 currentStageId 是否进入了 offer 阶段且初始状态不在该阶段;1b(0.25)在 offers 列表中查找属于 Sofia 的新 offer(id 不在初始集合中),并验证其 salary 字段匹配 120000(数值误差 ≤1 或文本包含 120000/120k)且 startDate 包含 2026-08-03。\n2. Outlook(0.30):遍历当前 emails,筛选 folderId 为 sent 且 id 不在初始集合中的新邮件。检查收件人包含 sofia.rossi@gmail.com,且邮件主题与去 HTML 后的正文同时包含 marketing manager 和 offer。\n3. Slack(0.30):定位 hiring 频道,获取其中 messageId 不在初始集合中的新消息。检查消息内容是否同时包含 sofia rossi、marketing manager、offer,且绝对不能包含薪资数字(120000、120k、120 等形式)。若找到符合主题的消息但包含薪资,则该组件直接判 0 分。\n三个组件得分累加,最终通过 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 的录用流程是否在三处 mock 服务中正确完成(Greenhouse 移动至 Offer 阶段并创建录用记录、Outlook 发送录用邮件、Slack #hiring 频道发布不含薪资的录用公告)。\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 这些是 mock 服务,可以命名为 greenhouse_mock、outlook_mock、slack_mock,或者保留 URL。按照示例,应该是 greenhouse_mock、outlook_mock、slack_mock,以及 /tmp/task_web_sid。\n\n6. **scoring_components**:\n - Component 1: weight 0.40\n - 1a: 0.15 - Sofia 的申请从初始阶段移动到了 'Offer' 阶段\n - 1b: 0.25 - 存在新的 offer 记录,base salary 120000 且 start date 2026-08-03\n 代码中 `verify_greenhouse` 返回 score,初始 0.0,通过条件分别加 0.15 和 0.25。\n 所以 Component 1 整体 weight 应该是 0.40。\n 但用户要求 \"weight 字段填写代码中显式给出的分值(如 0.3);若代码未显式分值但有通过/失败二值判定,weight 填 1.0\"。\n 这里 Component 1 整体是 0.40,但内部有细分。我可以把 Component 1 拆成 1a 和 1b,或者作为一个整体。\n 看 JSON 结构,scoring_components 是一个数组,每个组件有 weight。docstring 明确说了 Component 1 — GREENHOUSE, 0.40,然后内部有 1a (0.15) 和 1b (0.25)。\n 我应该按照 docstring 的结构来分组件。可以分成三个 Component(Greenhouse、Outlook、Slack),或者把 Greenhouse 拆成两个子组件。\n 为了准确,我可以列出:\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 让我再读一下 docstring:\n \"Component 1 — GREENHOUSE, 0.40:\n 1a (0.15) ...\n 1b (0.25) ...\"\n \n 如果我把 Component 1 作为一个整体,weight 0.40,那 check_logic 就要说明内部有两个子条件。但用户要求 \"weight 字段填写代码中显式给出的分值\"。代码中确实是分别 `score += 0.15` 和 `score += 0.25`。\n \n 我觉得拆成四个组件更准确:\n - Component 1a: 0.15\n - Component 1b: 0.25\n - Component 2: 0.30\n - Component 3: 0.30\n \n 或者按照 docstring 的层级:\n - Component 1 — GREENHOUSE: 0.40,然后在 description 中说明包含 1a 和 1b。\n \n 但 weight 应该填最细粒度的显式分值。让我看看代码:`score += 0.15` 和 `score += 0.25`。这些都是显式分值。\n \n 我决定拆成:\n 1. Component 1a: weight 0.15\n 2. Component 1b: weight 0.25\n 3. Component 2: weight 0.30\n 4. Component 3: weight 0.30\n \n 这样 total_max_score 就是 1.0。\n\n 每个组件的 check_logic:\n - Component 1a: 比较初始状态和当前状态中 Sofia 申请的 currentStageId。初始状态的 stage id 不在 'offer' stage ids 中,且当前状态的 stage id 在 'offer' stage ids 中。\n - Component 1b: 在当前状态的 offers 中查找 id 不在初始状态 offer ids 中,且 candidateId 匹配或 applicationId 匹配的新 offer。检查 salary 字段是否匹配 120000(容忍 1.0 误差或文本匹配),且 startDate 包含 '2026-08-03'。\n - Component 2: 在当前状态的 emails 中查找 id 不在初始状态 email ids 中,且 folderId 为 'sent' 的新邮件。检查收件人包含 sofia.rossi@gmail.com,且主题+正文(去 HTML)包含 'marketing manager' 和 'offer'。\n - Component 3: 在当前状态的 #hiring 频道消息中查找 messageId 不在初始状态消息 ids 中的新消息。检查内容包含 'sofia rossi'、'marketing manager'、'offer',且不包含薪资数字(120000、120k、120)。\n\n pass_condition:\n - 1a: Sofia 的申请从非 Offer 阶段移动到了 Offer 阶段。\n - 1b: 存在新的 offer 记录,salary 为 120000(±1)且 startDate 包含 2026-08-03。\n - 2: 存在新的已发送邮件给 Sofia,且邮件主题/正文包含 \"marketing manager\" 和 \"offer\"。\n - 3: 存在新的 #hiring 频道消息,包含 Sofia Rossi、marketing manager、offer,且不包含任何薪资数字(120000/120k/120)。\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 不存在或为空)→ 提前退出,输出 REWARD: 0.0\n - Greenhouse 无法访问 → 该组件返回 0.0\n - Outlook 无法访问 → 该组件返回 0.0\n - Slack 无法访问 → 该组件返回 0.0\n - Slack 中如果找到新的录用公告但泄露了薪资 → 该组件返回 0.0(注意不是继续找,是直接返回 0.0)\n - 各组件内部异常 → 返回当前已得分数或 0.0\n\n10. **scoring_logic_explanation**: \n 脚本首先读取 /tmp/task_web_sid 获取会话 ID。然后分别向三个 mock 服务(Greenhouse、Outlook、Slack)发送请求,获取 initial_state 和 current_state。评分基于 DELTA(当前状态 vs 初始状态)。\n 1. Greenhouse 组件(0.40):检查 Sofia Rossi 的申请是否从初始阶段移动到了名为 'Offer' 的阶段(0.15);并检查是否存在新的 offer 记录,其薪资为 120000 且开始日期为 2026-08-03(0.25)。\n 2. Outlook 组件(0.30):检查是否存在新的已发送邮件,收件人为 sofia.rossi@gmail.com,且邮件主题/正文中同时包含 \"marketing manager\" 和 \"offer\"。\n 3. Slack 组件(0.30):检查 #hiring 频道是否存在新消息,内容需同时包含 \"sofia rossi\"、\"marketing manager\" 和 \"offer\",且绝对不能包含薪资数字(120000、120k、120 等形式);若找到匹配消息但包含薪资,则该组件直接得 0 分。\n 三个组件得分相加,最终通过 min(total, 1.0) 钳制在 1.0 以内,并四舍五入到 4 位小数输出。\n\n11. **confidence**: 1.0(代码逻辑非常清晰)\n\n让我再检查一下 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n我需要确保所有 value 都是中文,除了 task_id、domain、字段名、代码标识符。\n\n让我再仔细看看 data_sources。代码中是从三个 URL 获取,这些 mock 服务通常可以称为 greenhouse_mock、outlook_mock、slack_mock。文件路径是 /tmp/task_web_sid。\n\nscoring_components 的 name:我可以使用 \"Component 1a — GREENHOUSE stage move\"、\"Component 1b — GREENHOUSE offer record\"、\"Component 2 — OUTLOOK email\"、\"Component 3 — SLACK message\"。\n\n等等,docstring 里明确写了 \"Component 1 — GREENHOUSE, 0.40\"。如果我把 1a 和 1b 分开,那 Component 1 的 0.40 就不见了。但代码里确实是分别加 0.15 和 0.25。\n我觉得分成四个组件是合理的,因为分值是显式分开的。\n\n或者,我可以把 name 写成 \"Component 1a\" 和 \"Component 1b\",这样也符合 docstring 的编号。\n\n让我再检查一下 Slack 的逻辑:\n```python\nif announce_ok and salary_absent:\n return 0.30\nif announce_ok and not salary_absent:\n return 0.0\n```\n这意味着如果有一条新消息是公告但包含薪资,直接返回 0.0。即使后面还有其他消息。这是一个重要的失败模式。\n\n还有 Outlook:\n```python\nfor e in (cur.get('emails') or []):\n ...\n if recipient_ok and role_ok and offer_ok:\n return 0.30\n```\n找到第一个匹配的邮件就返回。\n\nGreenhouse:\n```python\nfor o in (cur.get('offers') or []):\n ...\n if ...:\n new_offer = o\n break\n```\n只检查第一个匹配的新 offer。\n\n现在来构建 JSON。注意字符串里如果有双引号需要转义。\n\nsummary: 验证是否通过 Greenhouse、Outlook 和 Slack 三个 mock 服务完成向 Sofia Rossi(Marketing Manager)发送录用通知的完整流程,且 Slack 公告不包含薪资信息。\n\nscoring_logic_explanation 需要详细中文解释。\n\n让我组织一下语言:\n\n脚本首先读取 `/tmp/task_web_sid` 获取会话标识 sid;若读取失败则直接输出 REWARD: 0.0 并退出。\n随后脚本向三个 mock 服务(Greenhouse、Outlook、Slack)分别请求 `initial_state` 和 `current_state`,所有评分均基于状态差量(delta)进行。\n\n执行顺序如下:\n1. **Greenhouse(0.40)**:先通过 `jobStages` 解析出名为 `offer` 的阶段 ID。查找 Sofia Rossi(邮箱 `sofia.rossi@gmail.com`)在初始和当前状态中的申请记录。\n - **1a(0.15)**:判断 `currentStageId` 是否进入了 `offer` 阶段且初始状态不在该阶段。\n - **1b(0.25)**:在 `offers` 列表中查找属于 Sofia 的新 offer(id 不在初始集合中),并验证其 `salary` 字段匹配 120000(数值误差 ≤1 或文本包含 120000/120k)且 `startDate` 包含 `2026-08-03`。\n2. **Outlook(0.30)**:遍历当前 `emails`,筛选 `folderId` 为 `sent` 且 id 不在初始集合中的新邮件。检查收件人包含 `sofia.rossi@gmail.com`,且邮件主题与去 HTML 后的正文同时包含 `marketing manager` 和 `offer`。\n3. **Slack(0.30)**:定位 `hiring` 频道,获取其中 id 不在初始集合中的新消息。检查消息内容是否同时包含 `sofia rossi`、`marketing manager`、`offer`,且绝对不能包含薪资数字(`120000`、`120k`、`120` 等形式)。若找到符合主题的消息但包含薪资,则该组件直接判 0 分。\n\n三个组件得分累加,最终通过 `min(total, 1.0)` 钳制上限为 1.0,并四舍五入到 4 位小数作为最终 REWARD 输出。\n\nfailure_modes:\n- 读取 `/tmp/task_web_sid` 失败或为空 → 提前退出,返回 0.0\n- 任一 mock 服务(Greenhouse/Outlook/Slack)请求失败或返回 None → 对应组件得 0.0\n- Greenhouse 中 Sofia 未移动到 Offer 阶段 → 1a 不得分\n- Greenhouse 中无新 offer 记录,或薪资/开始日期不匹配 → 1b 不得分\n- Outlook 中无新的已发送录用邮件,或收件人/关键词不匹配 → 2 得 0.0\n- Slack #hiring 中无新公告,或关键词不匹配 → 3 得 0.0\n- Slack 公告包含薪资数字(120000/120k/120)→ 3 直接得 0.0(即使其他消息正确也不计分)\n- 各组件内部发生异常 → 通常返回当前已得分数或 0.0\n\nconfidence: 1.0\n\n现在检查 JSON 语法。所有 key 必须用双引号。字符串中的双引号需要转义。\n\n等等,我注意到 domain 的提取。docstring 中写的是 `Domain: mock_websites (greenhouse + outlook_web + slack)`。按照要求,domain 应该是 `mock_websites`。示例中也有 `mock_websites / software_engineer / libreoffice_calc`,所以填 `mock_websites` 是对的。\n\ndata_sources 列表:应该包含哪些?\n- `/tmp/task_web_sid`\n- `GREENHOUSE_URL` 对应的 mock 服务,可以叫 `greenhouse_mock`\n- `OUTLOOK_URL` 对应的 mock 服务,可以叫 `outlook_mock`\n- `SLACK_URL` 对应的 mock 服务,可以叫 `slack_mock`\n\n或者保留 URL?示例中写的是 `slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid`,所以用 mock 名称更合适。\n\n让我再确认一下 `has_salary_figure` 的逻辑:\n```python\nt = (text or '').lower().replace(',', '').replace('$', '')\nif '120000' in t: return True\nif '120k' in t: return True\nif re.search(r'\\b120\\b', t): return True\n```\n它会匹配 \"120\" 作为单词边界。例如 \"120\" 前后是非单词字符。所以 \"120k\" 已经被前面的条件捕获,`\\b120\\b` 会匹配单独的 \"120\"。\n\n`salary_matches` 对字符串的处理:\n```python\nnorm = value.lower().replace(',', '').replace('$', '').replace(' ', '')\nreturn '120000' in norm or '120k' in norm\n```\n注意这里没有用 `\\b120\\b`,只是检查是否包含子串。但通常薪资字段是数字或 \"120000\" 这样的字符串。\n\n好的,我认为分析已经足够准确。现在生成 JSON。\n\n注意:用户要求 \"不要输出 Markdown 代码块标记\",所以我直接输出裸 JSON。\n\n再检查一遍字段:\n- task_id: \"recruit_offer_001\"\n- domain: \"mock_websites\"\n- summary: \"验证是否通过 Greenhouse、Outlook 和 Slack 三个 mock 服务完成向 Sofia Rossi(Marketing Manager)发送录用通知的完整流程,且 Slack 公告不包含薪资信息\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"greenhouse_mock\", \"outlook_mock\", \"slack_mock\"]\n- scoring_components: 数组,包含 4 个对象\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\"\n- failure_modes: 数组\n- scoring_logic_explanation: 长字符串\n- confidence: 1.0\n\nscoring_components 的 detail:\n\nComponent 1a:\n- name: \"Component 1a — GREENHOUSE stage move\"\n- weight: 0.15\n- description: \"检查 Sofia Rossi 的申请是否从初始阶段移动到了 Greenhouse 的 Offer 阶段\"\n- check_logic: \"通过 `jobStages` 获取 name 为 'offer' 的阶段 ID 集合;在 `candidates` 中通过邮箱 `sofia.rossi@gmail.com` 找到 candidateId,再在 `applications` 中找到对应申请;比较初始状态 `init_stage` 和当前状态 `cur_stage` 的 `currentStageId`;通过条件为 `cur_stage` 属于 offer 阶段且 `init_stage` 不属于 offer 阶段\"\n- pass_condition: \"Sofia 的 currentStageId 从非 Offer 阶段变为 Offer 阶段\"\n\nComponent 1b:\n- name: \"Component 1b — GREENHOUSE offer record\"\n- weight: 0.25\n- description: \"检查是否为 Sofia 创建了新的 offer 记录,且薪资为 120000、开始日期为 2026-08-03\"\n- check_logic: \"在 `offers` 列表中筛选 id 不在 `init_offer_ids` 中的新记录,且 `candidateId` 或 `applicationId` 匹配 Sofia;检查 `salary` 字段通过 `salary_matches` 匹配 120000(数值误差 ≤1 或文本包含 120000/120k),且 `startDate` 字符串包含 `2026-08-03`\"\n- pass_condition: \"存在新的 offer 记录,salary 匹配 120000 且 startDate 包含 2026-08-03\"\n\nComponent 2:\n- name: \"Component 2 — OUTLOOK email\"\n- weight: 0.30\n- description: \"检查是否向 Sofia 发送了新的录用邮件,且邮件内容包含 Marketing Manager 和 offer 关键词\"\n- check_logic: \"遍历当前 `emails`,筛选 `folderId` 为 'sent' 且 id 不在 `init_ids` 中的新邮件;检查收件人信息中包含 `sofia.rossi@gmail.com`;将邮件 `subject` 与去 HTML 后的 `body` 拼接转小写后,判断是否同时包含 `marketing manager` 和 `offer`\"\n- pass_condition: \"存在新的已发送邮件,收件人为 Sofia,且主题/正文同时包含 marketing manager 和 offer\"\n\nComponent 3:\n- name: \"Component 3 — SLACK message\"\n- weight: 0.30\n- description: \"检查是否在 Slack #hiring 频道发布了新的录用公告,且消息不包含薪资数字\"\n- check_logic: \"定位 `hiring` 频道,获取其中 `messageId` 不在初始集合中的新消息;检查消息内容小写后同时包含 `sofia rossi`、`marketing manager`、`offer`;通过 `has_salary_figure` 检查内容是否包含 120000、120k 或单词边界匹配的 120;若公告匹配但包含薪资,直接返回 0.0\"\n- pass_condition: \"存在新的 #hiring 消息,包含 Sofia Rossi、marketing manager、offer,且不包含任何薪资数字(120000/120k/120)\"\n\nfailure_modes:\n- \"读取 `/tmp/task_web_sid` 失败或为空,脚本提前退出并返回 0.0\"\n- \"Greenhouse/Outlook/Slack 任一服务请求失败或返回 None,对应组件得 0.0\"\n- \"Greenhouse 中 Sofia 的申请未移动到 Offer 阶段,Component 1a 不得分\"\n- \"Greenhouse 中无新 offer 记录,或 salary/startDate 不匹配,Component 1b 不得分\"\n- \"Outlook 中无新的 sent 邮件,或收件人/关键词不匹配,Component 2 得 0.0\"\n- \"Slack #hiring 中无新公告,或关键词不匹配,Component 3 得 0.0\"\n- \"Slack 公告消息匹配主题但包含薪资数字(120000/120k/120),Component 3 直接得 0.0\"\n- \"各组件内部发生异常时,返回当前已累积分数或 0.0\"\n\nscore_aggregation: \"各组件分数相加,最终通过 `min(total, 1.0)` 钳制到上限 1.0,并四舍五入到 4 位小数\"\n\n好的,我现在可以生成最终 JSON 了。确保没有多余的空格或换行在 JSON 外面?不,JSON 内部可以有换行和缩进。但第一个字符必须是 `{`,最后一个必须是 `}`。\n\n让我再检查一下字符串中的特殊字符,比如反引号、换行符。在 JSON 中,多行字符串不能直接用换行,需要转义为 `\\n`。或者我可以写成一行。但通常 JSON 字符串可以包含实际的换行符吗?不,JSON 字符串中的换行必须转义为 `\\n`。\n\n为了安全起见,我把所有长字符串都写成一行,用 `\\n` 表示换行?不,用户要求输出 JSON 对象,我可以直接让 JSON 库处理。但我没有 JSON 库,我是手动生成。我可以用 `\\n` 来显式表示换行,或者直接把长字符串写成一行。\n\n实际上,在 JSON 中,字符串值里直接包含换行符是不合法的(除非转义)。所以我需要把多行文本转义,或者写成一行。我会把长字符串写成一行,用句号分隔。\n\n或者,我可以在 JSON 字符串中使用 `\\n` 转义序列。这样阅读起来也清晰。\n\n让我决定:在 `scoring_logic_explanation` 和 `failure_modes` 等字段中,如果需要换行,使用 `\\n` 转义。\n\n但等等,用户说 \"不要输出 Markdown 代码块标记\",所以我直接输出 JSON 文本即可。\n\n让我再确认一下 `domain`。docstring 写的是 `Domain: mock_websites (greenhouse + outlook_web + slack)`。示例说 \"如 mock_websites / software_engineer / libreoffice_calc\"。所以 `mock_websites` 是正确的。\n\n`task_id`: `recruit_offer_001`\n\n`is_placeholder`: false\n\n`confidence`: 1.0\n\n一切就绪。 {\"task_id\":\"recruit_offer_001\",\"domain\":\"mock_websites\",\"summary\":\"验证是否通过 Greenhouse、Outlook 和 Slack 三个 mock 服务完成向 Sofia Rossi(Marketing Manager)发送录用通知的完整流程,且 Slack 公告不包含薪资信息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"greenhouse_mock\",\"outlook_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"Component 1a — GREENHOUSE stage move\",\"weight\":0.15,\"description\":\"检查 Sofia Rossi 的申请是否从初始阶段移动到了 Greenhouse 的 Offer 阶段\",\"check_logic\":\"通过 jobStages 获取 name 为 'offer' 的阶段 ID 集合;在 candidates 中通过邮箱 sofia.rossi@gmail.com 找到 candidateId,再在 applications 中找到对应申请;比较初始状态 init_stage 和当前状态 cur_stage 的 currentStageId;通过条件为 cur_stage 属于 offer 阶段且 init_stage 不属于 offer 阶段\",\"pass_condition\":\"Sofia 的 currentStageId 从非 Offer 阶段变为 Offer 阶段\"},{\"name\":\"Component 1b — GREENHOUSE offer record\",\"weight\":0.25,\"description\":\"检查是否为 Sofia 创建了新的 offer 记录,且薪资为 120000、开始日期为 2026-08-03\",\"check_logic\":\"在 offers 列表中筛选 id 不在 init_offer_ids 中的新记录,且 candidateId 或 applicationId 匹配 Sofia;检查 salary 字段通过 salary_matches 匹配 120000(数值误差 ≤1 或文本包含 120000/120k),且 startDate 字符串包含 2026-08-03\",\"pass_condition\":\"存在新的 offer 记录,salary 匹配 120000 且 startDate 包含 2026-08-03\"},{\"name\":\"Component 2 — OUTLOOK email\",\"weight\":0.30,\"description\":\"检查是否向 Sofia 发送了新的录用邮件,且邮件内容包含 Marketing Manager 和 offer 关键词\",\"check_logic\":\"遍历当前 emails,筛选 folderId 为 'sent' 且 id 不在 init_ids 中的新邮件;检查收件人信息中包含 sofia.rossi@gmail.com;将邮件 subject 与去 HTML 后的 body 拼接转小写后,判断是否同时包含 marketing manager 和 offer\",\"pass_condition\":\"存在新的已发送邮件,收件人为 Sofia,且主题/正文同时包含 marketing manager 和 offer\"},{\"name\":\"Component 3 — SLACK message\",\"weight\":0.30,\"description\":\"检查是否在 Slack #hiring 频道发布了新的录用公告,且消息不包含薪资数字\",\"check_logic\":\"定位 hiring 频道,获取其中 messageId 不在初始集合中的新消息;检查消息内容小写后同时包含 sofia rossi、marketing manager、offer;通过 has_salary_figure 检查内容是否包含 120000、120k 或单词边界匹配的 120;若公告匹配但包含薪资,直接返回 0.0\",\"pass_condition\":\"存在新的 #hiring 消息,包含 Sofia Rossi、marketing manager、offer,且不包含任何薪资数字(120000/120k/120)\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空,脚本提前退出并返回 0.0\",\"Greenhouse/Outlook/Slack 任一服务请求失败或返回 None,对应组件得 0.0\",\"Greenhouse 中 Sofia 的申请未移动到 Offer 阶段,Component 1a 不得分\",\"Greenhouse 中无新 offer 记录,或 salary/startDate 不匹配,Component 1b 不得分\",\"Outlook 中无新的 sent 邮件,或收件人/关键词不匹配,Component 2 得 0.0\",\"Slack #hiring 中无新公告,或关键词不匹配,Component 3 得 0.0\",\"Slack 公告消息匹配主题但包含薪资数字(120000/120k/120),Component 3 直接得 0.0\",\"各组件内部发生异常时,返回当前已累积分数或 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识 sid;若读取失败则直接输出 REWARD: 0.0 并退出。随后脚本向三个 mock 服务(Greenhouse、Outlook、Slack)分别请求 initial_state 和 current_state,所有评分均基于状态差量(delta)进行。\\n1. Greenhouse(0.40):先通过 jobStages 解析出名为 offer 的阶段 ID。查找 Sofia Rossi(邮箱 sofia.rossi@gmail.com)在初始和当前状态中的申请记录。1a(0.15)判断 currentStageId 是否进入了 offer 阶段且初始状态不在该阶段;1b(0.25)在 offers 列表中查找属于 Sofia 的新 offer(id 不在初始集合中),并验证其 salary 字段匹配 120000(数值误差 ≤1 或文本包含 120000/120k)且 startDate 包含 2026-08-03。\\n2. Outlook(0.30):遍历当前 emails,筛选 folderId 为 sent 且 id 不在初始集合中的新邮件。检查收件人包含 sofia.rossi@gmail.com,且邮件主题与去 HTML 后的正文同时包含 marketing manager 和 offer。\\n3. Slack(0.30):定位 hiring 频道,获取其中 messageId 不在初始集合中的新消息。检查消息内容是否同时包含 sofia rossi、marketing manager、offer,且绝对不能包含薪资数字(120000、120k、120 等形式)。若找到符合主题的消息但包含薪资,则该组件直接判 0 分。\\n三个组件得分累加,最终通过 min(total, 1.0) 钳制上限为 1.0,并四舍五入到 4 位小数作为最终 REWARD 输出。\",\"confidence\":1.0}" +} diff --git a/legacy/recruit_source_001/_cua_gym_vm_bridge.sh b/legacy/recruit_source_001/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..b12d01c4246aee42a84679dea25ef4843ae967ee --- /dev/null +++ b/legacy/recruit_source_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://9.91.4.13:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 9.91.4.13:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 9.91.4.13). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (9.91.4.13 -> 9.91.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 9.91.4.13:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/recruit_source_001/initial_setup.py b/legacy/recruit_source_001/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ac7b713f6447eb467bb0b7ecca3c5981b9ca5c --- /dev/null +++ b/legacy/recruit_source_001/initial_setup.py @@ -0,0 +1,309 @@ +""" +Initial Setup: Source a LinkedIn candidate into Greenhouse + announce in Slack (BASELINE) +Task ID: recruit_source_001 +Domain: mock_websites (3-mock chained: linkedin + greenhouse + slack) + +Runs on initial_env. Injects the PRE-TASK baseline into all three mocks using the +INITIAL sid = 'cua-' + md5(task_id)[:16]. Baseline MUST NOT contain any target content: + - LinkedIn: Maria Volkova profile exists (READ-ONLY source, identical in both envs) + - Greenhouse: open 'Senior Backend Engineer' job + 'LinkedIn' source exist, but NO Maria Volkova candidate + - Slack #hiring: channel exists, but NO sourced-candidate announcement +""" +import hashlib +import json +import os +import shlex +import subprocess +import time + +import requests + +TASK_ID = 'recruit_source_001' +sid = 'cua-' + hashlib.md5(TASK_ID.encode()).hexdigest()[:16] + +URLS = { + 'linkedin': 'http://28.7.186.212:8177', + 'greenhouse': 'http://28.7.186.212:8166', + 'slack': 'http://28.7.186.212:8198', +} + +PROXIES = {'http': 'http://star-proxy.oa.com:3128', 'https': 'http://star-proxy.oa.com:3128'} + + +def http_get_json(url): + last = None + for attempt in range(4): + for proxies in (None, PROXIES): + try: + r = requests.get(url, timeout=30, proxies=proxies) + r.raise_for_status() + return r.json() + except Exception as e: # noqa + last = e + time.sleep(1.5) + raise RuntimeError(f'GET failed for {url}: {last}') + + +def http_post(url, payload): + last = None + for attempt in range(4): + for proxies in (None, PROXIES): + try: + r = requests.post(url, json=payload, timeout=30, proxies=proxies) + r.raise_for_status() + return r + except Exception as e: # noqa + last = e + time.sleep(1.5) + raise RuntimeError(f'POST failed for {url}: {last}') + + +def fetch_defaults(mock): + """Fetch the mock's built-in default state via a throwaway sid.""" + data = http_get_json(f'{URLS[mock]}/go?sid=defaults_probe_recruit_source_001') + return data.get('current_state') or data.get('initial_state') + + +# --------------------------------------------------------------------------- +# Baseline builders (shared shape with golden_patch.py) +# --------------------------------------------------------------------------- +MARIA_USER_ID = 'user_maria_volkova' + + +def build_linkedin_baseline(): + """Add Maria Volkova's profile to the LinkedIn users map (read-only source).""" + state = fetch_defaults('linkedin') + maria = { + 'id': MARIA_USER_ID, + 'name': 'Maria Volkova', + 'headline': 'Senior Software Engineer at Stripe', + 'location': 'Berlin', + 'about': ('Backend-focused software engineer with 9+ years building reliable, ' + 'high-throughput payment infrastructure. I care deeply about distributed ' + 'systems, observability, and developer experience.\n\n' + 'Currently at Stripe working on core payments APIs and ledger systems. ' + 'Open to connecting with engineers passionate about fintech and scale.'), + 'avatar': f'https://i.pravatar.cc/200?u={MARIA_USER_ID}', + 'banner': 'https://picsum.photos/1200/400?random=banner_maria', + 'connections': ['user_2', 'user_5'], + 'experience': [ + { + 'id': 'exp_maria_1', + 'title': 'Senior Software Engineer', + 'company': 'Stripe', + 'companyId': None, + 'startDate': '2021-03', + 'endDate': 'Present', + 'location': 'Berlin, Germany', + 'description': ('Building and scaling core payments APIs and the ledger ' + 'service. Led the migration to a sharded datastore handling ' + '40k TPS at peak.'), + }, + { + 'id': 'exp_maria_2', + 'title': 'Software Engineer', + 'company': 'Zalando', + 'companyId': None, + 'startDate': '2017-06', + 'endDate': '2021-02', + 'location': 'Berlin, Germany', + 'description': ('Worked on the checkout and order-management backend services ' + 'in a high-traffic e-commerce environment.'), + }, + ], + 'education': [ + { + 'id': 'edu_maria_1', + 'school': 'Technical University of Munich', + 'degree': 'M.Sc. Computer Science', + 'year': '2017', + }, + ], + 'skills': ['Distributed Systems', 'Go', 'Python', 'PostgreSQL', 'Kubernetes', 'gRPC'], + } + state.setdefault('users', {})[MARIA_USER_ID] = maria + return state + + +# Greenhouse fixed IDs for the Senior Backend Engineer requisition +SBE_JOB_ID = 'job-sbe-1' +SBE_STAGE_DEFS = [ + ('stage-job-sbe-1-1', 'Application Review', 0, 'application_review'), + ('stage-job-sbe-1-2', 'Recruiter Phone Screen', 1, 'phone_screen'), + ('stage-job-sbe-1-3', 'Hiring Manager Screen', 2, 'phone_screen'), + ('stage-job-sbe-1-4', 'Technical Interview', 3, 'interview'), + ('stage-job-sbe-1-5', 'Coding Challenge', 4, 'take_home'), + ('stage-job-sbe-1-6', 'Onsite Interview', 5, 'onsite'), + ('stage-job-sbe-1-7', 'Offer', 6, 'offer'), + ('stage-job-sbe-1-8', 'Hired', 7, 'hired'), +] + + +def build_greenhouse_baseline(): + """Default Greenhouse state + an open 'Senior Backend Engineer' job and its stages. + 'LinkedIn' source (src-3) already exists in defaults. NO Maria Volkova candidate.""" + state = fetch_defaults('greenhouse') + + # Add the Senior Backend Engineer job requisition (open). + sbe_job = { + 'id': SBE_JOB_ID, + 'title': 'Senior Backend Engineer', + 'status': 'open', + 'departmentId': 'dept-1', # Engineering + 'officeId': 'office-3', # Remote + 'hiringManagerId': 'user-3', # David Kim, VP of Engineering + 'recruiterId': 'user-1', # Jules Park (current user) + 'coordinatorId': 'user-7', + 'openings': 2, + 'openDate': '2026-05-12', + 'closeDate': None, + 'description': ('We are hiring a Senior Backend Engineer to design and scale the ' + 'distributed services that power our platform. You will own critical ' + 'APIs, mentor engineers, and drive backend architecture decisions.'), + 'requirements': [ + '6+ years of backend engineering experience', + 'Deep expertise in Go or Python', + 'Experience designing distributed systems at scale', + 'Strong knowledge of SQL and event-driven architectures', + 'Experience with cloud platforms (AWS/GCP) and Kubernetes', + ], + 'stages': [sid_ for (sid_, _n, _o, _t) in SBE_STAGE_DEFS], + 'candidateCount': 0, + 'createdAt': '2026-05-12T09:00:00Z', + 'updatedAt': '2026-05-12T09:00:00Z', + } + # Guard against any accidental pre-existing copy. + state['jobs'] = [j for j in state.get('jobs', []) if j.get('id') != SBE_JOB_ID] + state['jobs'].append(sbe_job) + + # Add the job's stages. + state.setdefault('jobStages', []) + state['jobStages'] = [s for s in state['jobStages'] if s.get('jobId') != SBE_JOB_ID] + for (stage_id, name, order, stype) in SBE_STAGE_DEFS: + state['jobStages'].append({ + 'id': stage_id, + 'jobId': SBE_JOB_ID, + 'name': name, + 'orderIndex': order, + 'stageType': stype, + }) + + # Negative constraint: ensure NO Maria Volkova candidate exists in baseline. + state['candidates'] = [c for c in state.get('candidates', []) + if c.get('name', '').strip().lower() != 'maria volkova'] + return state + + +def build_slack_baseline(): + """Default Slack state + a #hiring channel with generic prior chatter (no Maria announcement).""" + state = fetch_defaults('slack') + + members = [u['userId'] for u in state.get('users', [])] + state.setdefault('channels', []) + if not any(c.get('channelId') == 'hiring' for c in state['channels']): + state['channels'].append({ + 'channelId': 'hiring', + 'name': 'hiring', + 'description': 'Recruiting updates, sourcing, and pipeline coordination', + 'topic': 'Hiring & recruiting', + 'isPrivate': False, + 'isStarred': False, + 'members': members, + 'createdBy': 'user_1', + 'createdAt': '2026-01-05T09:00:00Z', + 'pinnedMessages': [], + 'unreadCount': 0, + }) + + state.setdefault('messages', {}) + # Generic, realistic prior messages — none about a newly sourced candidate. + state['messages']['hiring'] = [ + { + 'messageId': 'msg_hiring_1', 'senderId': 'user_2', + 'content': 'Reminder: interview debrief for the Product Designer role is at 4pm today.', + 'timestamp': '2026-06-28T15:02:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False, + }, + { + 'messageId': 'msg_hiring_2', 'senderId': 'user_4', + 'content': 'Updated the scorecard template for engineering loops, please take a look.', + 'timestamp': '2026-06-29T10:18:00Z', 'threadId': None, + 'reactions': [], 'attachments': [], 'isEdited': False, + }, + ] + return state + + +def build_all_baselines(): + return { + 'linkedin': build_linkedin_baseline(), + 'greenhouse': build_greenhouse_baseline(), + 'slack': build_slack_baseline(), + } + + +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 inject_all(baselines, label): + for mock, state in baselines.items(): + http_post(f'{URLS[mock]}/post?sid={sid}', {'action': 'set', 'state': state}) + print(f'[set] baseline injected into all three mocks ({label}): sid={sid}') + + +def verify_baseline(): + gh = http_get_json(f'{URLS["greenhouse"]}/go?sid={sid}')['current_state'] + assert any(j['title'] == 'Senior Backend Engineer' and j['status'] == 'open' + for j in gh['jobs']), 'SBE job missing in greenhouse baseline current_state' + assert any(s['name'] == 'LinkedIn' for s in gh['sources']), 'LinkedIn source missing' + assert not any(c.get('name', '').strip().lower() == 'maria volkova' + for c in gh['candidates']), 'Maria Volkova must NOT exist in baseline' + + li = http_get_json(f'{URLS["linkedin"]}/go?sid={sid}')['current_state'] + assert MARIA_USER_ID in li['users'], 'Maria Volkova LinkedIn profile missing' + assert li['users'][MARIA_USER_ID]['headline'] == 'Senior Software Engineer at Stripe' + + sl = http_get_json(f'{URLS["slack"]}/go?sid={sid}')['current_state'] + assert any(c['channelId'] == 'hiring' for c in sl['channels']), '#hiring channel missing' + assert not any('volkova' in m['content'].lower() or 'sourced' in m['content'].lower() + for m in sl['messages'].get('hiring', [])), 'baseline must have no sourcing announcement' + + +def main(): + baselines = build_all_baselines() + + # 1) Inject baseline (creates initial_state + current_state on all three mocks). + inject_all(baselines, 'pre-launch') + verify_baseline() + print('[verify] baseline OK on all three mocks (no target content present)') + + # Persist sid for golden_patch.py / reward.py + with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + print(f'[sid] wrote /tmp/task_web_sid = {sid}') + + # 2) GUI-ready: open all three apps (Greenhouse, LinkedIn profile, Slack). + li_url = f'{URLS["linkedin"]}/profile/{MARIA_USER_ID}?sid={sid}' + gh_url = f'{URLS["greenhouse"]}/?sid={sid}' + sl_url = f'{URLS["slack"]}/?sid={sid}' + launch_gui(f'google-chrome "{gh_url}" "{li_url}" "{sl_url}"', delay_sec=2.0) + print('GUI_READY: launched Chrome with greenhouse + linkedin profile + slack tabs') + + # 3) The greenhouse SPA persists its in-memory state back to the server via + # set_current on load. If its one-shot fetch of /state transiently fails, + # it cold-starts to DEFAULTS and clobbers current_state (dropping the SBE + # job). Re-assert the baseline AFTER the page's initial persist has settled + # so the stored current_state handed to the agent is correct. + time.sleep(12) + inject_all(baselines, 'post-launch re-assert') + verify_baseline() + print('[verify] baseline re-asserted and confirmed in current_state after browser load') + + +if __name__ == '__main__': + main() diff --git a/legacy/recruit_source_001/reward.py b/legacy/recruit_source_001/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ff92e04fd2e3591df4a9779a1d03d1f9485c06 --- /dev/null +++ b/legacy/recruit_source_001/reward.py @@ -0,0 +1,269 @@ +""" +Reward Script: Source LinkedIn candidate Maria Volkova into Greenhouse + announce in Slack #hiring +Task ID: recruit_source_001 +Domain: mock_websites (greenhouse + slack; linkedin is READ-ONLY source, NOT scored) + +Scoring rubric (sums to 1.0). Every component scores a TASK-INTRODUCED change +(absent from initial_state, present in golden current_state): + + Greenhouse (0.70): + C1 (0.20) New candidate 'Maria Volkova' exists in current_state AND absent from initial_state + C2 (0.15) Candidate currentCompany == 'Stripe' + C3 (0.15) Candidate source enum == 'sourced' (the 'LinkedIn' source-list entry maps to the + 'sourced' enum; candidates store the enum, not the display name) + C4 (0.20) An application links the candidate to the 'Senior Backend Engineer' job, sitting in + that job's INITIAL pipeline stage; this application is absent from initial_state + Slack (0.30): + C5 (0.30) A NEW message in #hiring (count grew vs initial_state) announcing the sourced + candidate — robust keyword check (Maria Volkova + Senior Backend Engineer / sourced) + +The reward script runs ON the VM and reads that VM's own sid from /tmp/task_web_sid, so the same +script returns 1.0 on the golden VM and 0.0 on the initial VM. +""" +import sys +import time + +import requests + +CANDIDATE_NAME = "Maria Volkova" +TARGET_COMPANY = "Stripe" +TARGET_SOURCE_ENUM = "sourced" # 'LinkedIn' source-list entry -> 'sourced' enum +JOB_TITLE = "Senior Backend Engineer" + +GH_URL = "http://28.7.186.212:8156" +SL_URL = "http://28.7.186.212:8198" +PROXY = "http://star-proxy.oa.com:3128" + + +# --- Read sid (this VM's own session id) --- +try: + with open("/tmp/task_web_sid") as f: + sid = f.read().strip() + if not sid: + raise ValueError("sid is empty") +except Exception as e: + print(f"CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}") + print("REWARD: 0.0") + sys.exit(0) + + +def fetch_state(base_url): + """Fetch /go state. Proxy-first, then direct fallback, with retries.""" + url = f"{base_url}/go?sid={sid}" + attempts = [ + {"proxies": {"http": PROXY, "https": PROXY}}, # proxy first + {}, # direct fallback + {"proxies": {"http": PROXY, "https": PROXY}}, # retry proxy + {}, # retry direct + ] + last_err = None + for opt in attempts: + try: + resp = requests.get(url, timeout=30, **opt) + resp.raise_for_status() + return resp.json() + except Exception as e: + last_err = e + time.sleep(2) + raise RuntimeError(f"All fetch attempts failed for {base_url}: {last_err}") + + +def full_name(c): + nm = (c.get("name") or "").strip() + if not nm: + nm = ((c.get("firstName") or "") + " " + (c.get("lastName") or "")).strip() + return nm + + +def find_candidate(candidates, target_name): + tn = target_name.lower().strip() + for c in candidates: + if full_name(c).lower().strip() == tn: + return c + return None + + +def find_job(jobs, title): + tl = title.lower().strip() + for j in jobs: + if (j.get("title") or "").lower().strip() == tl: + return j + return None + + +def initial_stage_id(job, job_stages): + """Return the id of the job's first/initial pipeline stage.""" + # Prefer the ordered 'stages' list on the job object + stages = job.get("stages") + if isinstance(stages, list) and stages: + return stages[0] + # Fallback: jobStages for this job, lowest orderIndex + js = [s for s in job_stages if s.get("jobId") == job.get("id")] + if js: + js_sorted = sorted(js, key=lambda s: s.get("orderIndex", s.get("order", 999))) + return js_sorted[0].get("id") + return None + + +def verify_task(): + total = 0.0 + + # --- Fetch Greenhouse + Slack state --- + try: + gh = fetch_state(GH_URL) + except Exception as e: + print(f"CRITICAL: cannot fetch greenhouse state: {e}") + print("REWARD: 0.0") + return 0.0 + try: + sl = fetch_state(SL_URL) + except Exception as e: + print(f"CRITICAL: cannot fetch slack state: {e}") + print("REWARD: 0.0") + return 0.0 + + gh_init = gh.get("initial_state") or {} + gh_cur = gh.get("current_state") or {} + sl_init = sl.get("initial_state") or {} + sl_cur = sl.get("current_state") or {} + + if not gh_cur or not sl_cur: + print("CRITICAL: current_state missing for greenhouse or slack") + print("REWARD: 0.0") + return 0.0 + + cur_cands = gh_cur.get("candidates", []) or [] + init_cands = gh_init.get("candidates", []) or [] + + cand = find_candidate(cur_cands, CANDIDATE_NAME) + cand_in_initial = find_candidate(init_cands, CANDIDATE_NAME) is not None + + # Component 1: New candidate 'Maria Volkova' exists now AND was absent in initial (0.20) + try: + if cand is not None and not cand_in_initial: + print(f"PASS: C1 — new candidate '{CANDIDATE_NAME}' present in current and absent in initial (0.20)") + total += 0.20 + elif cand is not None and cand_in_initial: + print(f"FAIL: C1 — candidate '{CANDIDATE_NAME}' already existed in initial_state (not task-introduced)") + else: + print(f"FAIL: C1 — candidate '{CANDIDATE_NAME}' not found in current_state") + except Exception as e: + print(f"ERROR: C1 — {e}") + + # Only score candidate-attribute / application components if it is a genuinely NEW candidate + cand_ok_new = cand is not None and not cand_in_initial + + # Component 2: currentCompany == 'Stripe' (0.15) + try: + if cand_ok_new: + cc = (cand.get("currentCompany") or "").strip() + if cc.lower() == TARGET_COMPANY.lower(): + print(f"PASS: C2 — currentCompany == '{TARGET_COMPANY}' (0.15)") + total += 0.15 + else: + print(f"FAIL: C2 — currentCompany expected '{TARGET_COMPANY}', found '{cc}'") + else: + print("FAIL: C2 — no new candidate to check currentCompany") + except Exception as e: + print(f"ERROR: C2 — {e}") + + # Component 3: source enum == 'sourced' (0.15) + try: + if cand_ok_new: + src = (cand.get("source") or "").strip().lower() + if src == TARGET_SOURCE_ENUM: + print(f"PASS: C3 — candidate source == '{TARGET_SOURCE_ENUM}' (LinkedIn -> sourced) (0.15)") + total += 0.15 + else: + print(f"FAIL: C3 — source expected '{TARGET_SOURCE_ENUM}', found '{src}'") + else: + print("FAIL: C3 — no new candidate to check source") + except Exception as e: + print(f"ERROR: C3 — {e}") + + # Component 4: application links candidate -> Senior Backend Engineer job, INITIAL stage, + # and is absent from initial_state (0.20) + try: + if cand_ok_new: + job = find_job(gh_cur.get("jobs", []) or [], JOB_TITLE) + if job is None: + print(f"FAIL: C4 — job '{JOB_TITLE}' not found") + else: + cand_id = cand.get("id") + init_stage = initial_stage_id(job, gh_cur.get("jobStages", []) or []) + cur_apps = gh_cur.get("applications", []) or [] + init_apps = gh_init.get("applications", []) or [] + init_app_ids = {a.get("id") for a in init_apps} + + # application(s) for this candidate + this job in current state + matched = [ + a for a in cur_apps + if a.get("candidateId") == cand_id and a.get("jobId") == job.get("id") + ] + # must be a NEW application (not present in initial_state) + matched_new = [a for a in matched if a.get("id") not in init_app_ids] + + if not matched_new: + print(f"FAIL: C4 — no NEW application linking '{CANDIDATE_NAME}' to '{JOB_TITLE}'") + else: + app = matched_new[0] + stage = app.get("currentStageId") + if init_stage is not None and stage == init_stage: + print(f"PASS: C4 — new application links candidate to '{JOB_TITLE}' at initial stage " + f"'{init_stage}' (0.20)") + total += 0.20 + else: + print(f"FAIL: C4 — application stage '{stage}' is not the initial stage '{init_stage}'") + else: + print("FAIL: C4 — no new candidate to check application linkage") + except Exception as e: + print(f"ERROR: C4 — {e}") + + # Component 5: NEW #hiring Slack message announcing the sourced candidate (0.30) + try: + # locate #hiring channel id + hiring_id = None + for ch in sl_cur.get("channels", []) or []: + if (ch.get("name") or "").lower() == "hiring": + hiring_id = ch.get("channelId") + break + + init_msgs = (sl_init.get("messages", {}) or {}).get(hiring_id, []) if hiring_id else [] + cur_msgs = (sl_cur.get("messages", {}) or {}).get(hiring_id, []) if hiring_id else [] + + if hiring_id is None: + print("FAIL: C5 — #hiring channel not found") + elif len(cur_msgs) <= len(init_msgs): + print(f"FAIL: C5 — no new message in #hiring (init={len(init_msgs)}, cur={len(cur_msgs)})") + else: + # only consider messages that are NEW relative to initial_state + 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] + announced = False + for m in new_msgs: + content = (m.get("content") or "").lower() + has_name = "maria volkova" in content or ("maria" in content and "volkova" in content) + has_context = ( + "senior backend engineer" in content + or "sourced" in content + or "linkedin" in content + or "pipeline" in content + ) + if has_name and has_context: + announced = True + break + if announced: + print("PASS: C5 — new #hiring message announces sourced candidate Maria Volkova (0.30)") + total += 0.30 + else: + print("FAIL: C5 — new #hiring message(s) found but none announce Maria Volkova + pipeline/sourced context") + except Exception as e: + print(f"ERROR: C5 — {e}") + + final = round(min(total, 1.0), 4) + print(f"\nScore: {total}/1.0") + print(f"REWARD: {final}") + return final + + +verify_task() diff --git a/legacy/recruit_source_001/reward_label.json b/legacy/recruit_source_001/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..053661e7811e886db9ce2c6b6981ddb7744198cf --- /dev/null +++ b/legacy/recruit_source_001/reward_label.json @@ -0,0 +1,68 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/recruit_source_001/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:32:43", + "label": { + "task_id": "recruit_source_001", + "domain": "mock_websites", + "summary": "验证是否将 LinkedIn 候选人 Maria Volkova 录入 Greenhouse 并在 Slack #hiring 频道宣布", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "greenhouse_mock (http://28.7.186.212:8166)", + "slack_mock (http://28.7.186.212:8198)" + ], + "scoring_components": [ + { + "name": "C1", + "weight": 0.2, + "description": "新候选人 'Maria Volkova' 存在于 current_state 且不存在于 initial_state", + "check_logic": "在 current_state.candidates 中通过 find_candidate 查找 full_name 为 'Maria Volkova' 的候选人,并确认 initial_state.candidates 中不存在同名候选人", + "pass_condition": "cand 不为 None 且 cand_in_initial 为 False" + }, + { + "name": "C2", + "weight": 0.15, + "description": "候选人当前公司 currentCompany 为 'Stripe'", + "check_logic": "仅当 cand_ok_new 为 True 时检查;取 cand.get('currentCompany') 去除空白后转小写,与 'stripe' 比较", + "pass_condition": "currentCompany 等于 'Stripe'(不区分大小写)" + }, + { + "name": "C3", + "weight": 0.15, + "description": "候选人来源枚举值为 'sourced'(对应 LinkedIn 来源列表项)", + "check_logic": "仅当 cand_ok_new 为 True 时检查;取 cand.get('source') 去除空白后转小写,与 'sourced' 比较", + "pass_condition": "source 等于 'sourced'(不区分大小写)" + }, + { + "name": "C4", + "weight": 0.2, + "description": "新申请将候选人链接到 'Senior Backend Engineer' 职位且处于该职位的初始 pipeline 阶段", + "check_logic": "仅当 cand_ok_new 为 True 时检查;在 current_state.jobs 中查找职位,通过 initial_stage_id 获取初始 stage id;在 current_state.applications 中筛选 candidateId 与 jobId 匹配且 id 不在 init_app_ids 中的新申请;检查 app.get('currentStageId') 是否等于 init_stage", + "pass_condition": "存在新申请(id 不在 initial_state.applications 中),其 candidateId 和 jobId 匹配,且 currentStageId 等于该职位的初始 stage id" + }, + { + "name": "C5", + "weight": 0.3, + "description": "Slack #hiring 频道中有新消息宣布该候选人", + "check_logic": "在 current_state.channels 中查找 name 为 'hiring' 的频道;比较该频道消息数量是否大于 initial 数量;筛选 messageId 不在 init_msgs 中的新消息;检查消息内容是否包含 'maria volkova'(或分别包含 'maria' 和 'volkova')以及上下文关键词('senior backend engineer' / 'sourced' / 'linkedin' / 'pipeline')", + "pass_condition": "#hiring 频道存在,消息数量增加,且至少一条新消息同时包含候选人姓名和上下文关键词" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过 round(min(total, 1.0), 4) 计算,即上限钳制到 1.0 并四舍五入到 4 位小数", + "failure_modes": [ + "无法读取 /tmp/task_web_sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0", + "获取 greenhouse state 失败 -> 打印 CRITICAL 并返回 0.0", + "获取 slack state 失败 -> 打印 CRITICAL 并返回 0.0", + "gh_cur 或 sl_cur 缺失 -> 打印 CRITICAL 并返回 0.0", + "C1 失败(候选人已存在于 initial_state 或未找到)会导致 C2-C4 跳过检查", + "C5 中 #hiring 频道未找到、消息数量未增加、或新消息不包含候选人姓名和上下文关键词" + ], + "scoring_logic_explanation": "脚本首先读取本机 /tmp/task_web_sid 获取会话 ID,然后分别向 Greenhouse 和 Slack 的 mock 服务拉取 initial_state 与 current_state。接着按顺序检查 5 个组件:C1 验证新候选人 Maria Volkova 是否仅出现在 current_state;只有 C1 通过后才会检查 C2-C4(候选人属性与职位申请)。C2 检查 currentCompany 是否为 'Stripe',C3 检查 source 枚举是否为 'sourced',C4 检查是否存在一个新的申请将候选人关联到 'Senior Backend Engineer' 职位且处于初始 pipeline 阶段。C5 独立检查 Slack #hiring 频道是否有新增消息,且消息内容需同时包含候选人姓名(Maria Volkova)和相关上下文关键词(如 Senior Backend Engineer / sourced / LinkedIn / pipeline)。各组件得分累加,最终通过 min(total, 1.0) 钳制上限并四舍五入输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读源码:\n\n1. **Task ID**: recruit_source_001\n2. **Domain**: mock_websites (greenhouse + slack; linkedin is READ-ONLY source, NOT scored)\n3. **Summary**: 验证是否将 LinkedIn 候选人 Maria Volkova 录入 Greenhouse 并在 Slack #hiring 频道宣布\n4. **is_placeholder**: false - 这是一个真正的评分脚本,不是占位符\n5. **data_sources**: \n - /tmp/task_web_sid (读取 session id)\n - Greenhouse mock (http://28.7.186.212:8156)\n - Slack mock (http://28.7.186.212:8198)\n\n6. **Scoring components**:\n - C1 (0.20): 新候选人 'Maria Volkova' 存在于 current_state 且不存在于 initial_state\n - C2 (0.15): 候选人 currentCompany == 'Stripe'\n - C3 (0.15): 候选人 source enum == 'sourced'\n - C4 (0.20): 申请将候选人链接到 'Senior Backend Engineer' 职位,且处于该职位的初始 pipeline 阶段,该申请不存在于 initial_state\n - C5 (0.30): Slack #hiring 频道中有新消息(数量比 initial_state 多),宣布该候选人,包含关键词检查\n\n7. **Score aggregation**: 各组件分数相加,最后取 min(total, 1.0) 并四舍五入到4位小数\n\n8. **Failure modes**:\n - 无法读取 /tmp/task_web_sid -> 0.0\n - 无法获取 greenhouse state -> 0.0\n - 无法获取 slack state -> 0.0\n - current_state 缺失 -> 0.0\n - C1 失败会影响 C2-C4(cand_ok_new 为 false)\n - C5 中 #hiring 频道未找到、无新消息、或新消息不包含关键词\n\n9. **Scoring logic explanation**: 按执行顺序:\n - 读取 /tmp/task_web_sid\n - 获取 Greenhouse 和 Slack 的 initial_state 和 current_state\n - 检查 C1: 新候选人 Maria Volkova\n - 只有 C1 通过才检查 C2-C4\n - C2: currentCompany == 'Stripe'\n - C3: source == 'sourced'\n - C4: 新申请链接到 Senior Backend Engineer 职位且处于初始阶段\n - C5: Slack #hiring 频道新消息宣布候选人\n - 汇总分数,上限 1.0\n\n10. **confidence**: 1.0 - 源码完整且逻辑清晰\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"recruit_source_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否将 LinkedIn 候选人 Maria Volkova 录入 Greenhouse 并在 Slack #hiring 频道宣布\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"greenhouse_mock (http://28.7.186.212:8166)\", \"slack_mock (http://28.7.186.212:8198)\"],\n \"scoring_components\": [\n {\n \"name\": \"C1\",\n \"weight\": 0.2,\n \"description\": \"新候选人 'Maria Volkova' 存在于 current_state 且不存在于 initial_state\",\n \"check_logic\": \"在 current_state.candidates 中查找 full_name 为 'Maria Volkova' 的候选人,并确认 initial_state.candidates 中不存在该候选人\",\n \"pass_condition\": \"cand 不为 None 且 cand_in_initial 为 False\"\n },\n {\n \"name\": \"C2\",\n \"weight\": 0.15,\n \"description\": \"候选人当前公司 currentCompany 为 'Stripe'\",\n \"check_logic\": \"仅当 cand_ok_new 为 True 时检查;比较 cand.get('currentCompany').strip().lower() 是否等于 'stripe'\",\n \"pass_condition\": \"currentCompany 等于 'Stripe'(不区分大小写)\"\n },\n {\n \"name\": \"C3\",\n \"weight\": 0.15,\n \"description\": \"候选人来源枚举值为 'sourced'(对应 LinkedIn 来源列表项)\",\n \"check_logic\": \"仅当 cand_ok_new 为 True 时检查;比较 cand.get('source').strip().lower() 是否等于 'sourced'\",\n \"pass_condition\": \"source 等于 'sourced'(不区分大小写)\"\n },\n {\n \"name\": \"C4\",\n \"weight\": 0.2,\n \"description\": \"新申请将候选人链接到 'Senior Backend Engineer' 职位且处于该职位的初始 pipeline 阶段\",\n \"check_logic\": \"仅当 cand_ok_new 为 True 时检查;在 current_state.jobs 中查找职位,获取初始 stageId;在 current_state.applications 中查找 candidateId 和 jobId 匹配且不在 initial_state.applications 中的新申请;检查 app.get('currentStageId') 是否等于 init_stage\",\n \"pass_condition\": \"存在新申请(id 不在 initial_app_ids 中),其 candidateId 和 jobId 匹配,且 currentStageId 等于该职位的初始 stage id\"\n },\n {\n \"name\": \"C5\",\n \"weight\": 0.3,\n \"description\": \"Slack #hiring 频道中有新消息宣布该候选人\",\n \"check_logic\": \"在 current_state.channels 中查找 name 为 'hiring' 的频道;比较该频道消息数量是否增加;筛选出 messageId 不在 initial_msgs 中的新消息;检查消息内容是否包含 'maria volkova'(或分别包含 'maria' 和 'volkova')以及上下文关键词('senior backend engineer' / 'sourced' / 'linkedin' / 'pipeline')\",\n \"pass_condition\": \"#hiring 频道存在,消息数量增加,且至少一条新消息同时包含候选人姓名和上下文关键词\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终通过 round(min(total, 1.0), 4) 计算,即上限钳制到 1.0 并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"无法读取 /tmp/task_web_sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0\",\n \"获取 greenhouse state 失败 -> 打印 CRITICAL 并返回 0.0\",\n \"获取 slack state 失败 -> 打印 CRITICAL 并返回 0.0\",\n \"gh_cur 或 sl_cur 缺失 -> 打印 CRITICAL 并返回 0.0\",\n \"C1 失败(候选人已存在于 initial_state 或未找到)会导致 C2-C4 跳过检查\",\n \"C5 中 #hiring 频道未找到、消息数量未增加、或新消息不包含候选人姓名和上下文关键词\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取本机 /tmp/task_web_sid 获取会话 ID,然后分别向 Greenhouse 和 Slack 的 mock 服务拉取 initial_state 与 current_state。接着按顺序检查 5 个组件:C1 验证新候选人 Maria Volkova 是否仅出现在 current_state;只有 C1 通过后才会检查 C2-C4(候选人属性与职位申请)。C2 检查 currentCompany 是否为 'Stripe',C3 检查 source 枚举是否为 'sourced',C4 检查是否存在一个新的申请将候选人关联到 'Senior Backend Engineer' 职位且处于初始 pipeline 阶段。C5 独立检查 Slack #hiring 频道是否有新增消息,且消息内容需同时包含候选人姓名(Maria Volkova)和相关上下文关键词(如 Senior Backend Engineer / sourced / LinkedIn / pipeline)。各组件得分累加,最终通过 min(total, 1.0) 钳制上限并四舍五入输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n确认 JSON 格式正确,没有多余内容。 {\n \"task_id\": \"recruit_source_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否将 LinkedIn 候选人 Maria Volkova 录入 Greenhouse 并在 Slack #hiring 频道宣布\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"greenhouse_mock (http://28.7.186.212:8166)\", \"slack_mock (http://28.7.186.212:8198)\"],\n \"scoring_components\": [\n {\n \"name\": \"C1\",\n \"weight\": 0.2,\n \"description\": \"新候选人 'Maria Volkova' 存在于 current_state 且不存在于 initial_state\",\n \"check_logic\": \"在 current_state.candidates 中通过 find_candidate 查找 full_name 为 'Maria Volkova' 的候选人,并确认 initial_state.candidates 中不存在同名候选人\",\n \"pass_condition\": \"cand 不为 None 且 cand_in_initial 为 False\"\n },\n {\n \"name\": \"C2\",\n \"weight\": 0.15,\n \"description\": \"候选人当前公司 currentCompany 为 'Stripe'\",\n \"check_logic\": \"仅当 cand_ok_new 为 True 时检查;取 cand.get('currentCompany') 去除空白后转小写,与 'stripe' 比较\",\n \"pass_condition\": \"currentCompany 等于 'Stripe'(不区分大小写)\"\n },\n {\n \"name\": \"C3\",\n \"weight\": 0.15,\n \"description\": \"候选人来源枚举值为 'sourced'(对应 LinkedIn 来源列表项)\",\n \"check_logic\": \"仅当 cand_ok_new 为 True 时检查;取 cand.get('source') 去除空白后转小写,与 'sourced' 比较\",\n \"pass_condition\": \"source 等于 'sourced'(不区分大小写)\"\n },\n {\n \"name\": \"C4\",\n \"weight\": 0.2,\n \"description\": \"新申请将候选人链接到 'Senior Backend Engineer' 职位且处于该职位的初始 pipeline 阶段\",\n \"check_logic\": \"仅当 cand_ok_new 为 True 时检查;在 current_state.jobs 中查找职位,通过 initial_stage_id 获取初始 stage id;在 current_state.applications 中筛选 candidateId 与 jobId 匹配且 id 不在 init_app_ids 中的新申请;检查 app.get('currentStageId') 是否等于 init_stage\",\n \"pass_condition\": \"存在新申请(id 不在 initial_state.applications 中),其 candidateId 和 jobId 匹配,且 currentStageId 等于该职位的初始 stage id\"\n },\n {\n \"name\": \"C5\",\n \"weight\": 0.3,\n \"description\": \"Slack #hiring 频道中有新消息宣布该候选人\",\n \"check_logic\": \"在 current_state.channels 中查找 name 为 'hiring' 的频道;比较该频道消息数量是否大于 initial 数量;筛选 messageId 不在 init_msgs 中的新消息;检查消息内容是否包含 'maria volkova'(或分别包含 'maria' 和 'volkova')以及上下文关键词('senior backend engineer' / 'sourced' / 'linkedin' / 'pipeline')\",\n \"pass_condition\": \"#hiring 频道存在,消息数量增加,且至少一条新消息同时包含候选人姓名和上下文关键词\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终通过 round(min(total, 1.0), 4) 计算,即上限钳制到 1.0 并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"无法读取 /tmp/task_web_sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0\",\n \"获取 greenhouse state 失败 -> 打印 CRITICAL 并返回 0.0\",\n \"获取 slack state 失败 -> 打印 CRITICAL 并返回 0.0\",\n \"gh_cur 或 sl_cur 缺失 -> 打印 CRITICAL 并返回 0.0\",\n \"C1 失败(候选人已存在于 initial_state 或未找到)会导致 C2-C4 跳过检查\",\n \"C5 中 #hiring 频道未找到、消息数量未增加、或新消息不包含候选人姓名和上下文关键词\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取本机 /tmp/task_web_sid 获取会话 ID,然后分别向 Greenhouse 和 Slack 的 mock 服务拉取 initial_state 与 current_state。接着按顺序检查 5 个组件:C1 验证新候选人 Maria Volkova 是否仅出现在 current_state;只有 C1 通过后才会检查 C2-C4(候选人属性与职位申请)。C2 检查 currentCompany 是否为 'Stripe',C3 检查 source 枚举是否为 'sourced',C4 检查是否存在一个新的申请将候选人关联到 'Senior Backend Engineer' 职位且处于初始 pipeline 阶段。C5 独立检查 Slack #hiring 频道是否有新增消息,且消息内容需同时包含候选人姓名(Maria Volkova)和相关上下文关键词(如 Senior Backend Engineer / sourced / LinkedIn / pipeline)。各组件得分累加,最终通过 min(total, 1.0) 钳制上限并四舍五入输出。\",\n \"confidence\": 1.0\n}" +} diff --git a/legacy/sdr_discovery_call_003/_cua_gym_vm_bridge.sh b/legacy/sdr_discovery_call_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3d159c30606b4c6db6e8cc750237f846e53ca2b --- /dev/null +++ b/legacy/sdr_discovery_call_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.186.212:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.186.212:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.186.212). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.186.212}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.186.212 -> 28.133.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.186.212:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/legacy/sdr_discovery_call_003/initial_setup.py b/legacy/sdr_discovery_call_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed607699ef7febda1606b4b85adebcb8a387960 --- /dev/null +++ b/legacy/sdr_discovery_call_003/initial_setup.py @@ -0,0 +1,530 @@ +# --- 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.186.212", "28.7.186.212"): + 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 books discovery call, advances lead, notifies sales channel +Task ID: sdr_discovery_call_003 +Domain: mock_websites +Mocks: google_calendar_mock, salesforce_mock, slack_mock +""" +import os +import shlex +import subprocess +import time +import uuid +from datetime import date, timedelta + +import requests + +# --- Mock registry --- +MOCKS = { + 'google_calendar_mock': 'http://28.7.186.212:8161', + 'salesforce_mock': 'http://28.7.186.212:8195', + 'slack_mock': 'http://28.7.186.212:8198', +} +PRIMARY = 'google_calendar_mock' +BASE_URL = MOCKS[PRIMARY] + +# --- sid --- +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + + +def upcoming_friday(reference=None): + """Return this/upcoming Friday using the VM's local date as the anchor.""" + reference = reference or date.today() + days_until_friday = (4 - reference.weekday()) % 7 + return reference + timedelta(days=days_until_friday) + + +def iso_on(day, clock): + return f'{day.isoformat()}T{clock}.000Z' + + +TARGET_FRIDAY = upcoming_friday() +WEEK_ANCHOR = TARGET_FRIDAY - timedelta(days=4) + +# --- 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'{BASE_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +# --- Build per-mock initial states --- +def build_google_calendar(): + return { + 'user': { + 'id': 'u1', + 'username': 'Alex Morgan', + 'email': 'alex.morgan@northwindcloud.com', + 'avatar': 'https://i.pravatar.cc/150?u=alex-morgan', + }, + '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': [ + { + 'id': 'evt_standup', + 'calendarId': 'c2', + 'title': 'Team Standup', + 'start': iso_on(TARGET_FRIDAY, '09:00:00'), + 'end': iso_on(TARGET_FRIDAY, '09:30:00'), + 'allDay': False, + 'location': 'Zoom', + 'description': 'Daily sync with the sales pod', + 'guests': [], + 'color': '#33B679', + 'recurring': 'daily', + 'reminders': [{'type': 'popup', 'minutes': 5}], + 'meetLink': '', + 'status': 'confirmed', + }, + { + 'id': 'evt_one_on_one', + 'calendarId': 'c2', + 'title': '1:1 with Manager', + 'start': iso_on(TARGET_FRIDAY, '15:00:00'), + 'end': iso_on(TARGET_FRIDAY, '15:30:00'), + 'allDay': False, + 'location': 'Manager office', + 'description': 'Weekly check-in', + 'guests': ['dana.kim@northwindcloud.com'], + 'color': '#33B679', + 'recurring': 'weekly', + 'reminders': [{'type': 'popup', 'minutes': 10}], + 'meetLink': '', + 'status': 'confirmed', + }, + ], + 'view': 'week', + 'currentDate': iso_on(WEEK_ANCHOR, '00:00:00'), + 'sidebarOpen': True, + 'settings': { + 'weekStart': 0, + 'defaultDuration': 60, + 'defaultView': 'week', + 'defaultReminder': {'type': 'popup', 'minutes': 10}, + 'timeFormat': '12h', + 'showWeekNumbers': False, + 'showDeclinedEvents': False, + }, + } + + +def build_salesforce(): + sdr = { + 'userId': 'user-1', + 'firstName': 'Alex', + 'lastName': 'Morgan', + 'email': 'alex.morgan@northwindcloud.com', + 'phone': '(555) 123-4567', + 'title': 'Sales Development Representative', + 'department': 'Sales', + 'role': 'SDR', + 'avatar': 'https://i.pravatar.cc/150?u=user-1', + 'timezone': 'America/New_York', + 'locale': 'en-US', + 'theme': 'lightning', + } + return { + 'user': sdr, + 'users': [sdr], + 'leads': [ + { + 'leadId': 'lead-1', + 'firstName': 'Sarah', + 'lastName': 'Johnson', + 'company': 'TechVentures Inc.', + 'title': 'VP of Engineering', + 'email': 'sarah.j@techventures.com', + 'phone': '(555) 111-2222', + 'mobile': '', + 'status': 'New', + 'source': 'Website', + 'rating': 'Hot', + 'street': '', 'city': 'San Francisco', 'state': 'CA', 'zip': '94105', 'country': 'USA', + 'industry': 'Technology', + 'employees': 250, + 'revenue': 15000000, + 'website': 'https://www.techventures.com', + 'description': 'Inbound lead from website demo request.', + 'ownerId': 'user-1', + 'createdDate': '2026-06-20T00:00:00.000Z', + 'modifiedDate': '2026-06-20T00:00:00.000Z', + }, + { + 'leadId': 'lead-2', + 'firstName': 'Sara', + 'lastName': 'Johns', + 'company': 'TechVintage LLC', + 'title': 'Operations Lead', + 'email': 'sara.johns@techvintage.com', + 'phone': '(555) 333-4444', + 'mobile': '', + 'status': 'New', + 'source': 'Trade Show', + 'rating': 'Warm', + 'street': '', 'city': 'Austin', 'state': 'TX', 'zip': '73301', 'country': 'USA', + 'industry': 'Retail', + 'employees': 40, + 'revenue': 3000000, + 'website': 'https://www.techvintage.com', + 'description': 'Met at SaaS expo booth.', + 'ownerId': 'user-1', + 'createdDate': '2026-06-19T00:00:00.000Z', + 'modifiedDate': '2026-06-19T00:00:00.000Z', + }, + ], + 'accounts': [], + 'contacts': [], + 'opportunities': [], + 'cases': [], + 'activities': [], + 'chatterPosts': [], + 'files': [], + 'following': [], + 'recentlyViewed': [], + 'dismissedNotifications': [], + } + + +def build_slack(): + sdr = { + 'userId': 'user_1', + 'fullName': 'Alex Morgan', + 'displayName': 'Alex', + 'email': 'alex.morgan@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=1', + 'title': 'Sales Development Representative', + 'status': 'online', + 'statusMessage': '', + 'statusEmoji': '', + 'timeZone': 'America/New_York', + } + users = [ + sdr, + {'userId': 'user_2', 'fullName': 'Dana Kim', 'displayName': 'Dana', 'email': 'dana.kim@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Sales Manager', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + {'userId': 'user_3', 'fullName': 'Marcus Lee', 'displayName': 'Marcus', 'email': 'marcus.lee@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Account Executive', 'status': 'away', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'}, + {'userId': 'user_4', 'fullName': 'Priya Patel', 'displayName': 'Priya', 'email': 'priya.patel@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Sales Operations', 'status': 'online', + 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'}, + ] + return { + 'currentUser': sdr, + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind Cloud', 'icon': ''}, + 'users': users, + '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': '2026-01-05T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'sales', 'name': 'sales', 'description': 'Sales team pipeline and wins', 'topic': 'Close the quarter strong', + 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3'], + 'createdBy': 'user_2', 'createdAt': '2026-01-05T10:05:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'sales-ops', 'name': 'sales-ops', 'description': 'Tooling, CRM hygiene, process', 'topic': 'Keep the CRM clean', + 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_4'], + 'createdBy': 'user_4', 'createdAt': '2026-01-05T10:10:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'messages': { + 'general': [ + {'messageId': 'msg_g1', 'senderId': 'user_2', 'content': 'Morning team, big week ahead!', + 'timestamp': '2026-06-22T13:00:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'sales': [ + {'messageId': 'msg_s1', 'senderId': 'user_3', 'content': 'Closed the Acme renewal this morning.', + 'timestamp': '2026-06-22T14:30:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + {'messageId': 'msg_s2', 'senderId': 'user_2', 'content': 'Nice work Marcus! Keep the momentum going.', + 'timestamp': '2026-06-22T14:35:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'sales-ops': [ + {'messageId': 'msg_so1', 'senderId': 'user_4', 'content': 'Reminder: update lead statuses before EOW.', + 'timestamp': '2026-06-22T09: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': [], + } + + +BUILDERS = { + 'google_calendar_mock': build_google_calendar, + 'salesforce_mock': build_salesforce, + 'slack_mock': build_slack, +} + +# --- 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}] State injection failed: {resp.status_code} {resp.text}' + go = requests.get(f'{url}/go?sid={sid}', timeout=10, 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}') +print(f'Target discovery call slot: {TARGET_FRIDAY.isoformat()} 14:00-14:30 local time') + + +# --- Launch browser --- +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 = BASE_URL +launch_gui(f'google-chrome "{BASE_URL}/?sid={sid}"', delay_sec=2.0) +_open_remaining_mock_tabs(_primary_mock_url) +wait_mocks_loaded() +print(f'GUI_READY: launched browser at {BASE_URL}/?sid={sid}') diff --git a/legacy/sdr_discovery_call_003/reward.py b/legacy/sdr_discovery_call_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..36ef2b326555f8e12842ec8093b4ba626c299e06 --- /dev/null +++ b/legacy/sdr_discovery_call_003/reward.py @@ -0,0 +1,529 @@ +# --- 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.186.212", "28.7.186.212"): + if _h not in _np: + _np = (_np + "," + _h).lstrip(",") +_os.environ["no_proxy"] = _np +_os.environ["NO_PROXY"] = _np +# --- end override --- + +""" +Reward Script: SDR books discovery call, advances lead, and notifies Slack +Task ID: sdr_discovery_call_003 +Domain: mock_websites (multi-mock: google_calendar, salesforce, slack) + +Scoring (all components measure task-introduced changes; each FAILS on initial_env): + Component 1 — Google Calendar discovery-call event (0.40) + 1a (0.20) NEW event on Work calendar (c2), this/upcoming Friday 14:00-14:30 local date + 1b (0.10) guest 'sarah.j@techventures.com' present on that event + 1c (0.10) event title/description references Sarah Johnson / TechVentures + Component 2 — Salesforce lead advancement (0.30) + 2a (0.20) Sarah Johnson lead status changed to 'Working' + 2b (0.10) compound: Sarah == 'Working' AND distractor 'Sara Johns' still 'New' + Component 3 — Slack heads-up message in #sales (0.30) + 3a (0.10) a NEW message exists in 'sales' channel (not 'sales-ops'), sent by current user + 3b (0.10) compound: that new message names the customer (Sarah Johnson / TechVentures) + 3c (0.10) compound: that new message states the meeting time AND CRM stage 'Working' +Total: 1.0 +""" +import os +import re +import sys +from datetime import date, datetime, timedelta + +import requests + +CAL_URL = 'http://28.7.186.212:8161' +SF_URL = 'http://28.7.186.212:8195' +SLACK_URL = 'http://28.7.186.212:8198' + +# --- 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'{SLACK_URL}/go?sid=conn-probe') +PROXIES = None +print(f'Egress proxy: {PROXY or "direct"}') + + +def fetch_state(base_url): + """Fetch /go state for a mock. Returns (initial, current) dicts or (None, None).""" + try: + resp = requests.get(f'{base_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 {} + except Exception as e: + print(f'ERROR: Cannot fetch state from {base_url}: {e}') + return None, None + + +def upcoming_friday(reference=None): + """Return this/upcoming Friday using the VM's local date as the anchor.""" + reference = reference or date.today() + days_until_friday = (4 - reference.weekday()) % 7 + return reference + timedelta(days=days_until_friday) + + +TARGET_FRIDAY = upcoming_friday() + + +def _parse_iso_datetime(value): + if not value: + return None + text = str(value).strip() + if text.endswith(('Z', 'z')): + text = text[:-1] + '+00:00' + try: + return datetime.fromisoformat(text) + except ValueError: + return None + + +def _normalize_text(value): + return re.sub(r'\s+', ' ', str(value or '').strip().lower()) + + +def _compact_text(value): + return re.sub(r'[^a-z0-9]+', '', str(value or '').lower()) + + +def _mentions_customer(text): + lower = _normalize_text(text) + compact = _compact_text(text) + mentions_sarah_johnson = ( + re.search(r'\bsarah\b', lower) is not None + and re.search(r'\bjohnson\b', lower) is not None + ) + # Accept TechVentures, Tech Ventures, Tech-Ventures, etc. + return mentions_sarah_johnson or 'techventures' in compact + + +def _status_equals(value, expected): + return str(value or '').strip().lower() == expected.lower() + + +def _same_ymd(candidate, target): + return ( + candidate is not None + and candidate.year == target.year + and candidate.month == target.month + and candidate.day == target.day + ) + + +def _datetime_candidates_from_value(value): + """Parse event datetimes from ISO strings and common UI-rendered variants.""" + text = str(value or '').strip() + candidates = [] + parsed = _parse_iso_datetime(text) + if parsed is not None: + candidates.append(parsed) + if parsed.tzinfo is not None: + try: + candidates.append(parsed.astimezone().replace(tzinfo=None)) + except ValueError: + pass + + dates = _candidate_dates_from_text(text) + times = _time_candidates_from_text(text) + for candidate_date in dates: + for candidate_hour, candidate_minute in times: + candidates.append(datetime( + candidate_date.year, + candidate_date.month, + candidate_date.day, + candidate_hour, + candidate_minute, + )) + return candidates + + +def _matches_target_datetime(value, target, hour, minute): + return any( + _same_ymd(candidate, target) + and candidate.hour == hour + and candidate.minute == minute + for candidate in _datetime_candidates_from_value(value) + ) + + +def _date_from_parts(year, month, day): + try: + return date(int(year), int(month), int(day)) + except (TypeError, ValueError): + return None + + +def _year_or_target(year_text): + if not year_text: + return TARGET_FRIDAY.year + year = int(year_text) + return 2000 + year if year < 100 else year + + +MONTH_RE = ( + r'jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|' + r'jul(?:y)?|aug(?:ust)?|sep(?:t(?:ember)?|tember)?|oct(?:ober)?|' + r'nov(?:ember)?|dec(?:ember)?' +) +MONTH_NUMBERS = { + 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, + 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, +} + + +def _candidate_dates_from_text(text): + """Extract explicit or relative dates from a message as concrete dates.""" + raw = str(text or '') + lower = raw.lower() + candidates = [] + + for match in re.finditer(r'\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b', lower): + candidates.append(_date_from_parts(match.group(1), match.group(2), match.group(3))) + + for match in re.finditer(r'\b(\d{1,2})[-/.](\d{1,2})(?:[-/.](\d{2,4}))?\b', lower): + year = _year_or_target(match.group(3)) + candidates.append(_date_from_parts(year, match.group(1), match.group(2))) + candidates.append(_date_from_parts(year, match.group(2), match.group(1))) + + for match in re.finditer(rf'\b({MONTH_RE})\.?\s+(\d{{1,2}})(?:st|nd|rd|th)?(?:,?\s+(\d{{2,4}}))?\b', lower): + month = MONTH_NUMBERS[match.group(1)[:3]] + year = _year_or_target(match.group(3)) + candidates.append(_date_from_parts(year, month, match.group(2))) + + for match in re.finditer(rf'\b(\d{{1,2}})(?:st|nd|rd|th)?\s+({MONTH_RE})\.?(?:,?\s+(\d{{2,4}}))?\b', lower): + month = MONTH_NUMBERS[match.group(2)[:3]] + year = _year_or_target(match.group(3)) + candidates.append(_date_from_parts(year, month, match.group(1))) + + for match in re.finditer(r'(?:(\d{4})\s*年\s*)?(\d{1,2})\s*月\s*(\d{1,2})\s*日?', raw): + year = _year_or_target(match.group(1)) + candidates.append(_date_from_parts(year, match.group(2), match.group(3))) + + if re.search(r'\b(?:(?:this|upcoming|coming)\s+)?fri(?:day)?\b', lower): + candidates.append(TARGET_FRIDAY) + + return [candidate for candidate in candidates if candidate is not None] + + +def _text_has_target_date(text): + return any(_same_ymd(candidate, TARGET_FRIDAY) for candidate in _candidate_dates_from_text(text)) + + +def _time_candidates_from_text(text): + raw = str(text or '').lower() + candidates = [] + + # 12-hour clock: 2 PM, 2:00pm, 2 p.m., 02:00 PM. + for match in re.finditer( + r'\b(0?[1-9]|1[0-2])(?:\s*[::]\s*([0-5]\d))?\s*([ap])\.?\s*m\.?\b', + raw, + ): + hour = int(match.group(1)) + minute = int(match.group(2) or 0) + meridiem = match.group(3) + if meridiem == 'p' and hour != 12: + hour += 12 + if meridiem == 'a' and hour == 12: + hour = 0 + candidates.append((hour, minute)) + + # 24-hour clock and common bare UI text: 14:00, 14.00, 2:00. + for match in re.finditer(r'\b([01]?\d|2[0-3])\s*[::.]\s*([0-5]\d)\b', raw): + hour = int(match.group(1)) + minute = int(match.group(2)) + candidates.append((hour, minute)) + if hour == 2: + candidates.append((14, minute)) + + # Natural language / Chinese shorthand often produced in Slack updates. + if re.search(r'\b2\s*(?:o[\'’]?clock)\b', raw): + candidates.append((14, 0)) + if re.search(r'(?:下午|午後)\s*2\s*(?:点|點|时|時)?(?:\s*整)?', raw): + candidates.append((14, 0)) + if re.search(r'\b14\s*(?:h|hrs?|hours?)\b|14\s*(?:点|點|时|時)', raw): + candidates.append((14, 0)) + + return candidates + + +def _text_has_target_time(text): + return (14, 0) in _time_candidates_from_text(text) + + +def _work_calendar_ids(cal_state): + ids = {'c2'} + for calendar in cal_state.get('calendars', []) or []: + name = _normalize_text(calendar.get('name')) + if name == 'work' and calendar.get('id'): + ids.add(calendar.get('id')) + return ids + + +def _sales_channel_ids(sl_state): + ids = [] + for channel in sl_state.get('channels', []) or []: + if _normalize_text(channel.get('name')) == 'sales' and channel.get('channelId'): + ids.append(channel.get('channelId')) + if not ids: + ids.append('sales') + return ids + + +def _message_signal_score(message): + text = str(message.get('content', '')) + return sum([ + _mentions_customer(text), + _text_has_target_date(text), + _text_has_target_time(text), + 'working' in text.lower(), + ]) + + +def verify_task(): + total_score = 0.0 + + cal_init, cal_cur = fetch_state(CAL_URL) + sf_init, sf_cur = fetch_state(SF_URL) + sl_init, sl_cur = fetch_state(SLACK_URL) + + # Gate: if any mock state could not be fetched, we cannot verify -> 0.0 + if cal_cur is None or sf_cur is None or sl_cur is None: + print('CRITICAL: One or more mock states unreachable.') + print('REWARD: 0.0') + return 0.0 + + # ============================================================ + # Component 1 — Google Calendar discovery-call event (0.40) + # ============================================================ + discovery_evt = None + try: + init_events = cal_init.get('events', []) or [] + cur_events = cal_cur.get('events', []) or [] + init_ids = {e.get('id') for e in init_events} + work_calendar_ids = _work_calendar_ids(cal_cur) + + # Find a NEW event on the Work calendar (c2) at the dynamic target slot. + for e in cur_events: + if e.get('id') in init_ids: + continue # pre-existing event, not a task change + on_work_calendar = e.get('calendarId') in work_calendar_ids + right_start = _matches_target_datetime( + e.get('start') or e.get('startTime'), + TARGET_FRIDAY, + 14, + 0, + ) + right_end = _matches_target_datetime( + e.get('end') or e.get('endTime'), + TARGET_FRIDAY, + 14, + 30, + ) + if on_work_calendar and right_start and right_end: + discovery_evt = e + break + + # 1a: new 30-min event in the correct slot on Work calendar (0.20) + if discovery_evt is not None: + print(f'PASS: 1a NEW Work-calendar event {TARGET_FRIDAY.isoformat()} 14:00-14:30 (0.20)') + total_score += 0.20 + else: + print(f'FAIL: 1a no NEW c2 event at {TARGET_FRIDAY.isoformat()} 14:00-14:30') + except Exception as e: + print(f'ERROR: Component 1a — {e}') + + # 1b: guest sarah.j@techventures.com present on the discovery event (0.10) + try: + if discovery_evt is not None: + guests = [str(g).lower() for g in (discovery_evt.get('guests') or [])] + if 'sarah.j@techventures.com' in guests: + print('PASS: 1b guest sarah.j@techventures.com present (0.10)') + total_score += 0.10 + else: + print(f'FAIL: 1b guest missing, found guests={guests}') + else: + print('FAIL: 1b no discovery event to check guests') + except Exception as e: + print(f'ERROR: Component 1b — {e}') + + # 1c: event references Sarah Johnson / TechVentures (0.10) + try: + if discovery_evt is not None: + text = (str(discovery_evt.get('title', '')) + ' ' + + str(discovery_evt.get('description', ''))) + if _mentions_customer(text): + print('PASS: 1c event references Sarah Johnson / TechVentures (0.10)') + total_score += 0.10 + else: + print(f'FAIL: 1c title/desc lacks customer reference: {text!r}') + else: + print('FAIL: 1c no discovery event to check text') + except Exception as e: + print(f'ERROR: Component 1c — {e}') + + # ============================================================ + # Component 2 — Salesforce lead advancement (0.30) + # ============================================================ + sarah_status = None + sara_status = None + try: + cur_leads = sf_cur.get('leads', []) or [] + for l in cur_leads: + fn = str(l.get('firstName', '')).strip().lower() + ln = str(l.get('lastName', '')).strip().lower() + company = _compact_text(l.get('company', '')) + if fn == 'sarah' and ln == 'johnson' and 'techventures' in company: + sarah_status = str(l.get('status', '')) + elif fn == 'sara' and ln == 'johns': + sara_status = str(l.get('status', '')) + + # 2a: Sarah Johnson status advanced to 'Working' (0.20) + if _status_equals(sarah_status, 'Working'): + print('PASS: 2a Sarah Johnson lead status == Working (0.20)') + total_score += 0.20 + else: + print(f'FAIL: 2a Sarah Johnson status={sarah_status!r} (expected Working)') + except Exception as e: + print(f'ERROR: Component 2a — {e}') + + # 2b: compound — correct lead advanced AND distractor untouched (0.10) + # (Fails on initial because Sarah is still 'New' there.) + try: + if _status_equals(sarah_status, 'Working') and _status_equals(sara_status, 'New'): + print('PASS: 2b Sarah=Working AND distractor Sara Johns=New (0.10)') + total_score += 0.10 + else: + print(f'FAIL: 2b Sarah={sarah_status!r}, Sara Johns={sara_status!r} ' + '(expected Working / New)') + except Exception as e: + print(f'ERROR: Component 2b — {e}') + + # ============================================================ + # Component 3 — Slack heads-up in #sales (0.30) + # ============================================================ + new_sales_msg = None + authored_new_msgs = [] + try: + sales_channel_ids = _sales_channel_ids(sl_cur) + init_messages = sl_init.get('messages', {}) or {} + cur_messages = sl_cur.get('messages', {}) or {} + init_msgs = [] + cur_msgs = [] + for channel_id in sales_channel_ids: + init_msgs.extend(init_messages.get(channel_id, []) or []) + cur_msgs.extend(cur_messages.get(channel_id, []) or []) + init_msg_ids = {m.get('messageId') for m in init_msgs} + current_user_id = (sl_cur.get('currentUser', {}) or {}).get('userId') + + # New messages in 'sales' that did not exist initially. + new_msgs = [m for m in cur_msgs if m.get('messageId') not in init_msg_ids] + authored_new_msgs = [ + m for m in new_msgs + if (not current_user_id) or m.get('senderId') == current_user_id + ] + if authored_new_msgs: + new_sales_msg = max( + enumerate(authored_new_msgs), + key=lambda item: (_message_signal_score(item[1]), item[0]), + )[1] + + # 3a: a NEW message exists in 'sales', authored by current user (0.10) + if new_sales_msg is not None: + print(f'PASS: 3a NEW #sales message by current user {current_user_id} (0.10)') + total_score += 0.10 + else: + print(f'FAIL: 3a no new #sales message by current user (new={len(new_msgs)})') + except Exception as e: + print(f'ERROR: Component 3a — {e}') + + # 3b: compound — new message names the customer (0.10) + try: + if authored_new_msgs: + if any(_mentions_customer(m.get('content', '')) for m in authored_new_msgs): + print('PASS: 3b message names customer Sarah Johnson / TechVentures (0.10)') + total_score += 0.10 + else: + texts = [m.get('content', '') for m in authored_new_msgs] + print(f'FAIL: 3b customer name missing in authored #sales messages: {texts!r}') + else: + print('FAIL: 3b no new message to check customer name') + except Exception as e: + print(f'ERROR: Component 3b — {e}') + + # 3c: compound — message states meeting time AND CRM stage 'Working' (0.10) + try: + if authored_new_msgs: + # Accept explicit dates (ISO, numeric, month-name, Chinese) or "this Friday", + # then compare year/month/day to the dynamic target date. + matching_msg = None + debug_parts = [] + for m in authored_new_msgs: + text = str(m.get('content', '')) + has_clock = _text_has_target_time(text) + has_date = _text_has_target_date(text) + stage_ok = 'working' in text.lower() + debug_parts.append({ + 'clock': has_clock, + 'date': has_date, + 'stage': stage_ok, + 'text': text, + }) + if has_clock and has_date and stage_ok: + matching_msg = m + break + if matching_msg is not None: + print('PASS: 3c message states meeting time AND stage Working (0.10)') + total_score += 0.10 + else: + print(f'FAIL: 3c no authored #sales message has target date/time and Working; ' + f'details={debug_parts!r}') + else: + print('FAIL: 3c no new message to check time/stage') + except Exception as e: + print(f'ERROR: Component 3c — {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/legacy/sdr_discovery_call_003/reward_label.json b/legacy/sdr_discovery_call_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..59e445deb0155530379e582ab46a6dace8c0950c --- /dev/null +++ b/legacy/sdr_discovery_call_003/reward_label.json @@ -0,0 +1,89 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/sdr_discovery_call_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 21:51:10", + "label": { + "task_id": "sdr_discovery_call_003", + "domain": "mock_websites", + "summary": "验证SDR是否在Google Calendar创建与Sarah Johnson的发现通话事件、在Salesforce将其lead状态推进到Working,并在Slack #sales频道发送包含会议时间与CRM状态的通知消息", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "http://28.7.186.212:8161", + "http://28.7.186.212:8195", + "http://28.7.186.212:8198" + ], + "scoring_components": [ + { + "name": "Component 1a", + "weight": 0.2, + "description": "在Work日历上新建本周/即将到来的周五14:00-14:30的发现通话事件", + "check_logic": "比较current_state与initial_state的events,筛选calendarId属于Work日历(c2或name为work的日历id)、start匹配TARGET_FRIDAY 14:00、end匹配14:30且id不在init_ids中的新事件", + "pass_condition": "存在一个满足上述条件的新事件" + }, + { + "name": "Component 1b", + "weight": 0.1, + "description": "该日历事件的guests中包含指定邮箱", + "check_logic": "在discovery_evt的guests列表中检查是否存在'sarah.j@techventures.com'(代码中将guests转为小写字符串列表进行成员判断)", + "pass_condition": "guests列表包含sarah.j@techventures.com" + }, + { + "name": "Component 1c", + "weight": 0.1, + "description": "事件标题或描述提及客户Sarah Johnson或TechVentures", + "check_logic": "将title和description拼接后,通过_mentions_customer函数检查:同时包含sarah和johnson,或compact后包含techventures", + "pass_condition": "标题或描述中提及客户" + }, + { + "name": "Component 2a", + "weight": 0.2, + "description": "Salesforce中Sarah Johnson的lead状态变为Working", + "check_logic": "遍历sf_cur的leads,匹配firstName为sarah、lastName为johnson且company包含techventures的记录,检查其status是否为Working(_status_equals比较,不区分大小写)", + "pass_condition": "Sarah Johnson的status等于Working" + }, + { + "name": "Component 2b", + "weight": 0.1, + "description": "复合条件:目标lead已推进且干扰项未被改动", + "check_logic": "同时检查sarah_status为Working且sara_status(firstName=sara, lastName=johns)为New", + "pass_condition": "Sarah Johnson状态为Working且Sara Johns状态仍为New" + }, + { + "name": "Component 3a", + "weight": 0.1, + "description": "当前用户在Slack #sales频道发送了新消息", + "check_logic": "获取sales频道(name为sales)的current_state与initial_state消息,排除initial_state中已存在的messageId,筛选senderId等于current_user_id的新消息;若存在多条,选取_message_signal_score最高者", + "pass_condition": "存在至少一条由当前用户发送的、initial_state中没有的新消息" + }, + { + "name": "Component 3b", + "weight": 0.1, + "description": "新消息内容中提及客户名称", + "check_logic": "对authored_new_msgs中任意一条消息,使用_mentions_customer检查content是否同时包含sarah和johnson,或techventures", + "pass_condition": "任意一条新消息提及Sarah Johnson或TechVentures" + }, + { + "name": "Component 3c", + "weight": 0.1, + "description": "新消息同时声明会议时间与CRM阶段Working", + "check_logic": "遍历authored_new_msgs,检查content是否同时满足:_text_has_target_time(包含14:00)、_text_has_target_date(包含TARGET_FRIDAY日期)、以及包含working字样", + "pass_condition": "存在一条新消息同时包含目标会议时间、目标日期和Working字样" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各子组件分数累加,最终通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数", + "failure_modes": [ + "无法从/tmp/task_web_sid读取sid或sid为空:打印CRITICAL并返回0.0", + "任一mock服务(Calendar/Salesforce/Slack)状态拉取失败返回None:打印CRITICAL并返回0.0", + "未找到符合条件的新日历事件导致1b/1c无法检查而不加分", + "Salesforce中未找到Sarah Johnson或Sara Johns记录导致对应子项失败", + "Slack #sales频道无新消息或新消息非当前用户发送导致Component 3子项失败" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话标识,失败则直接返回0.0。接着通过HTTP从三个mock服务(Google Calendar、Salesforce、Slack)分别拉取initial_state与current_state,任一拉取失败即返回0.0。评分分为三大组件:Component 1检查Google Calendar的Work日历上是否在本周/即将到来的周五14:00-14:30新建了发现通话事件,并验证其guests包含sarah.j@techventures.com、标题/描述提及客户;Component 2检查Salesforce中Sarah Johnson的lead状态是否变为Working,且干扰项Sara Johns保持New;Component 3检查Slack #sales频道是否有当前用户发送的新消息,且消息内容提及客户、包含会议时间(日期与14:00)及CRM阶段Working。各子项按0.20/0.10等权重累加,最终总分经min(..., 1.0)钳制并四舍五入到4位小数。异常路径被try-except包裹,出错时打印ERROR但不中断后续评分。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: sdr_discovery_call_003\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock: google_calendar, salesforce, slack)\"\n3. **summary**: 一句话概括:验证 SDR 是否在 Google Calendar 创建了与 Sarah Johnson 的发现通话事件、在 Salesforce 中将 Sarah Johnson 的 lead 状态推进到 Working,并在 Slack #sales 频道发送了通知消息。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `http://28.7.186.212:8161` (Google Calendar mock)\n - `http://28.7.186.212:8195` (Salesforce mock)\n - `http://28.7.186.212:8198` (Slack mock)\n6. **scoring_components**:\n - Component 1: Google Calendar discovery-call event (0.40)\n - 1a (0.20): NEW event on Work calendar (c2), this/upcoming Friday 14:00-14:30\n - 1b (0.10): guest 'sarah.j@techventures.com' present\n - 1c (0.10): event title/description references Sarah Johnson / TechVentures\n - Component 2: Salesforce lead advancement (0.30)\n - 2a (0.20): Sarah Johnson lead status changed to 'Working'\n - 2b (0.10): Sarah == 'Working' AND distractor 'Sara Johns' still 'New'\n - Component 3: Slack heads-up message in #sales (0.30)\n - 3a (0.10): NEW message in 'sales' channel, sent by current user\n - 3b (0.10): message names customer (Sarah Johnson / TechVentures)\n - 3c (0.10): message states meeting time AND CRM stage 'Working'\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后通过 `round(min(total_score, 1.0), 4)` 汇总,即相加后钳制到上限 1.0。\n9. **failure_modes**:\n - 读取 sid 失败(/tmp/task_web_sid 不存在或为空)-> 打印 CRITICAL 并返回 0.0\n - 任一 mock 状态拉取失败(cal_cur, sf_cur, sl_cur 为 None)-> 打印 CRITICAL 并返回 0.0\n - 各子组件检查失败会打印 FAIL 但不提前退出,只是不加分\n - 异常会被捕获打印 ERROR 但不中断流程\n\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 解析代理设置,然后依次从三个 mock 服务(Google Calendar、Salesforce、Slack)拉取 initial_state 和 current_state,任一拉取失败则返回 0.0。\n - Component 1:在 Calendar current_state 中查找 Work 日历(c2)上、本周/ upcoming Friday 14:00-14:30 的新事件(排除 initial_state 中已存在的事件)。找到后分别检查是否包含指定 guest 邮箱、标题/描述是否提及客户。\n - Component 2:在 Salesforce current_state 的 leads 列表中查找 Sarah Johnson(公司 TechVentures)的状态是否为 Working,以及干扰项 Sara Johns 是否仍为 New。\n - Component 3:在 Slack current_state 的 sales 频道中找出 initial_state 中没有的新消息,且发送者为当前用户。然后检查这些消息是否提及客户、是否包含会议时间(日期+14:00)和 CRM stage 'Working'。\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: \"sdr_discovery_call_003\"\ndomain: \"mock_websites\"\nsummary: \"验证SDR是否在Google Calendar创建与Sarah Johnson的发现通话事件、在Salesforce将其lead状态推进到Working,并在Slack #sales频道发送包含会议时间与CRM状态的通知消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"http://28.7.186.212:8161\", \"http://28.7.186.212:8195\", \"http://28.7.186.212:8198\"]\n\nscoring_components:\n- name: \"Component 1a\", weight: 0.20, description: \"在Work日历上新建本周/即将到来的周五14:00-14:30的发现通话事件\", check_logic: \"比较current_state与initial_state的events,筛选calendarId属于Work日历(c2或name为work的日历id)、start匹配TARGET_FRIDAY 14:00、end匹配14:30且id不在init_ids中的新事件\", pass_condition: \"存在一个满足上述条件的新事件\"\n- name: \"Component 1b\", weight: 0.10, description: \"该日历事件的guests中包含指定邮箱\", check_logic: \"在discovery_evt的guests列表中检查是否存在'sarah.j@techventures.com'(不区分大小写,代码中转为小写比较)\", pass_condition: \"guests列表包含sarah.j@techventures.com\"\n- name: \"Component 1c\", weight: 0.10, description: \"事件标题或描述提及客户Sarah Johnson或TechVentures\", check_logic: \"将title和description拼接后,通过_mentions_customer函数检查:同时包含sarah和johnson,或compact后包含techventures\", pass_condition: \"标题或描述中提及客户\"\n- name: \"Component 2a\", weight: 0.20, description: \"Salesforce中Sarah Johnson的lead状态变为Working\", check_logic: \"遍历sf_cur的leads,匹配firstName为sarah、lastName为johnson且company包含techventures的记录,检查其status是否为Working(_status_equals比较,不区分大小写)\", pass_condition: \"Sarah Johnson的status等于Working\"\n- name: \"Component 2b\", weight: 0.10, description: \"复合条件:目标lead已推进且干扰项未被改动\", check_logic: \"同时检查sarah_status为Working且sara_status(firstName=sara, lastName=johns)为New\", pass_condition: \"Sarah Johnson状态为Working且Sara Johns状态仍为New\"\n- name: \"Component 3a\", weight: 0.10, description: \"当前用户在Slack #sales频道发送了新消息\", check_logic: \"获取sales频道(name为sales)的current_state与initial_state消息,排除initial_state中已存在的messageId,筛选senderId等于current_user_id的新消息;若存在多条,选取_message_signal_score最高者\", pass_condition: \"存在至少一条由当前用户发送的、initial_state中没有的新消息\"\n- name: \"Component 3b\", weight: 0.10, description: \"新消息内容中提及客户名称\", check_logic: \"对authored_new_msgs中任意一条消息,使用_mentions_customer检查content是否同时包含sarah和johnson,或techventures\", pass_condition: \"任意一条新消息提及Sarah Johnson或TechVentures\"\n- name: \"Component 3c\", weight: 0.10, description: \"新消息同时声明会议时间与CRM阶段Working\", check_logic: \"遍历authored_new_msgs,检查content是否同时满足:_text_has_target_time(包含14:00)、_text_has_target_date(包含TARGET_FRIDAY日期)、以及包含working字样\", pass_condition: \"存在一条新消息同时包含目标会议时间、目标日期和Working字样\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各子组件分数累加,最终通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数\"\nfailure_modes: [\n \"无法从/tmp/task_web_sid读取sid或sid为空:打印CRITICAL并返回0.0\",\n \"任一mock服务(Calendar/Salesforce/Slack)状态拉取失败返回None:打印CRITICAL并返回0.0\",\n \"未找到符合条件的新日历事件导致1b/1c无法检查\",\n \"Salesforce中未找到Sarah Johnson或Sara Johns记录\",\n \"Slack #sales频道无新消息或新消息非当前用户发送\"\n]\nscoring_logic_explanation: \"脚本首先读取/tmp/task_web_sid获取会话标识,失败则直接返回0.0。接着通过HTTP从三个mock服务(Google Calendar、Salesforce、Slack)分别拉取initial_state与current_state,任一拉取失败即返回0.0。评分分为三大组件:Component 1检查Google Calendar的Work日历上是否在本周/即将到来的周五14:00-14:30新建了发现通话事件,并验证其guests包含sarah.j@techventures.com、标题/描述提及客户;Component 2检查Salesforce中Sarah Johnson的lead状态是否变为Working,且干扰项Sara Johns保持New;Component 3检查Slack #sales频道是否有当前用户发送的新消息,且消息内容提及客户、包含会议时间(日期与14:00)及CRM阶段Working。各子项按0.20/0.10等权重累加,最终总分经min(..., 1.0)钳制并四舍五入到4位小数。异常路径被try-except包裹,出错时打印ERROR但不中断后续评分。\"\nconfidence: 1.0\n\n检查 JSON 格式是否合法。所有字符串需要正确转义。确保没有多余的逗号。\n\n再检查一下 weight 字段。代码中显式给出的分值:\n- 1a: 0.20\n- 1b: 0.10\n- 1c: 0.10\n- 2a: 0.20\n- 2b: 0.10\n- 3a: 0.10\n- 3b: 0.10\n- 3c: 0.10\n总和正好是 1.0。\n\ndata_sources 应该包含 mock 服务的地址。脚本从 /tmp/task_web_sid 获取 sid,然后从三个 URL 获取状态。\n\n确认 domain 提取:docstring 中明确写了 \"Domain: mock_websites (multi-mock: google_calendar, salesforce, slack)\",所以 domain 是 \"mock_websites\"。\n\n确认 is_placeholder:false,因为脚本有完整的验证逻辑。\n\n确认 score_aggregation:代码中是 total_score 累加,最后 `final_score = round(min(total_score, 1.0), 4)`。\n\n确认 failure_modes:\n- sid 读取失败:sys.exit(0) 之前打印 REWARD: 0.0\n- mock 状态获取失败:return 0.0\n- 其他失败只是不加分,不提前退出。\n\nJSON 中不能有注释。确保所有 key 都用双引号。\n\n让我再仔细看看代码中有没有隐含的失败模式。例如:\n- `if cal_cur is None or sf_cur is None or sl_cur is None:` 这是显式的。\n- sid 读取失败是显式的。\n- 其他子组件的异常被捕获,打印 ERROR,不退出。\n\n好的,开始输出 JSON。 {\"task_id\":\"sdr_discovery_call_003\",\"domain\":\"mock_websites\",\"summary\":\"验证SDR是否在Google Calendar创建与Sarah Johnson的发现通话事件、在Salesforce将其lead状态推进到Working,并在Slack #sales频道发送包含会议时间与CRM状态的通知消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"http://28.7.186.212:8161\",\"http://28.7.186.212:8195\",\"http://28.7.186.212:8198\"],\"scoring_components\":[{\"name\":\"Component 1a\",\"weight\":0.2,\"description\":\"在Work日历上新建本周/即将到来的周五14:00-14:30的发现通话事件\",\"check_logic\":\"比较current_state与initial_state的events,筛选calendarId属于Work日历(c2或name为work的日历id)、start匹配TARGET_FRIDAY 14:00、end匹配14:30且id不在init_ids中的新事件\",\"pass_condition\":\"存在一个满足上述条件的新事件\"},{\"name\":\"Component 1b\",\"weight\":0.1,\"description\":\"该日历事件的guests中包含指定邮箱\",\"check_logic\":\"在discovery_evt的guests列表中检查是否存在'sarah.j@techventures.com'(代码中将guests转为小写字符串列表进行成员判断)\",\"pass_condition\":\"guests列表包含sarah.j@techventures.com\"},{\"name\":\"Component 1c\",\"weight\":0.1,\"description\":\"事件标题或描述提及客户Sarah Johnson或TechVentures\",\"check_logic\":\"将title和description拼接后,通过_mentions_customer函数检查:同时包含sarah和johnson,或compact后包含techventures\",\"pass_condition\":\"标题或描述中提及客户\"},{\"name\":\"Component 2a\",\"weight\":0.2,\"description\":\"Salesforce中Sarah Johnson的lead状态变为Working\",\"check_logic\":\"遍历sf_cur的leads,匹配firstName为sarah、lastName为johnson且company包含techventures的记录,检查其status是否为Working(_status_equals比较,不区分大小写)\",\"pass_condition\":\"Sarah Johnson的status等于Working\"},{\"name\":\"Component 2b\",\"weight\":0.1,\"description\":\"复合条件:目标lead已推进且干扰项未被改动\",\"check_logic\":\"同时检查sarah_status为Working且sara_status(firstName=sara, lastName=johns)为New\",\"pass_condition\":\"Sarah Johnson状态为Working且Sara Johns状态仍为New\"},{\"name\":\"Component 3a\",\"weight\":0.1,\"description\":\"当前用户在Slack #sales频道发送了新消息\",\"check_logic\":\"获取sales频道(name为sales)的current_state与initial_state消息,排除initial_state中已存在的messageId,筛选senderId等于current_user_id的新消息;若存在多条,选取_message_signal_score最高者\",\"pass_condition\":\"存在至少一条由当前用户发送的、initial_state中没有的新消息\"},{\"name\":\"Component 3b\",\"weight\":0.1,\"description\":\"新消息内容中提及客户名称\",\"check_logic\":\"对authored_new_msgs中任意一条消息,使用_mentions_customer检查content是否同时包含sarah和johnson,或techventures\",\"pass_condition\":\"任意一条新消息提及Sarah Johnson或TechVentures\"},{\"name\":\"Component 3c\",\"weight\":0.1,\"description\":\"新消息同时声明会议时间与CRM阶段Working\",\"check_logic\":\"遍历authored_new_msgs,检查content是否同时满足:_text_has_target_time(包含14:00)、_text_has_target_date(包含TARGET_FRIDAY日期)、以及包含working字样\",\"pass_condition\":\"存在一条新消息同时包含目标会议时间、目标日期和Working字样\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各子组件分数累加,最终通过min(total_score, 1.0)钳制到上限1.0,并四舍五入保留4位小数\",\"failure_modes\":[\"无法从/tmp/task_web_sid读取sid或sid为空:打印CRITICAL并返回0.0\",\"任一mock服务(Calendar/Salesforce/Slack)状态拉取失败返回None:打印CRITICAL并返回0.0\",\"未找到符合条件的新日历事件导致1b/1c无法检查而不加分\",\"Salesforce中未找到Sarah Johnson或Sara Johns记录导致对应子项失败\",\"Slack #sales频道无新消息或新消息非当前用户发送导致Component 3子项失败\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话标识,失败则直接返回0.0。接着通过HTTP从三个mock服务(Google Calendar、Salesforce、Slack)分别拉取initial_state与current_state,任一拉取失败即返回0.0。评分分为三大组件:Component 1检查Google Calendar的Work日历上是否在本周/即将到来的周五14:00-14:30新建了发现通话事件,并验证其guests包含sarah.j@techventures.com、标题/描述提及客户;Component 2检查Salesforce中Sarah Johnson的lead状态是否变为Working,且干扰项Sara Johns保持New;Component 3检查Slack #sales频道是否有当前用户发送的新消息,且消息内容提及客户、包含会议时间(日期与14:00)及CRM阶段Working。各子项按0.20/0.10等权重累加,最终总分经min(..., 1.0)钳制并四舍五入到4位小数。异常路径被try-except包裹,出错时打印ERROR但不中断后续评分。\",\"confidence\":1.0}" +} diff --git a/mktg_perf_report_005/_cua_gym_vm_bridge.sh b/mktg_perf_report_005/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/mktg_perf_report_005/_cua_gym_vm_bridge.sh @@ -0,0 +1,106 @@ +#!/bin/bash +# CUA-Gym VM-side network fix (direct-IP mock access). +# +# Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by +# their real IDC address (http://28.7.184.198:81xx) instead of the old +# localhost:9000-9097 socat bridge, so the VM only needs two fixes: +# +# 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's +# cluster DNS, which is unreachable from QEMU SLIRP NAT +# ("Temporary failure in name resolution"). +# 2. The mock host excluded from the woa http proxy — otherwise the VM's +# Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403 +# from the proxy when hitting 28.7.184.198:81xx. (The old socat path never +# hit this because localhost is bypassed by default.) +# +# Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic +# OSWorld setup pipeline. +# +# Argv: +# $1 optional sudo password (default "password"; SetupController +# substitutes {CLIENT_PASSWORD} when uploaded as a cache file). +# $2 unused (kept for backward compat — was socat first port 9000). +# $3 unused (kept for backward compat — was socat last port 9097). +# $4 optional mock host IP (default 28.7.184.198). + +set +e + +PASS="${1:-password}" +MOCK_HOST="${4:-28.7.184.198}" +# Derive the /16 IDC subnet so future port/host tweaks on the same segment +# stay bypassed too (28.7.184.198 -> 28.7.0.0/16). +MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')" + +run_root() { + echo "$PASS" | sudo -S -p "" bash -c "$1" +} + +# Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2. +GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')" +GW="${GW:-10.0.2.2}" + +# ─── CUA-Gym network fix (Taiji-specific) ───────────────────────────── +fix_vm_network() { + # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP + # DNS forwarder. Nothing hardcoded except the mock host above. + local GW_NET="${GW%.*}" + local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3 + local OWN_CIDR + OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \ + | awk '{print $4; exit}')" + local OWN_IP="${OWN_CIDR%/*}" + local OWN_NET="" + [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24" + + # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps + # systemd-resolved/NetworkManager from clobbering it. + if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf + chattr +i /etc/resolv.conf 2>/dev/null || true"; then + echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})" + else + echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf" + fi + + # 2) Build the proxy bypass list from detected values + the direct-IP + # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx + # reachable from inside the VM — without it the woa proxy 403s it. + local ignore_list="['localhost', '127.0.0.0/8', '${GW}'" + [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'" + [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'" + [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'" + [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'" + [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'" + ignore_list="${ignore_list}]" + + # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these. + if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then + echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}" + else + echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)" + fi + + # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl). + local NP="localhost,127.0.0.1,${GW}" + [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}" + [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}" + [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24" + [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}" + [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}" + + for var in no_proxy NO_PROXY; do + if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then + echo "export ${var}=${NP}" >> /home/user/.bashrc + fi + done + run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \ + && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \ + || echo 'no_proxy=\"${NP}\"' >> /etc/environment + grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \ + && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \ + || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1 + echo "[cua_gym_vm_bridge] no_proxy=${NP}" +} + +fix_vm_network + +echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed" diff --git a/mktg_perf_report_005/initial_setup.py b/mktg_perf_report_005/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fe97c22dda159c6957922212c4f80056e5aafd72 --- /dev/null +++ b/mktg_perf_report_005/initial_setup.py @@ -0,0 +1,500 @@ +""" +Initial Setup: post-campaign performance pull (HubSpot -> Google Sheets -> Airtable -> Slack -> Gmail) +Task ID: mktg_perf_report_005 +Domain: mock_websites (multi-app web pipeline) + +FIX ROUND 2 (Option A): use a DISTINCT sid per environment. This script runs on the +INITIAL VM only and uses sid `prof16_perf_report_002_initial`. It writes the BLANK +initial state via action:"set" (so both initial_state and current_state are blank on +the initial VM). The golden VM uses a separate sid, so the two environments' server +state are fully independent and the reward script (which reads /tmp/task_web_sid on +whichever VM it runs on) sees blank on the initial VM and golden on the golden VM. + +Mocks (blank initial state): + - HubSpot http://28.7.184.198:8150 (read-only source of campaign metrics) + - Google Sheets http://28.7.184.198:8145 (row 3 to be filled by agent) + - Airtable http://28.7.184.198:8109 (record Status: Live -> Reported) + - Slack http://28.7.184.198:8178 (post to #campaign-reporting) + - Gmail http://28.7.184.198:8138 (send to cmo@northwindcloud.com) +""" + +import json +import os +import shlex +import subprocess +import time + +import requests + +WORKDIR = '/home/user' +TASK_ID = 'prof16_perf_report_002' +# DISTINCT sid for the INITIAL VM (independent of the golden VM's sid). +SID = 'prof16_perf_report_002_initial' + +# --- Mock endpoints (task-specified IPs/ports) --- +HUBSOT_URL = 'http://28.7.184.198:8150' +SHEETS_URL = 'http://28.7.184.198:8145' +AIRTABLE_URL = 'http://28.7.184.198:8109' +SLACK_URL = 'http://28.7.184.198:8178' +GMAIL_URL = 'http://28.7.184.198:8138' + +MOCKS = { + 'hubspot': HUBSOT_URL, + 'sheets': SHEETS_URL, + 'airtable': AIRTABLE_URL, + 'slack': SLACK_URL, + 'gmail': GMAIL_URL, +} + +# --- Canonical campaign metrics (the fixed source figures) --- +MQLS = 312 +OPEN_RATE = '38.4%' +CONVERSION_RATE = '4.9%' +CAMPAIGN_NAME = 'Spring Nurture 2026' +RECIPIENT = 'cmo@northwindcloud.com' + + +def build_hubspot_state(): + """HubSpot: the 'Campaign Performance' report is the read-only source. + A custom `campaignReports` structure carries the three canonical metrics; + standard HubSpot keys are populated so the app renders.""" + return { + 'contacts': [ + {'id': 'c1', 'firstName': 'Sarah', 'lastName': 'Chen', 'email': 'sarah.chen@northwindcloud.com', + 'phone': '+1 (555) 010-2233', 'jobTitle': 'Campaign Manager', 'companyId': 'comp1', + 'lifecycleStage': 'customer', 'leadStatus': 'open_deal', 'owner': 'Admin User', + 'city': 'Austin', 'state': 'TX', 'country': 'United States', + 'createDate': '2026-01-10T09:00:00Z', 'lastActivityDate': '2026-06-20T14:00:00Z', 'timeline': []}, + {'id': 'c2', 'firstName': 'Marcus', 'lastName': 'Johnson', 'email': 'marcus.johnson@northwindcloud.com', + 'phone': '+1 (555) 010-2244', 'jobTitle': 'Marketing Director', 'companyId': 'comp1', + 'lifecycleStage': 'customer', 'leadStatus': 'open_deal', 'owner': 'Admin User', + 'city': 'Austin', 'state': 'TX', 'country': 'United States', + 'createDate': '2026-01-12T09:00:00Z', 'lastActivityDate': '2026-06-18T14:00:00Z', 'timeline': []}, + ], + 'companies': [ + {'id': 'comp1', 'name': 'Northwind Cloud', 'domain': 'northwindcloud.com', 'industry': 'Technology', + 'phone': '+1 (555) 100-0001', 'city': 'Austin', 'state': 'TX', 'country': 'United States', + 'numberOfEmployees': 420, 'annualRevenue': 48000000, 'lifecycleStage': 'customer', + 'owner': 'Admin User', 'description': 'Cloud infrastructure and marketing platform provider', + 'createDate': '2026-01-05T09:00:00Z'}, + ], + 'deals': [ + {'id': 'd1', 'name': 'Northwind Expansion', 'stage': 'contract_sent', 'amount': 75000, + 'closeDate': '2026-07-30', 'dealType': 'existing_business', 'priority': 'high', 'owner': 'Admin User', + 'companyId': 'comp1', 'contactIds': ['c1'], 'probability': 90, + 'description': 'Annual expansion of Northwind Cloud platform seats', + 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-06-10T14:00:00Z'}, + ], + 'tickets': [], + 'tasks': [ + {'id': 'task1', 'title': 'Pull Spring Nurture 2026 performance report', 'type': 'to_do', + 'status': 'not_started', 'priority': 'high', 'dueDate': '2026-07-02T17:00:00Z', + 'notes': 'Copy metrics into Campaign Reports 2026 sheet and notify stakeholders', + 'owner': 'Admin User', 'contactId': 'c1', 'companyId': 'comp1', 'dealId': 'd1', + 'createDate': '2026-07-01T08:00:00Z', 'completedDate': None}, + ], + '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': '#E6FFTA', 'order': 4}, + 'closed': {'id': 'closed', 'label': 'Closed', 'color': '#E6FFEC', 'order': 5}, + }, + 'appState': { + 'sidebarOpen': True, + 'currentUser': {'name': 'Campaign Manager', 'email': 'campaign.mgr@northwindcloud.com', 'avatar': None}, + }, + # Custom campaign performance report — the canonical source figures + 'campaignReports': [ + { + 'id': 'cr_spring_nurture_2026', + 'name': 'Spring Nurture 2026', + 'mql': MQLS, + 'openRate': 38.4, + 'conversionRate': 4.9, + 'source': 'HubSpot', + 'period': '2026-04-01 to 2026-06-30', + } + ], + } + + +def build_sheets_state(): + """Google Sheets: workbook 'Campaign Reports 2026', sheet 'Performance'. + Row 2 header; Row 3 = 'Spring Nurture 2026' with B3/C3/D3/E3 EMPTY (agent fills them).""" + return { + 'id': 'workbook_campaign_reports_2026', + 'title': 'Campaign Reports 2026', + 'activeSheetId': 'sheet_performance', + 'selectedCell': 'A1', + 'selectionRange': None, + 'clipboard': None, + 'isDragging': False, + 'undoStack': [], + 'redoStack': [], + 'namedRanges': [], + 'conditionalFormats': [], + 'charts': [], + 'showGridlines': True, + 'showFormulas': False, + 'zoom': 100, + 'sheets': [ + { + 'id': 'sheet_performance', + 'name': 'Performance', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 2, + 'frozenCols': 0, + 'tabColor': '#1A73E8', + 'isHidden': False, + 'columnWidths': {'0': 200, '1': 100, '2': 120, '3': 160, '4': 120}, + 'data': { + # Row 2 = header + 'A2': {'value': 'Campaign', 'formula': 'Campaign', 'style': {'bold': True, 'bg': '#E8EAED', 'align': 'center'}}, + 'B2': {'value': 'MQLs', 'formula': 'MQLs', 'style': {'bold': True, 'bg': '#E8EAED', 'align': 'center'}}, + 'C2': {'value': 'Open Rate', 'formula': 'Open Rate', 'style': {'bold': True, 'bg': '#E8EAED', 'align': 'center'}}, + 'D2': {'value': 'Conversion Rate', 'formula': 'Conversion Rate', 'style': {'bold': True, 'bg': '#E8EAED', 'align': 'center'}}, + 'E2': {'value': 'Source', 'formula': 'Source', 'style': {'bold': True, 'bg': '#E8EAED', 'align': 'center'}}, + # Row 3 = Spring Nurture 2026 (B3/C3/D3/E3 EMPTY — to be filled by agent) + 'A3': {'value': CAMPAIGN_NAME, 'formula': CAMPAIGN_NAME}, + 'B3': {'value': '', 'formula': ''}, + 'C3': {'value': '', 'formula': ''}, + 'D3': {'value': '', 'formula': ''}, + 'E3': {'value': '', 'formula': ''}, + # Row 4 = another campaign (already filled, must stay unchanged) + 'A4': {'value': 'Winter Launch 2025', 'formula': 'Winter Launch 2025'}, + 'B4': {'value': '268', 'formula': '268', 'format': 'number'}, + 'C4': {'value': '33.1%', 'formula': '33.1%', 'format': 'percent'}, + 'D4': {'value': '3.7%', 'formula': '3.7%', 'format': 'percent'}, + 'E4': {'value': 'HubSpot', 'formula': 'HubSpot'}, + # Row 5 = another campaign (already filled) + 'A5': {'value': 'Summer Webinar 2025', 'formula': 'Summer Webinar 2025'}, + 'B5': {'value': '199', 'formula': '199', 'format': 'number'}, + 'C5': {'value': '41.2%', 'formula': '41.2%', 'format': 'percent'}, + 'D5': {'value': '5.4%', 'formula': '5.4%', 'format': 'percent'}, + 'E5': {'value': 'Marketo', 'formula': 'Marketo'}, + }, + }, + { + 'id': 'sheet_notes', + 'name': 'Notes', + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 0, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {'0': 300}, + 'data': { + 'A1': {'value': 'Data Source', 'formula': 'Data Source', 'style': {'bold': True}}, + 'A2': {'value': 'HubSpot Campaign Performance reports', 'formula': 'HubSpot Campaign Performance reports'}, + 'A3': {'value': 'Review Date', 'formula': 'Review Date', 'style': {'bold': True}}, + 'A4': {'value': '2026-07-02', 'formula': '2026-07-02'}, + }, + }, + ], + } + + +def build_airtable_state(): + """Airtable: base 'Campaign Ops', table 'Campaigns'. + Record 'Spring Nurture 2026' has Status='Live' (agent changes to 'Reported').""" + return { + 'currentUser': { + 'id': 'user_1', 'name': 'Campaign Manager', 'email': 'campaign.mgr@northwindcloud.com', + 'avatar': 'https://ui-avatars.com/api/?name=Campaign+Manager&background=8B5CF6&color=fff', + }, + 'collaborators': [ + {'id': 'user_1', 'name': 'Campaign Manager', 'email': 'campaign.mgr@northwindcloud.com', + 'avatar': 'https://ui-avatars.com/api/?name=Campaign+Manager&background=8B5CF6&color=fff'}, + {'id': 'user_2', 'name': 'Marcus Johnson', 'email': 'marcus.johnson@northwindcloud.com', + 'avatar': 'https://ui-avatars.com/api/?name=Marcus+Johnson&background=EC4899&color=fff'}, + ], + 'bases': { + 'base_campaign_ops': { + 'id': 'base_campaign_ops', 'name': 'Campaign Ops', 'color': 'bg-teal-600', + 'tables': ['tbl_campaigns'], + } + }, + 'tables': { + 'tbl_campaigns': { + 'id': 'tbl_campaigns', + 'name': 'Campaigns', + 'baseId': 'base_campaign_ops', + 'fields': [ + {'id': 'fld_campaign', 'name': 'Campaign', 'type': 'text', 'primary': True}, + {'id': 'fld_status', 'name': 'Status', 'type': 'single_select', 'options': [ + {'id': 'status_live', 'name': 'Live', 'color': 'bg-[#FFEAB6] text-[#8D6302]'}, + {'id': 'status_reported', 'name': 'Reported', 'color': 'bg-[#D1F7C4] text-[#2D7514]'}, + {'id': 'status_draft', 'name': 'Draft', 'color': 'bg-[#E5F4FF] text-[#1A56B0]'}, + ]}, + {'id': 'fld_channel', 'name': 'Channel', 'type': 'text'}, + {'id': 'fld_budget', 'name': 'Budget', 'type': 'currency'}, + ], + 'records': [ + { + 'id': 'rec_spring_nurture_2026', + 'createdTime': '2026-04-01T09:00:00.000Z', + 'fields': { + 'fld_campaign': CAMPAIGN_NAME, + 'fld_status': 'Live', + 'fld_channel': 'Email Nurture', + 'fld_budget': 24000, + }, + }, + { + 'id': 'rec_winter_launch_2025', + 'createdTime': '2025-12-01T09:00:00.000Z', + 'fields': { + 'fld_campaign': 'Winter Launch 2025', + 'fld_status': 'Reported', + 'fld_channel': 'Email + Paid', + 'fld_budget': 31000, + }, + }, + { + 'id': 'rec_summer_webinar_2025', + 'createdTime': '2025-08-01T09:00:00.000Z', + 'fields': { + 'fld_campaign': 'Summer Webinar 2025', + 'fld_status': 'Draft', + 'fld_channel': 'Webinar', + 'fld_budget': 12000, + }, + }, + ], + 'views': [ + {'id': 'view_campaign_grid', 'name': 'Grid View', 'type': 'grid', 'filters': [], 'sorts': [], + 'groupBy': [], 'hiddenFieldIds': [], 'fieldWidths': {}, 'rowHeight': 'short'}, + ], + 'activeViewId': 'view_campaign_grid', + } + }, + 'activeBaseId': 'base_campaign_ops', + 'activeTableId': 'tbl_campaigns', + 'ui': {'viewSidebarOpen': False, 'expandedRecordId': None, 'searchQuery': '', 'isSearching': False}, + } + + +def build_slack_state(): + """Slack: workspace 'Northwind Cloud' with #campaign-reporting (empty of the report message).""" + return { + 'currentUser': { + 'userId': 'user_1', 'fullName': 'Campaign Manager', 'displayName': 'Campaign Manager', + 'email': 'campaign.mgr@northwindcloud.com', 'avatar': 'https://picsum.photos/200/200?random=1', + 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago', + }, + 'workspace': {'workspaceId': 'ws_northwind', 'workspaceName': 'Northwind Cloud', 'icon': ''}, + 'users': [ + {'userId': 'user_1', 'fullName': 'Campaign Manager', 'displayName': 'Campaign Manager', + 'email': 'campaign.mgr@northwindcloud.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'status': 'online'}, + {'userId': 'user_2', 'fullName': 'Marcus Johnson', 'displayName': 'Marcus', + 'email': 'marcus.johnson@northwindcloud.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'status': 'online'}, + {'userId': 'user_3', 'fullName': 'CMO Office', 'displayName': 'CMO', + 'email': 'cmo@northwindcloud.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'status': 'away'}, + ], + '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': '2026-01-01T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'campaign-reporting', 'name': 'campaign-reporting', 'description': 'Campaign performance reporting', + 'topic': 'Post campaign performance summaries here', 'isPrivate': False, 'isStarred': True, + 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_1', 'createdAt': '2026-02-01T10:00:00Z', + 'pinnedMessages': [], 'unreadCount': 0}, + {'channelId': 'marketing', 'name': 'marketing', 'description': 'Marketing team chat', 'topic': '', + 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2'], 'createdBy': 'user_1', + 'createdAt': '2026-01-15T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0}, + ], + 'messages': { + 'general': [ + {'messageId': 'msg_gen_1', 'senderId': 'user_2', 'content': 'Morning all — Q3 planning starts Thursday.', + 'timestamp': '2026-07-01T13:00:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}, + ], + 'campaign-reporting': [], + 'marketing': [ + {'messageId': 'msg_mkt_1', 'senderId': 'user_1', 'content': 'Spring Nurture 2026 wrapped up last week.', + 'timestamp': '2026-06-30T16: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': [], + } + + +def build_gmail_state(): + """Gmail: logged in as the campaign manager; no sent email to cmo yet.""" + return { + 'user': { + 'userId': 'u1', 'username': 'Campaign Manager', 'email': 'campaign.mgr@northwindcloud.com', + 'avatar': 'https://picsum.photos/200/200?random=10', + }, + 'emails': [ + { + 'id': 'email_1', 'threadId': 'thread_1', + 'from': {'name': 'Marcus Johnson', 'email': 'marcus.johnson@northwindcloud.com'}, + 'to': [{'name': 'Campaign Manager', 'email': 'campaign.mgr@northwindcloud.com'}], + 'subject': 'Re: Q3 campaign calendar', + 'body': '

Thanks — please make sure the Spring Nurture wrap-up is summarized for the CMO.

', + 'timestamp': '2026-07-01T15:20:00Z', 'read': False, 'starred': False, 'important': True, + 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox', 'attachments': [], + }, + { + 'id': 'email_2', 'threadId': 'thread_2', + 'from': {'name': 'HubSpot Notifications', 'email': 'noreply@hubspot.com'}, + 'to': [{'name': 'Campaign Manager', 'email': 'campaign.mgr@northwindcloud.com'}], + 'subject': 'Your Spring Nurture 2026 report is ready', + 'body': '

The campaign performance report for Spring Nurture 2026 is now available.

', + 'timestamp': '2026-06-30T12:00:00Z', 'read': True, 'starred': False, 'important': False, + 'labels': ['l3'], 'category': 'promotions', 'folder': 'inbox', 'attachments': [], + }, + ], + 'labels': [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'l3', 'name': 'Campaigns', 'color': '#22c55e'}, + ], + 'drafts': [], + } + + +def launch_gui(command, delay_sec=1.0): + env = os.environ.copy() + env['DISPLAY'] = ':0' + try: + subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + except Exception as e: + print(f'WARN: launch_gui failed for {command!r}: {e}') + time.sleep(delay_sec) + + +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() + + +def main(): + sid = SID + with open('/tmp/task_web_sid', 'w') as f: + f.write(sid) + print(f'sid = {sid}') + + states = { + 'hubspot': build_hubspot_state(), + 'sheets': build_sheets_state(), + 'airtable': build_airtable_state(), + 'slack': build_slack_state(), + 'gmail': build_gmail_state(), + } + + for name, state in states.items(): + url = MOCKS[name] + resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30) + assert resp.status_code == 200, f'{name}: set failed: {resp.text}' + print(f'Injected initial (blank) state -> {name} ({url})') + + # Verify initial_state persisted on each server + for name in states: + url = MOCKS[name] + go = requests.get(f'{url}/go?sid={sid}', timeout=10).json() + assert go.get('initial_state') is not None, f'{name}: initial_state missing after injection' + # Sanity: on the initial VM, current_state must equal initial_state (both blank) + cs = go.get('current_state') + assert cs is not None, f'{name}: current_state missing on initial VM' + print('Verified: all 5 mocks have initial_state AND current_state set (both blank on initial VM)') + + # Marker file recording the canonical ground-truth (initial) values + marker = { + 'task_id': TASK_ID, + 'sid': sid, + 'mocks': MOCKS, + 'source_metrics': {'campaign': CAMPAIGN_NAME, 'mql': MQLS, 'open_rate': OPEN_RATE, 'conversion_rate': CONVERSION_RATE}, + 'recipient': RECIPIENT, + 'initial': { + 'sheets_B3': '', 'sheets_C3': '', 'sheets_D3': '', 'sheets_E3': '', + 'airtable_spring_status': 'Live', + 'slack_campaign_reporting_messages': 0, + 'gmail_sent_to_cmoo': 0, + }, + 'golden': { + 'sheets_B3': 312, 'sheets_C3': '38.4%', 'sheets_D3': '4.9%', 'sheets_E3': 'HubSpot', + 'airtable_spring_status': 'Reported', + 'slack_campaign_reporting_messages': 1, + 'gmail_sent_to_cmoo': 1, + }, + } + with open(f'{WORKDIR}/{TASK_ID}.json', 'w') as f: + json.dump(marker, f, indent=2) + print(f'Marker file written: {WORKDIR}/{TASK_ID}.json') + + # Launch a Chrome window for EVERY mock + for name, url in MOCKS.items(): + launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.4) + + 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_perf_report_005/reward.py b/mktg_perf_report_005/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..058fffd63366292f15bf93d2fe5a6476e5676744 --- /dev/null +++ b/mktg_perf_report_005/reward.py @@ -0,0 +1,241 @@ +""" +Reward Script: prof16_perf_report_002 — Spring Nurture 2026 performance report pipeline +Task ID: mktg_perf_report_005 +Domain: mock_websites (multi-mock: Google Sheets, Airtable, Slack, Gmail) +Scoring: 5 deterministic components (0.30 + 0.20 + 0.20 + 0.15 + 0.15 = 1.0). + Each component verifies a task-introduced change. The initial VM's sid holds the + blank initial state; the golden VM's sid holds the full golden end state. Because + each environment uses a DISTINCT sid, the reward script naturally scores 0.0 on + initial_env and 1.0 on golden_env. +""" +import json +import re +import sys + +import requests + +# --- Mock URLs (from task_config.json task_instruction) --- +MOCKS = { + 'sheets': 'http://28.7.184.198:8145', # Google Sheets + 'airtable': 'http://28.7.184.198:8109', # Airtable + 'slack': 'http://28.7.184.198:8178', # Slack + 'gmail': 'http://28.7.184.198:8138', # Gmail +} + +# Ground-truth expected values (from task_config.json context / task_instruction) +EXPECTED = { + 'sheets': { + 'B3': 312, + 'C3': '38.4%', + 'D3': '4.9%', + 'E3': 'HubSpot', + }, + 'airtable_status': 'Reported', + 'slack_message': ('Spring Nurture 2026 performance — MQLs: 312, Open Rate: 38.4%, ' + 'Conversion: 4.9% (source: HubSpot). Logged to Campaign Reports 2026 sheet.'), + 'gmail_to': 'cmo@northwindcloud.com', + 'gmail_subject': 'Spring Nurture 2026 — Performance Summary', + 'gmail_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.'), +} + + +# --- Helpers (template-mandated boilerplate) --- +def _comp(idx, name, weight, passed, score, detail="", description=""): + """Emit a structured COMPONENT line for per-module scoring visibility.""" + print("COMPONENT: " + json.dumps({ + "id": idx, + "name": name, + "weight": float(weight), + "passed": bool(passed), + "score": float(score), + "detail": detail, + "description": description, + })) + + +def _run_component(idx, name, weight, fn, args): + """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail).""" + try: + passed, score, detail = fn(*args) + except Exception as e: + passed, score, detail = False, 0.0, f'error: {e}' + status = 'PASS' if passed else 'FAIL' + suffix = f' ({weight} pts)' if passed else f' — {detail}' + print(f'{status}: Component {idx} — {name}{suffix}') + _comp(idx, name, weight, passed, score, detail, + description=(fn.__doc__ or '').strip()) + return passed, score, detail + + +def contains_parts(text, parts): + """Match normalized text fragments in order, ignoring characters between them.""" + normalized = re.sub(r'\s+', ' ', str(text)).strip().lower() + pos = 0 + for part in parts: + part_norm = re.sub(r'\s+', ' ', part).strip().lower() + found = normalized.find(part_norm, pos) + if found < 0: + return False + pos = found + len(part_norm) + return True + + +# --- State fetch --- +def fetch_states(): + """Read sid and fetch current_state for all 4 mocks. Returns dict of current_state.""" + 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) + + states = {} + for name, url in MOCKS.items(): + try: + resp = requests.get(f'{url}/go?sid={sid}', timeout=15) + resp.raise_for_status() + data = resp.json() + cur = data.get('current_state') + if cur is None: + print(f'CRITICAL: current_state is None for {name} (sid={sid})') + print('REWARD: 0.0') + sys.exit(0) + states[name] = cur + except Exception as e: + print(f'CRITICAL: Cannot fetch state from {name} ({url}/go?sid={sid}): {e}') + print('REWARD: 0.0') + sys.exit(0) + return states + + +# --- Per-component checks (one function per sub-objective) --- + +def check_component_1(states): + """Google Sheets 'Performance' row 3 has B3=312, C3='38.4%', D3='4.9%', E3='HubSpot'. + Pass condition: all four cells in row 3 equal the expected ground-truth values exactly. + """ + cur = states['sheets'] + perf = next((s for s in cur.get('sheets', []) if s.get('name') == 'Performance'), None) + if perf is None: + return False, 0.0, 'Performance sheet not found' + data = perf.get('data', {}) + exp = EXPECTED['sheets'] + mismatches = [] + for col, exp_val in exp.items(): + cell = data.get(col, {}) + actual = cell.get('value') if isinstance(cell, dict) else cell + # Normalize: sheet stores int 312; compare with type-flexible equality + if str(actual) != str(exp_val): + mismatches.append(f'{col}={actual!r} (expected {exp_val!r})') + if mismatches: + return False, 0.0, '; '.join(mismatches) + return True, 0.30, 'B3=312, C3=38.4%, D3=4.9%, E3=HubSpot all match' + + +def check_component_2(states): + """Airtable 'Campaigns' record 'Spring Nurture 2026' has Status field = 'Reported'. + Pass condition: the Spring Nurture 2026 record's status field equals 'Reported'. + """ + cur = states['airtable'] + tables = cur.get('tables', {}) + for tid, t in tables.items(): + if t.get('name') == 'Campaigns': + for r in t.get('records', []): + flds = r.get('fields', {}) + campaign = flds.get('fld_campaign', flds.get('Campaign', '')) + if 'Spring Nurture' in str(campaign): + status = flds.get('fld_status', flds.get('Status', '')) + if str(status) == EXPECTED['airtable_status']: + return True, 0.20, f"status='{status}'" + return False, 0.0, f"status='{status}' (expected 'Reported')" + return False, 0.0, 'Spring Nurture 2026 record not found in Campaigns table' + + +def check_component_3(states): + """Slack #campaign-reporting contains exactly one message with the required text fragments. + Pass condition: exactly one message contains both sides of the expected dash in order. + """ + cur = states['slack'] + msgs = cur.get('messages', {}).get('campaign-reporting', []) + if len(msgs) != 1: + return False, 0.0, f'expected exactly 1 message, found {len(msgs)}' + content = msgs[0].get('content', '') + parts = EXPECTED['slack_message'].split(' — ') + if contains_parts(content, parts): + return True, 0.20, 'exactly one message with all required text fragments' + return False, 0.0, f'content mismatch: {content[:80]!r}...' + + +def check_component_4(states): + """Gmail has one sent message to cmo@northwindcloud.com with the required subject fragments. + Pass condition: exactly one sent email has both sides of the expected subject dash in order. + """ + cur = states['gmail'] + emails = cur.get('emails', []) + sent = [e for e in emails if e.get('folder') == 'sent' or 'SENT' in (e.get('labels') or [])] + if not sent: + # Fall back: any email whose recipient is the CMO + sent = [e for e in emails if any( + (r.get('email') == EXPECTED['gmail_to']) for r in (e.get('to') or []))] + subject_parts = EXPECTED['gmail_subject'].split(' — ') + matches = [e for e in sent if any( + (r.get('email') == EXPECTED['gmail_to']) for r in (e.get('to') or [])) + and contains_parts(e.get('subject', ''), subject_parts)] + if len(matches) == 1: + return True, 0.15, f"1 sent email to {EXPECTED['gmail_to']} with required subject fragments" + return False, 0.0, f'expected exactly 1 matching sent email, found {len(matches)}' + + +def check_component_5(states): + """Gmail sent message to cmo@northwindcloud.com has the required body text fragments. + Pass condition: the matching email body contains both sides of the expected dash in order. + """ + cur = states['gmail'] + emails = cur.get('emails', []) + sent = [e for e in emails if e.get('folder') == 'sent' or 'SENT' in (e.get('labels') or [])] + if not sent: + sent = [e for e in emails if any( + (r.get('email') == EXPECTED['gmail_to']) for r in (e.get('to') or []))] + subject_parts = EXPECTED['gmail_subject'].split(' — ') + matches = [e for e in sent if any( + (r.get('email') == EXPECTED['gmail_to']) for r in (e.get('to') or [])) + and contains_parts(e.get('subject', ''), subject_parts)] + if not matches: + return False, 0.0, 'no matching sent email to verify body' + body = matches[0].get('body', '') + # Defensive: strip any HTML tags (golden stores plain text, but guard against

wrapping) + norm = re.sub(r'<[^>]+>', '', body).strip() + exp_norm = re.sub(r'<[^>]+>', '', EXPECTED['gmail_body']).strip() + if contains_parts(norm, exp_norm.split(' — ')): + return True, 0.15, 'body contains all required text fragments' + return False, 0.0, f'body mismatch: {body[:80]!r}...' + + +def verify_task(): + """Verify task completion with progressive scoring. Returns float 0.0-1.0.""" + states = fetch_states() + total_score = 0.0 + for idx, name, weight, fn, args in [ + (1, 'Google Sheets row 3 values', 0.30, check_component_1, (states,)), + (2, 'Airtable Status = Reported', 0.20, check_component_2, (states,)), + (3, 'Slack campaign-reporting message', 0.20, check_component_3, (states,)), + (4, 'Gmail sent subject', 0.15, check_component_4, (states,)), + (5, 'Gmail sent body', 0.15, check_component_5, (states,)), + ]: + _, 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_perf_report_005/reward_label.json b/mktg_perf_report_005/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..8fe4cb539f96e324c268f4751147fa623856fb11 --- /dev/null +++ b/mktg_perf_report_005/reward_label.json @@ -0,0 +1,72 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof16_perf_report_002/reward.py", + "api_url": "http://28.7.184.184:8000/v1/chat/completions", + "model": "Kimi-K2.6", + "max_code_chars": 100000, + "created_at": "2026-07-14 10:29:02", + "label": { + "task_id": "mktg_perf_report_005", + "domain": "mock_websites", + "summary": "验证在 Google Sheets、Airtable、Slack 和 Gmail 四个 mock 服务中是否正确完成了 Spring Nurture 2026 绩效报告流程的各项数据录入与通知操作", + "is_placeholder": false, + "data_sources": [ + "/tmp/task_web_sid", + "sheets_mock", + "airtable_mock", + "slack_mock", + "gmail_mock" + ], + "scoring_components": [ + { + "name": "Component 1", + "weight": 0.3, + "description": "检查 Google Sheets 的 Performance 工作表第3行四个单元格是否与预期值完全匹配", + "check_logic": "从 states['sheets'] 中查找 name 为 'Performance' 的 sheet,获取其 data 字段,对 B3、C3、D3、E3 分别与 EXPECTED['sheets'] 中的期望值进行 str(actual) != str(exp_val) 的字符串精确比较", + "pass_condition": "Performance 工作表存在,且 B3=312、C3='38.4%'、D3='4.9%'、E3='HubSpot' 全部精确匹配" + }, + { + "name": "Component 2", + "weight": 0.2, + "description": "检查 Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported", + "check_logic": "遍历 states['airtable']['tables'],找到 name 为 'Campaigns' 的表,再遍历其 records,查找 fields 中 fld_campaign 或 Campaign 包含 'Spring Nurture' 的记录,检查其 fld_status 或 Status 是否精确等于 EXPECTED['airtable_status']", + "pass_condition": "找到 Spring Nurture 2026 记录,且其 Status 字段精确等于 'Reported'" + }, + { + "name": "Component 3", + "weight": 0.2, + "description": "检查 Slack #campaign-reporting 频道是否恰好包含一条内容完全匹配的消息", + "check_logic": "检查 states['slack']['messages']['campaign-reporting'] 列表长度是否为 1,且唯一消息的 content 字段精确等于 EXPECTED['slack_message']", + "pass_condition": "campaign-reporting 频道恰好有 1 条消息,且内容完全匹配预期字符串" + }, + { + "name": "Component 4", + "weight": 0.15, + "description": "检查 Gmail 是否有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件", + "check_logic": "从 states['gmail']['emails'] 中优先筛选 folder 为 'sent' 或 labels 包含 'SENT' 的邮件;若 sent 为空则回退到筛选 to 中包含 EXPECTED['gmail_to'] 的邮件;再从中筛选 to 中包含该地址且 subject 精确等于 EXPECTED['gmail_subject'] 的邮件,检查匹配数量是否恰好为 1", + "pass_condition": "恰好存在 1 封发送给 cmo@northwindcloud.com 且主题为 'Spring Nurture 2026 — Performance Summary' 的邮件" + }, + { + "name": "Component 5", + "weight": 0.15, + "description": "检查 Gmail 发送给 cmo@northwindcloud.com 的匹配邮件正文是否完全匹配预期文本", + "check_logic": "使用与 Component 4 相同的逻辑定位匹配邮件,获取其 body 字段,通过 re.sub(r'<[^>]+>', '', body).strip() 去除 HTML 标签并 strip 后,与同样处理后的 EXPECTED['gmail_body'] 进行精确比较", + "pass_condition": "找到匹配邮件,且其正文去除 HTML 标签并 strip 后精确等于预期正文" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数", + "failure_modes": [ + "无法从 /tmp/task_web_sid 读取 sid 或 sid 为空:打印 CRITICAL 并 sys.exit(0),REWARD 为 0.0", + "从任一 mock 服务拉取状态失败或返回 current_state 为 None:打印 CRITICAL 并 sys.exit(0),REWARD 为 0.0", + "Google Sheets 中 Performance 工作表不存在或四个单元格任一不匹配:该组件得 0.0", + "Airtable 中未找到 Spring Nurture 2026 记录或 Status 不等于 Reported:该组件得 0.0", + "Slack #campaign-reporting 频道消息数量不为 1 或内容不匹配:该组件得 0.0", + "Gmail 中未找到恰好 1 封匹配 sent 邮件(主题或收件人不匹配):Component 4 得 0.0", + "Gmail 匹配邮件正文去除 HTML 后不匹配:Component 5 得 0.0", + "组件函数执行异常:捕获后该组件得 0.0" + ], + "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败或为空则直接退出并返回 0.0。随后使用 sid 向 Google Sheets、Airtable、Slack、Gmail 四个 mock 服务的 /go?sid={sid} 端点拉取 current_state,任一服务拉取失败或返回 current_state 为 None 则直接退出并返回 0.0。接着按顺序执行 5 个确定性精确匹配检查:1) Google Sheets 的 Performance 工作表第3行四个单元格(B3、C3、D3、E3)是否与预期值完全匹配;2) Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported;3) Slack #campaign-reporting 频道是否恰好有一条内容完全匹配的消息;4) Gmail 是否恰好有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件(优先查找 sent 文件夹,若无则回退到收件人为 CMO 的任意邮件);5) 该邮件正文去除 HTML 标签后是否与预期正文完全匹配。每个组件通过则累加其权重分值,失败则计 0 分但不中断后续检查。最终总分为各组件得分之和,经 min(总分, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不包含任何额外文本、Markdown 代码块标记或思考过程。\n\n让我仔细阅读源码并提取所需信息:\n\n1. **task_id**: 从 docstring 中提取,明确写了 `Task ID: prof16_perf_report_002`\n2. **domain**: 从 docstring 中提取,明确写了 `Domain: mock_websites (multi-mock: Google Sheets, Airtable, Slack, Gmail)`\n3. **summary**: 一句话概括。这个脚本验证在多个 mock 服务(Google Sheets、Airtable、Slack、Gmail)中是否正确完成了 Spring Nurture 2026 绩效报告流程。\n4. **is_placeholder**: false。这个脚本有完整的检查逻辑,不是占位脚本。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `sheets` mock: `http://28.7.186.212:8165`\n - `airtable` mock: `http://28.7.186.212:8129`\n - `slack` mock: `http://28.7.186.212:8198`\n - `gmail` mock: `http://28.7.186.212:8158`\n6. **scoring_components**: 有5个组件,权重分别是 0.30, 0.20, 0.20, 0.15, 0.15。\n\n让我详细分析每个组件:\n\n**Component 1**: \n- name: Google Sheets row 3 values\n- weight: 0.30\n- description: 检查 Google Sheets 的 Performance 工作表第3行是否正确填写了 B3=312, C3=38.4%, D3=4.9%, E3=HubSpot\n- check_logic: 从 states['sheets'] 中找到 name 为 'Performance' 的 sheet,检查 data 中 B3, C3, D3, E3 的值是否与 EXPECTED['sheets'] 中的期望值完全匹配(使用 str(actual) != str(exp_val) 进行类型灵活的字符串比较)\n- pass_condition: Performance 工作表存在,且 B3=312, C3='38.4%', D3='4.9%', E3='HubSpot' 全部匹配\n\n**Component 2**:\n- name: Airtable Status = Reported\n- weight: 0.20\n- description: 检查 Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 'Reported'\n- check_logic: 遍历 states['airtable'] 中的 tables,找到 name 为 'Campaigns' 的表,再遍历 records,查找 fields 中 fld_campaign 或 Campaign 包含 'Spring Nurture' 的记录,检查其 fld_status 或 Status 是否等于 'Reported'\n- pass_condition: 找到 Spring Nurture 2026 记录且其 Status 字段精确等于 'Reported'\n\n**Component 3**:\n- name: Slack campaign-reporting message\n- weight: 0.20\n- description: 检查 Slack #campaign-reporting 频道是否包含且仅包含一条完全匹配预期文本的消息\n- check_logic: 检查 states['slack']['messages']['campaign-reporting'] 的长度是否为 1,且唯一消息的 content 完全等于 EXPECTED['slack_message']\n- pass_condition: campaign-reporting 频道恰好有 1 条消息,且内容完全匹配预期字符串\n\n**Component 4**:\n- name: Gmail sent subject\n- weight: 0.15\n- description: 检查 Gmail 是否有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件\n- check_logic: 从 states['gmail']['emails'] 中筛选 folder 为 'sent' 或 labels 包含 'SENT' 的邮件;如果没有则回退到查找 to 中包含 cmo@northwindcloud.com 的邮件;再筛选 to 中包含 cmo@northwindcloud.com 且 subject 等于 EXPECTED['gmail_subject'] 的邮件;检查匹配数量是否恰好为 1\n- pass_condition: 恰好存在 1 封发送给 cmo@northwindcloud.com 且主题完全为 'Spring Nurture 2026 — Performance Summary' 的邮件\n\n**Component 5**:\n- name: Gmail sent body\n- weight: 0.15\n- description: 检查 Gmail 发送给 cmo@northwindcloud.com 的匹配邮件正文是否完全匹配预期文本\n- check_logic: 使用与 Component 4 相同的逻辑找到匹配邮件,然后获取其 body,去除 HTML 标签并 strip 后与去除 HTML 标签并 strip 后的 EXPECTED['gmail_body'] 比较\n- pass_condition: 找到匹配邮件,且其正文(去除 HTML 标签后)精确等于预期正文\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到4位小数\n9. **failure_modes**:\n - 无法从 /tmp/task_web_sid 读取 sid 或 sid 为空:打印 CRITICAL 并 sys.exit(0) 返回 0.0\n - 从任一 mock 服务获取 current_state 失败或 current_state 为 None:打印 CRITICAL 并 sys.exit(0) 返回 0.0\n - 各组件检查失败返回 0.0 分(但脚本不会提前退出,会继续检查其他组件)\n - 组件函数执行异常:捕获为 error,该组件得 0.0\n\n10. **scoring_logic_explanation**: 按执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接退出并返回 0.0\n - 使用 sid 分别向 4 个 mock 服务(Google Sheets、Airtable、Slack、Gmail)的 /go?sid={sid} 端点请求当前状态,任一失败或返回 current_state 为 None 则直接退出并返回 0.0\n - 依次执行 5 个确定性精确匹配组件检查:\n 1. Google Sheets Performance 工作表第3行四个单元格精确匹配\n 2. Airtable Campaigns 表中 Spring Nurture 2026 记录状态为 Reported\n 3. Slack #campaign-reporting 频道恰好一条消息且内容精确匹配\n 4. Gmail 恰好一封发送给 CMO 且主题精确匹配的邮件\n 5. Gmail 该邮件正文(去 HTML 后)精确匹配\n - 每个组件通过则累加对应权重分数,失败则加 0\n - 最终总分用 min(总分, 1.0) 钳制并四舍五入到4位小数输出\n\n11. **confidence**: 1.0(源码完整清晰,逻辑明确)\n\n现在构造 JSON。注意:\n- 不要输出 Markdown 代码块\n- 第一个字符必须是 {,最后一个必须是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- 不要输出额外解释\n\n让我再检查一下 docstring 中的 domain:`mock_websites (multi-mock: Google Sheets, Airtable, Slack, Gmail)`。按照要求,domain 填 `mock_websites`。\n\n检查 weight 字段:代码中显式给出了 0.30, 0.20, 0.20, 0.15, 0.15。\n\n检查 failure_modes:需要列出会导致提前退出、返回 0.0 或扣分的异常路径。\n- 读取 sid 失败/为空:提前退出,REWARD 0.0\n- mock 状态拉取失败或 current_state 为 None:提前退出,REWARD 0.0\n- 各组件不匹配:扣分(该组件 0 分)\n- Slack 消息数量不为 1:扣分\n- Gmail 匹配邮件数量不为 1:扣分\n\n检查 scoring_logic_explanation 是否需要包含 \"按执行顺序说明脚本如何读取状态、逐项检查、汇总得分\"。是的,我已经在思考中组织了。\n\n确保 JSON 格式正确,没有 trailing comma。\n\n让我再仔细看看 check_component_4 和 check_component_5 的 fallback 逻辑:\n```python\nsent = [e for e in emails if e.get('folder') == 'sent' or 'SENT' in (e.get('labels') or [])]\nif not sent:\n # Fall back: any email whose recipient is the CMO\n sent = [e for e in emails if any(\n (r.get('email') == EXPECTED['gmail_to']) for r in (e.get('to') or []))]\n```\n这是一个 fallback,如果 sent 文件夹为空,则查找任何收件人为 CMO 的邮件。这应该在 check_logic 中体现。\n\nComponent 4 pass_condition: 恰好存在 1 封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件(优先从 sent 文件夹查找,sent 为空时回退到任意收件人为 CMO 的邮件)。\n\nComponent 5 pass_condition: 找到上述匹配邮件,且其正文(去除 HTML 标签并 strip 后)精确等于预期正文。\n\n好的,开始写 JSON。\n\n注意:JSON 中不能有注释。字符串中的换行需要正确处理。在 Python 字符串中我可以使用 \\n 或者多行字符串,但 JSON 标准不允许真正的多行字符串(除非转义 \\n)。不过 Python 的 json.dumps 会处理,但我这里是手动构造文本。我应该使用 \\n 来表示换行,或者直接在字符串中写换行(但这样不是标准 JSON,虽然很多解析器支持)。为了安全,我应该在字符串中使用实际的换行符(因为用户要求输出 JSON 对象,且没有说必须是一行)。实际上标准 JSON 字符串可以包含换行符,只要它们被转义为 \\n。但在 Python 代码块中生成时,我可以直接写多行字符串,因为最终输出是文本。\n\n等等,用户说 \"只输出一个 JSON 对象,不要输出 Markdown 代码块标记\"。所以我应该输出原始 JSON 文本。在 JSON 中,字符串值不能包含未转义的控制字符(如真正的换行符),必须写成 \\n。但通常为了可读性,很多输出会包含真正的换行符在字符串外,而字符串内用 \\n。我需要确保生成的是合法的 JSON。\n\n让我用 \\n 来表示换行。\n\n再检查一下 `data_sources` 字段。应该列出脚本从哪些数据源获取状态。\n- `/tmp/task_web_sid`\n- `sheets_mock` (http://28.7.186.212:8165)\n- `airtable_mock` (http://28.7.186.212:8129)\n- `slack_mock` (http://28.7.186.212:8198)\n- `gmail_mock` (http://28.7.186.212:8158)\n\n或者简单写 `sheets_mock`、`airtable_mock`、`slack_mock`、`gmail_mock`。源码中 MOCKS 字典的键是这些。我会写 `sheets_mock`、`airtable_mock`、`slack_mock`、`gmail_mock`,并加上 `/tmp/task_web_sid`。\n\n再检查 `summary`:一句话概括。可以写:\"验证在 Google Sheets、Airtable、Slack 和 Gmail 四个 mock 服务中是否正确完成了 Spring Nurture 2026 绩效报告流程的各项数据录入与通知操作。\"\n\n再检查 `is_placeholder`:false。\n\n再检查 `score_aggregation`:各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限 1.0,并四舍五入到4位小数。\n\n再检查 `scoring_logic_explanation`:\n\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败或为空则直接退出并返回 0.0。随后使用 sid 向 Google Sheets、Airtable、Slack、Gmail 四个 mock 服务的 /go?sid={sid} 端点拉取 current_state,任一服务拉取失败或返回 current_state 为 None 则直接退出并返回 0.0。接着按顺序执行 5 个确定性精确匹配检查:1) Google Sheets 的 Performance 工作表第3行四个单元格(B3、C3、D3、E3)是否与预期值完全匹配;2) Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported;3) Slack #campaign-reporting 频道是否恰好有一条内容完全匹配的消息;4) Gmail 是否恰好有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件(优先查找 sent 文件夹,若无则回退到收件人为 CMO 的任意邮件);5) 该邮件正文去除 HTML 标签后是否与预期正文完全匹配。每个组件通过则累加其权重分值,失败则计 0 分但不中断。最终总分为各组件得分之和,经 min(总分, 1.0) 钳制并四舍五入到 4 位小数后输出。\"\n\n这个很详细了。\n\n现在确认 JSON 格式。我需要确保所有引号都是双引号,并且正确转义。\n\n让我构建最终的 JSON 字符串。\n\n```json\n{\n \"task_id\": \"prof16_perf_report_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Google Sheets、Airtable、Slack 和 Gmail 四个 mock 服务中是否正确完成了 Spring Nurture 2026 绩效报告流程的各项数据录入与通知操作\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"sheets_mock\",\n \"airtable_mock\",\n \"slack_mock\",\n \"gmail_mock\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.30,\n \"description\": \"检查 Google Sheets 的 Performance 工作表第3行四个单元格是否与预期值完全匹配\",\n \"check_logic\": \"从 states['sheets'] 中查找 name 为 'Performance' 的 sheet,获取其 data 字段,对 B3、C3、D3、E3 分别与 EXPECTED['sheets'] 中的期望值进行 str(actual) != str(exp_val) 的字符串精确比较\",\n \"pass_condition\": \"Performance 工作表存在,且 B3=312、C3='38.4%'、D3='4.9%'、E3='HubSpot' 全部精确匹配\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.20,\n \"description\": \"检查 Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported\",\n \"check_logic\": \"遍历 states['airtable']['tables'],找到 name 为 'Campaigns' 的表,再遍历其 records,查找 fields 中 fld_campaign 或 Campaign 包含 'Spring Nurture' 的记录,检查其 fld_status 或 Status 是否精确等于 EXPECTED['airtable_status']\",\n \"pass_condition\": \"找到 Spring Nurture 2026 记录,且其 Status 字段精确等于 'Reported'\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.20,\n \"description\": \"检查 Slack #campaign-reporting 频道是否恰好包含一条内容完全匹配的消息\",\n \"check_logic\": \"检查 states['slack']['messages']['campaign-reporting'] 列表长度是否为 1,且唯一消息的 content 字段精确等于 EXPECTED['slack_message']\",\n \"pass_condition\": \"campaign-reporting 频道恰好有 1 条消息,且内容完全匹配预期字符串\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.15,\n \"description\": \"检查 Gmail 是否有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件\",\n \"check_logic\": \"从 states['gmail']['emails'] 中优先筛选 folder 为 'sent' 或 labels 包含 'SENT' 的邮件;若 sent 为空则回退到筛选 to 中包含 EXPECTED['gmail_to'] 的邮件;再从中筛选 to 中包含该地址且 subject 精确等于 EXPECTED['gmail_subject'] 的邮件,检查匹配数量是否恰好为 1\",\n \"pass_condition\": \"恰好存在 1 封发送给 cmo@northwindcloud.com 且主题为 'Spring Nurture 2026 — Performance Summary' 的邮件\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"检查 Gmail 发送给 cmo@northwindcloud.com 的匹配邮件正文是否完全匹配预期文本\",\n \"check_logic\": \"使用与 Component 4 相同的逻辑定位匹配邮件,获取其 body 字段,通过 re.sub(r'<[^>]+>', '', body).strip() 去除 HTML 标签并 strip 后,与同样处理后的 EXPECTED['gmail_body'] 进行精确比较\",\n \"pass_condition\": \"找到匹配邮件,且其正文去除 HTML 标签并 strip 后精确等于预期正文\"\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 或 sid 为空:打印 CRITICAL 并 sys.exit(0),REWARD 为 0.0\",\n \"从任一 mock 服务拉取状态失败或返回 current_state 为 None:打印 CRITICAL 并 sys.exit(0),REWARD 为 0.0\",\n \"Google Sheets 中 Performance 工作表不存在或四个单元格任一不匹配:该组件得 0.0\",\n \"Airtable 中未找到 Spring Nurture 2026 记录或 Status 不等于 Reported:该组件得 0.0\",\n \"Slack #campaign-reporting 频道消息数量不为 1 或内容不匹配:该组件得 0.0\",\n \"Gmail 中未找到恰好 1 封匹配 sent 邮件(主题或收件人不匹配):Component 4 得 0.0\",\n \"Gmail 匹配邮件正文去除 HTML 后不匹配:Component 5 得 0.0\",\n \"组件函数执行异常:捕获后该组件得 0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败或为空则直接退出并返回 0.0。随后使用 sid 向 Google Sheets、Airtable、Slack、Gmail 四个 mock 服务的 /go?sid={sid} 端点拉取 current_state,任一服务拉取失败或返回 current_state 为 None 则直接退出并返回 0.0。接着按顺序执行 5 个确定性精确匹配检查:1) Google Sheets 的 Performance 工作表第3行四个单元格(B3、C3、D3、E3)是否与预期值完全匹配;2) Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported;3) Slack #campaign-reporting 频道是否恰好有一条内容完全匹配的消息;4) Gmail 是否恰好有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件(优先查找 sent 文件夹,若无则回退到收件人为 CMO 的任意邮件);5) 该邮件正文去除 HTML 标签后是否与预期正文完全匹配。每个组件通过则累加其权重分值,失败则计 0 分但不中断后续检查。最终总分为各组件得分之和,经 min(总分, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。\",\n \"confidence\": 1.0\n}\n```\n\n我需要确保 JSON 是合法的。让我检查一下:\n- 所有键都是双引号。\n- 所有字符串值都是双引号。\n- 没有尾随逗号。\n- 换行在字符串中使用了实际的换行符?不,我在上面的文本块中写了多行字符串,但在 JSON 中这是不允许的(字符串不能包含未转义的换行符)。我需要在字符串中使用 \\n 或者确保字符串在一行内。\n\n实际上,在最终输出中,我可以将长字符串放在一行中,或者使用 \\n。为了安全和合法,我应该将多行字符串中的换行替换为 \\n。\n\n让我重新组织一下字符串,确保它们是合法的 JSON 字符串。\n\nscoring_logic_explanation 中的换行应该变成 \\n。但用户只是要求输出 JSON 对象,我可以输出格式化的 JSON,其中字符串内部包含 \\n 转义序列。\n\n让我重新写一下:\n\n\"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败或为空则直接退出并返回 0.0。随后使用 sid 向 Google Sheets、Airtable、Slack、Gmail 四个 mock 服务的 /go?sid={sid} 端点拉取 current_state,任一服务拉取失败或返回 current_state 为 None 则直接退出并返回 0.0。接着按顺序执行 5 个确定性精确匹配检查:1) Google Sheets 的 Performance 工作表第3行四个单元格(B3、C3、D3、E3)是否与预期值完全匹配;2) Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported;3) Slack #campaign-reporting 频道是否恰好有一条内容完全匹配的消息;4) Gmail 是否恰好有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件(优先查找 sent 文件夹,若无则回退到收件人为 CMO 的任意邮件);5) 该邮件正文去除 HTML 标签后是否与预期正文完全匹配。每个组件通过则累加其权重分值,失败则计 0 分但不中断后续检查。最终总分为各组件得分之和,经 min(总分, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。\"\n\n这个字符串没有实际换行,是合法的。\n\nfailure_modes 数组中的字符串也没有实际换行,是合法的。\n\nsummary 也是合法的。\n\n好的,我确认这个 JSON 是合法的。\n\n等等,domain 从 docstring 中提取的是 `mock_websites (multi-mock: Google Sheets, Airtable, Slack, Gmail)`。用户要求 \"如 mock_websites / software_engineer / libreoffice_calc\"。我应该填 `mock_websites` 还是完整字符串?示例显示的是简单的类别。docstring 中明确 `Domain: mock_websites (multi-mock: ...)`,所以 domain 是 `mock_websites`。我会填 `mock_websites`。\n\n再检查 task_id:`prof16_perf_report_002`。\n\n再检查 is_placeholder:false。\n\n再检查 confidence:1.0。\n\n一切看起来都正确。 {\n \"task_id\": \"prof16_perf_report_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Google Sheets、Airtable、Slack 和 Gmail 四个 mock 服务中是否正确完成了 Spring Nurture 2026 绩效报告流程的各项数据录入与通知操作\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"sheets_mock\",\n \"airtable_mock\",\n \"slack_mock\",\n \"gmail_mock\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.30,\n \"description\": \"检查 Google Sheets 的 Performance 工作表第3行四个单元格是否与预期值完全匹配\",\n \"check_logic\": \"从 states['sheets'] 中查找 name 为 'Performance' 的 sheet,获取其 data 字段,对 B3、C3、D3、E3 分别与 EXPECTED['sheets'] 中的期望值进行 str(actual) != str(exp_val) 的字符串精确比较\",\n \"pass_condition\": \"Performance 工作表存在,且 B3=312、C3='38.4%'、D3='4.9%'、E3='HubSpot' 全部精确匹配\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.20,\n \"description\": \"检查 Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported\",\n \"check_logic\": \"遍历 states['airtable']['tables'],找到 name 为 'Campaigns' 的表,再遍历其 records,查找 fields 中 fld_campaign 或 Campaign 包含 'Spring Nurture' 的记录,检查其 fld_status 或 Status 是否精确等于 EXPECTED['airtable_status']\",\n \"pass_condition\": \"找到 Spring Nurture 2026 记录,且其 Status 字段精确等于 'Reported'\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.20,\n \"description\": \"检查 Slack #campaign-reporting 频道是否恰好包含一条内容完全匹配的消息\",\n \"check_logic\": \"检查 states['slack']['messages']['campaign-reporting'] 列表长度是否为 1,且唯一消息的 content 字段精确等于 EXPECTED['slack_message']\",\n \"pass_condition\": \"campaign-reporting 频道恰好有 1 条消息,且内容完全匹配预期字符串\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.15,\n \"description\": \"检查 Gmail 是否有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件\",\n \"check_logic\": \"从 states['gmail']['emails'] 中优先筛选 folder 为 'sent' 或 labels 包含 'SENT' 的邮件;若 sent 为空则回退到筛选 to 中包含 EXPECTED['gmail_to'] 的邮件;再从中筛选 to 中包含该地址且 subject 精确等于 EXPECTED['gmail_subject'] 的邮件,检查匹配数量是否恰好为 1\",\n \"pass_condition\": \"恰好存在 1 封发送给 cmo@northwindcloud.com 且主题为 'Spring Nurture 2026 — Performance Summary' 的邮件\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"检查 Gmail 发送给 cmo@northwindcloud.com 的匹配邮件正文是否完全匹配预期文本\",\n \"check_logic\": \"使用与 Component 4 相同的逻辑定位匹配邮件,获取其 body 字段,通过 re.sub(r'<[^>]+>', '', body).strip() 去除 HTML 标签并 strip 后,与同样处理后的 EXPECTED['gmail_body'] 进行精确比较\",\n \"pass_condition\": \"找到匹配邮件,且其正文去除 HTML 标签并 strip 后精确等于预期正文\"\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 或 sid 为空:打印 CRITICAL 并 sys.exit(0),REWARD 为 0.0\",\n \"从任一 mock 服务拉取状态失败或返回 current_state 为 None:打印 CRITICAL 并 sys.exit(0),REWARD 为 0.0\",\n \"Google Sheets 中 Performance 工作表不存在或四个单元格任一不匹配:该组件得 0.0\",\n \"Airtable 中未找到 Spring Nurture 2026 记录或 Status 不等于 Reported:该组件得 0.0\",\n \"Slack #campaign-reporting 频道消息数量不为 1 或内容不匹配:该组件得 0.0\",\n \"Gmail 中未找到恰好 1 封匹配 sent 邮件(主题或收件人不匹配):Component 4 得 0.0\",\n \"Gmail 匹配邮件正文去除 HTML 后不匹配:Component 5 得 0.0\",\n \"组件函数执行异常:捕获后该组件得 0.0\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败或为空则直接退出并返回 0.0。随后使用 sid 向 Google Sheets、Airtable、Slack、Gmail 四个 mock 服务的 /go?sid={sid} 端点拉取 current_state,任一服务拉取失败或返回 current_state 为 None 则直接退出并返回 0.0。接着按顺序执行 5 个确定性精确匹配检查:1) Google Sheets 的 Performance 工作表第3行四个单元格(B3、C3、D3、E3)是否与预期值完全匹配;2) Airtable 的 Campaigns 表中 Spring Nurture 2026 记录的 Status 字段是否为 Reported;3) Slack #campaign-reporting 频道是否恰好有一条内容完全匹配的消息;4) Gmail 是否恰好有一封发送给 cmo@northwindcloud.com 且主题完全匹配的邮件(优先查找 sent 文件夹,若无则回退到收件人为 CMO 的任意邮件);5) 该邮件正文去除 HTML 标签后是否与预期正文完全匹配。每个组件通过则累加其权重分值,失败则计 0 分但不中断后续检查。最终总分为各组件得分之和,经 min(总分, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。\",\n \"confidence\": 1.0\n}" +} diff --git a/recruit_coordinator_006__long/_cua_gym_vm_bridge.sh b/recruit_coordinator_006__long/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/recruit_coordinator_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/recruit_coordinator_006__long/initial_setup.py b/recruit_coordinator_006__long/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..be14532729d0c105100f730f813f92b6f6b9f7e8 --- /dev/null +++ b/recruit_coordinator_006__long/initial_setup.py @@ -0,0 +1,969 @@ +""" +Initial Setup: Process outstanding offer approvals (Senior Backend Engineer) +Task ID: recruit_coordinator_006__long +Mocks: greenhouse_mock,gmail_mock,google_sheets_mock,slack_mock + +A recruiting coordinator processes the OUTSTANDING OFFER APPROVALS for the +'Senior Backend Engineer' job (job-1). A Google Sheet 'Offer Decisions' (tab +`Offers`) lists each candidate with the panel's compensation recommendation +(`Recommended Salary`, `Band Max`) and a `Decision` signal. Per row the +coordinator ROUTES the candidate in Greenhouse: + - HIRE (Decision 'Approved' AND Recommended Salary <= Band Max): + Move Stage -> 'Hired'; email Subject 'Offer confirmed - '; + add + PIN a decision note ('Hired - offer approved'); and append a + row (Name, Email, Salary) to a NEW Sheets 'Approved Offers' tab. + - REJECT (Decision 'Declined' OR Recommended Salary > Band Max i.e. over-band): + Reject with reason 'Compensation expectations'; email Subject + 'Update on your offer - '; add + PIN a note + ('Rejected - Compensation expectations'). + - HOLD (Decision 'Pending'): LEAVE unchanged (distractor). + - SKIP a candidate already in the 'Hired' stage (stale sheet row) and a + wrong-job candidate whose application is in a DIFFERENT job's Offer + stage (must not be touched). +Then post a one-line summary to Slack #recruiting and PIN it. + +HIDDEN ACCESS POINTS the agent must DISCOVER (the point of this task): + - Greenhouse Move Stage -> 'Hired' lives only on the candidate's own DETAIL + page (C5), and only while status is active. + - Greenhouse Reject on the detail page is DISABLED until a rejection reason is + picked from the dropdown (C6) -> status='rejected' + rejectionReason. + - Greenhouse note PIN is a hover toggle on the candidate Notes side-tab (C4); + only NEWLY-ADDED pinned notes are credited (diff by id). + - Google Sheets add a new tab 'Approved Offers' via the '+' control (C3). + - Slack message PIN is behind the per-message hover '...' menu (C4 aux). + +Ground truth (answer key) is embedded as a hidden `_offer` dict on each relevant +application, PRECOMPUTED IN PYTHON from the visible sheet columns + rule so the +visible data and the key can never disagree. It is mirrored in +google_sheets.initial_state._task_adapter (offers_tab/output_tab/headers_by_sheet +/expected) and slack.initial_state._task_adapter.summary_channel. + +Observable result kept ABSENT at injection (Rule 3): + - HIRE/REJECT applications start status='active' in the Offer stage (not Hired, + not rejected). notes[] holds only unpinned watermark notes. + - Gmail has NO email whose subject starts with 'Offer confirmed -' or + 'Update on your offer -'. + - Google Sheets has the 'Offers' tab but NO 'Approved Offers' tab. + - Slack #recruiting starts EMPTY (no messages, no pinned messages). +""" +import os +import shlex +import subprocess +import time +import uuid +from datetime import datetime, timedelta, timezone + +import requests + +TASK_ID = 'd4918cca-0109-46e9-861f-14d200ccc319' + +sid = str(uuid.uuid4()) +with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f: + f.write(sid) +print(f'Generated sid: {sid}') + + +# ------------------------------------------------------------------ +# Time anchors +# ------------------------------------------------------------------ +NOW = datetime(2026, 6, 30, 16, 0, 0, tzinfo=timezone.utc) + + +def iso(dt): + return dt.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + + +APPLIED_AT = iso(NOW - timedelta(days=30)) +OFFER_SINCE = iso(NOW - timedelta(days=3)) +LAST_ACTIVITY = iso(NOW - timedelta(days=1)) + + +# ================================================================== +# Scenario source of truth — everything (sheet cells, greenhouse +# applications, the embedded answer key) is DERIVED from this list. +# ================================================================== +BAND_MAX = 190000 + +# kind: hire | reject | leave | skip_hired | skip_wrongjob +ROW_SPECS = [ + dict(cand='cand-1', first='Ava', last='Ng', decision='Approved', salary=175000, kind='hire'), + dict(cand='cand-2', first='Ben', last='Osei', decision='Approved', salary=185000, kind='hire'), + dict(cand='cand-3', first='Carla', last='Diaz', decision='Approved', salary=205000, kind='reject'), # over-band + dict(cand='cand-4', first='Dan', last='Levy', decision='Declined', salary=180000, kind='reject'), # declined + dict(cand='cand-5', first='Eve', last='Park', decision='Pending', salary=182000, kind='leave'), + dict(cand='cand-6', first='Finn', last='Rao', decision='Pending', salary=188000, kind='leave'), + dict(cand='cand-7', first='Gina', last='Toh', decision='Approved', salary=170000, kind='skip_hired'), # already Hired + dict(cand='cand-8', first='Hugo', last='Vidal', decision='Approved', salary=178000, kind='skip_wrongjob'),# wrong job +] + +REJECT_REASON = 'Compensation expectations' + + +def route(decision, salary): + """The task's routing rule over the sheet's Decision + salary columns.""" + if decision == 'Pending': + return 'leave' + if decision == 'Approved' and salary <= BAND_MAX: + return 'hire' + # Declined, or Approved-but-over-band + return 'reject' + + +# ================================================================== +# GREENHOUSE +# ================================================================== +GH_USERS = [ + {'id': 'user-1', 'firstName': 'Jules', 'lastName': 'Park', 'name': 'Jules Park', + 'email': 'jules.park@company.com', 'role': 'recruiter', 'avatarUrl': None, + 'department': 'People Operations', 'title': 'Recruiting Coordinator'}, + {'id': 'user-2', 'firstName': 'Sarah', 'lastName': 'Chen', 'name': 'Sarah Chen', + 'email': 'sarah.chen@company.com', 'role': 'recruiter', 'avatarUrl': None, + 'department': 'People Operations', 'title': 'Recruiter'}, + {'id': 'user-3', 'firstName': 'David', 'lastName': 'Kim', 'name': 'David Kim', + 'email': 'david.kim@company.com', 'role': 'hiring_manager', 'avatarUrl': None, + 'department': 'Engineering', 'title': 'VP of Engineering'}, + {'id': 'user-4', 'firstName': 'Emily', 'lastName': 'Rodriguez', 'name': 'Emily Rodriguez', + 'email': 'emily.rodriguez@company.com', 'role': 'hiring_manager', 'avatarUrl': None, + 'department': 'Design', 'title': 'Head of Design'}, + {'id': 'user-5', 'firstName': 'Marcus', 'lastName': 'Johnson', 'name': 'Marcus Johnson', + 'email': 'marcus.johnson@company.com', 'role': 'interviewer', 'avatarUrl': None, + 'department': 'Engineering', 'title': 'Staff Engineer'}, +] +GH_CURRENT_USER = GH_USERS[0] + + +def job_stages(job_id): + """Standard 8-stage engineering pipeline. Index 7 = Offer, 8 = Hired.""" + spec = [ + ('Application Review', 'application_review'), + ('Recruiter Phone Screen', 'phone_screen'), + ('Hiring Manager Screen', 'phone_screen'), + ('Technical Interview', 'interview'), + ('Take Home', 'take_home'), + ('Onsite', 'onsite'), + ('Offer', 'offer'), + ('Hired', 'hired'), + ] + return [ + {'id': f'stage-{job_id}-{i}', 'jobId': job_id, 'name': name, + 'orderIndex': i - 1, 'stageType': stype} + for i, (name, stype) in enumerate(spec, start=1) + ] + + +JOB1_STAGES = job_stages('job-1') +JOB2_STAGES = job_stages('job-2') +GH_JOB_STAGES = JOB1_STAGES + JOB2_STAGES + +OFFER_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'offer') # stage-job-1-7 +HIRED_STAGE_ID = next(s['id'] for s in JOB1_STAGES if s['stageType'] == 'hired') # stage-job-1-8 +JOB2_OFFER_STAGE_ID = next(s['id'] for s in JOB2_STAGES if s['stageType'] == 'offer') + +GH_JOBS = [ + {'id': 'job-1', 'title': 'Senior Backend Engineer', 'status': 'open', + 'departmentId': 'dept-1', 'officeId': 'office-1', + 'hiringManagerId': 'user-3', 'recruiterId': 'user-1', 'coordinatorId': 'user-1', + 'openings': 3, 'openDate': '2026-04-01', 'closeDate': None, + 'description': 'Own core backend services in Go/Python.', + 'requirements': ['6+ years backend', 'Distributed systems', 'Go/Python'], + 'stages': [s['id'] for s in JOB1_STAGES], 'candidateCount': 11, + 'createdAt': '2026-04-01T09:00:00Z', 'updatedAt': LAST_ACTIVITY}, + {'id': 'job-2', 'title': 'Product Designer', 'status': 'open', + 'departmentId': 'dept-2', 'officeId': 'office-2', + 'hiringManagerId': 'user-4', 'recruiterId': 'user-2', 'coordinatorId': 'user-1', + 'openings': 1, 'openDate': '2026-05-01', 'closeDate': None, + 'description': 'Own product design for our growth surfaces.', + 'requirements': ['4+ years product design', 'Figma', 'Portfolio'], + 'stages': [s['id'] for s in JOB2_STAGES], 'candidateCount': 3, + 'createdAt': '2026-05-01T09:00:00Z', 'updatedAt': LAST_ACTIVITY}, +] + + +def email_for(first, last): + return f'{first.lower()}.{last.lower()}@example.com' + + +# ---- Candidates (8 sheet candidates + 3 pure distractors) ---------- +DISTRACTOR_CANDS = [ + ('cand-9', 'Iris', 'Wong'), # job-1 Technical Interview + ('cand-10', 'Jonah', 'Blum'), # job-1 Application Review + ('cand-11', 'Kira', 'Lund'), # job-2 Recruiter Phone Screen +] +ALL_CANDS = [(s['cand'], s['first'], s['last']) for s in ROW_SPECS] + DISTRACTOR_CANDS +GH_CANDIDATES = [ + {'id': cid, 'firstName': fn, 'lastName': ln, 'name': f'{fn} {ln}', + 'email': email_for(fn, ln), 'phone': '+1-555-{:04d}'.format(1000 + i), + 'location': 'Remote', 'currentCompany': 'Acme', 'currentTitle': 'Engineer', + 'resumeUrl': None, 'linkedinUrl': None, 'source': 'applied', + 'referrerId': None, 'tags': [], + 'createdAt': APPLIED_AT, 'updatedAt': LAST_ACTIVITY} + for i, (cid, fn, ln) in enumerate(ALL_CANDS, start=1) +] + + +# ---- Applications + embedded answer key (_offer) ------------------- +GH_APPLICATIONS = [] +GH_SCORECARDS = [] +GH_OFFERS = [] +_sc = 0 +_off = 0 + +for idx, spec in enumerate(ROW_SPECS, start=1): + cid = spec['cand'] + fn, ln = spec['first'], spec['last'] + kind = spec['kind'] + cand_name = f'{fn} {ln}' + cand_email = email_for(fn, ln) + salary = spec['salary'] + + # Greenhouse placement per kind + the hidden answer key. + if kind == 'hire': + job_id, stage_id, status, hired_at = 'job-1', OFFER_STAGE_ID, 'active', None + offer = {'action': 'hire', 'requires_action': True, + 'candidate_name': cand_name, 'candidate_email': cand_email, + 'target_stage_id': HIRED_STAGE_ID, 'target_status': 'active', + 'reject_reason': None, + 'email_subject': f'Offer confirmed - {cand_name}', + 'note_required': True, 'note_keywords': ['hired', 'offer approved', 'approved'], + 'approved_salary': salary} + elif kind == 'reject': + job_id, stage_id, status, hired_at = 'job-1', OFFER_STAGE_ID, 'active', None + offer = {'action': 'reject', 'requires_action': True, + 'candidate_name': cand_name, 'candidate_email': cand_email, + 'target_stage_id': None, 'target_status': 'rejected', + 'reject_reason': REJECT_REASON, + 'email_subject': f'Update on your offer - {cand_name}', + 'note_required': True, + 'note_keywords': ['reject', 'compensation expectations'], + 'approved_salary': None} + elif kind == 'leave': + job_id, stage_id, status, hired_at = 'job-1', OFFER_STAGE_ID, 'active', None + offer = {'action': 'leave', 'requires_action': False, + 'candidate_name': cand_name, 'candidate_email': cand_email, + 'target_stage_id': None, 'target_status': 'active', + 'reject_reason': None, 'email_subject': None, + 'note_required': False, 'note_keywords': [], 'approved_salary': None} + elif kind == 'skip_hired': + job_id, stage_id, status, hired_at = 'job-1', HIRED_STAGE_ID, 'active', LAST_ACTIVITY + offer = {'action': 'skip', 'requires_action': False, + 'candidate_name': cand_name, 'candidate_email': cand_email, + 'target_stage_id': None, 'target_status': 'active', + 'reject_reason': None, 'email_subject': None, + 'note_required': False, 'note_keywords': [], 'approved_salary': None, + '_skip_reason': 'already_hired'} + else: # skip_wrongjob + job_id, stage_id, status, hired_at = 'job-2', JOB2_OFFER_STAGE_ID, 'active', None + offer = {'action': 'skip', 'requires_action': False, + 'candidate_name': cand_name, 'candidate_email': cand_email, + 'target_stage_id': None, 'target_status': 'active', + 'reject_reason': None, 'email_subject': None, + 'note_required': False, 'note_keywords': [], 'approved_salary': None, + '_skip_reason': 'wrong_job'} + + app_id = f'app-{idx}' + GH_APPLICATIONS.append({ + 'id': app_id, 'candidateId': cid, 'jobId': job_id, + 'currentStageId': stage_id, 'status': status, + 'appliedAt': APPLIED_AT, 'rejectedAt': None, 'rejectionReason': None, + 'hiredAt': hired_at, 'lastActivityAt': LAST_ACTIVITY, 'source': 'applied', + 'creditedTo': None, 'recruiterId': 'user-1' if job_id == 'job-1' else 'user-2', + 'coordinatorId': 'user-1', + 'actionRequired': 'offer_decision' if kind in ('hire', 'reject', 'leave') else None, + 'daysInCurrentStage': 3, + '_offer': offer, + }) + + # Realism: one submitted onsite scorecard per offer-stage candidate. + if kind in ('hire', 'reject', 'leave', 'skip_wrongjob'): + _sc += 1 + GH_SCORECARDS.append({ + 'id': f'sc-{_sc}', 'applicationId': app_id, 'interviewerId': 'user-5', + 'stageId': stage_id, 'overallRecommendation': 'strong_yes', + 'attributes': [{'name': 'Technical', 'rating': 4, 'note': 'Excellent.'}], + 'submittedAt': iso(NOW - timedelta(days=5)), + 'createdAt': iso(NOW - timedelta(days=6)), 'notes': ''}) + + # Realism: an offer record for the offer-stage / hired candidates. + if kind in ('hire', 'reject', 'leave'): + _off += 1 + GH_OFFERS.append({ + 'id': f'offer-{_off}', 'applicationId': app_id, 'jobId': 'job-1', + 'status': 'pending_approval', 'salary': salary, 'currency': 'USD', + 'startDate': '2026-08-01', 'expiresAt': iso(NOW + timedelta(days=14)), + 'createdBy': 'user-1', + 'approvers': [{'userId': 'user-3', 'status': 'pending', 'respondedAt': None}], + 'createdAt': OFFER_SINCE, 'updatedAt': LAST_ACTIVITY}) + elif kind == 'skip_hired': + _off += 1 + GH_OFFERS.append({ + 'id': f'offer-{_off}', 'applicationId': app_id, 'jobId': 'job-1', + 'status': 'accepted', 'salary': salary, 'currency': 'USD', + 'startDate': '2026-07-15', 'expiresAt': iso(NOW - timedelta(days=1)), + 'createdBy': 'user-1', + 'approvers': [{'userId': 'user-3', 'status': 'approved', + 'respondedAt': iso(NOW - timedelta(days=2))}], + 'createdAt': iso(NOW - timedelta(days=6)), 'updatedAt': LAST_ACTIVITY}) + + +# ---- Pure distractor applications (NO _offer; never graded) -------- +DISTRACTOR_APPS = [ + ('app-9', 'cand-9', 'job-1', 'stage-job-1-4', 'active', None, None), + ('app-10', 'cand-10', 'job-1', 'stage-job-1-1', 'active', None, None), + ('app-11', 'cand-11', 'job-2', 'stage-job-2-2', 'active', None, None), +] +for (aid, cid, jid, stage, status, rej_at, rej_reason) in DISTRACTOR_APPS: + GH_APPLICATIONS.append({ + 'id': aid, 'candidateId': cid, 'jobId': jid, + 'currentStageId': stage, 'status': status, + 'appliedAt': APPLIED_AT, 'rejectedAt': rej_at, 'rejectionReason': rej_reason, + 'hiredAt': None, 'lastActivityAt': LAST_ACTIVITY, 'source': 'applied', + 'creditedTo': None, 'recruiterId': 'user-1' if jid == 'job-1' else 'user-2', + 'coordinatorId': 'user-1', 'actionRequired': None, 'daysInCurrentStage': 5}) + + +GREENHOUSE_STATE = { + 'currentUser': GH_CURRENT_USER, + 'users': GH_USERS, + 'departments': [ + {'id': 'dept-1', 'name': 'Engineering', 'parentId': None}, + {'id': 'dept-2', 'name': 'Design', 'parentId': None}, + {'id': 'dept-6', 'name': 'People Operations', 'parentId': None}, + ], + 'offices': [ + {'id': 'office-1', 'name': 'San Francisco HQ', 'location': 'San Francisco, CA'}, + {'id': 'office-2', 'name': 'New York', 'location': 'New York, NY'}, + {'id': 'office-3', 'name': 'Remote', 'location': 'Remote'}, + ], + 'sources': [{'id': 'src-1', 'name': 'Applied'}, + {'id': 'src-2', 'name': 'Referral'}], + 'rejectionReasons': [ + {'id': 'rr-1', 'name': 'Compensation expectations'}, + {'id': 'rr-2', 'name': 'Lacking technical skills'}, + {'id': 'rr-3', 'name': 'Culture/values misalignment'}, + {'id': 'rr-4', 'name': 'Not enough support'}, + ], + 'jobs': GH_JOBS, + 'jobStages': GH_JOB_STAGES, + 'candidates': GH_CANDIDATES, + 'applications': GH_APPLICATIONS, + 'scorecards': GH_SCORECARDS, + 'interviews': [], + 'offers': GH_OFFERS, + 'notes': [ + # Unpinned watermark notes only (reward credits only NEWLY-ADDED pinned notes). + {'id': 'note-1', 'candidateId': 'cand-1', 'authorId': 'user-1', + 'body': 'Offer packet drafted; awaiting final approval.', 'visibility': 'public', + 'isPinned': False, 'createdAt': LAST_ACTIVITY, 'updatedAt': LAST_ACTIVITY}, + {'id': 'note-2', 'candidateId': 'cand-3', 'authorId': 'user-3', + 'body': 'Panel flagged compensation ask is high.', 'visibility': 'public', + 'isPinned': False, 'createdAt': LAST_ACTIVITY, 'updatedAt': LAST_ACTIVITY}, + ], + 'activityFeed': [], + 'notifications': [ + {'id': 'notif-1', 'type': 'approval_due', 'title': 'Offer approvals pending', + 'message': 'Outstanding offer approvals for Senior Backend Engineer.', + 'isRead': False, 'link': '/jobs/job-1', 'createdAt': OFFER_SINCE}, + ], + 'ui': {'searchQuery': '', 'activeJobId': 'job-1', 'activeCandidateId': None, + 'modals': {'addCandidate': False, 'createJob': False, + 'scheduleInterview': False, 'rejectCandidate': False, + 'moveStage': False, 'search': False, 'notifications': False}}, +} + + +# ================================================================== +# GMAIL — coordinator inbox. NO decision emails present (Rule 3). +# ================================================================== +def gmail_email(i, sender_name, sender_email, subject, body, folder='inbox', + read=False, days_ago=1): + ts = iso(NOW - timedelta(days=days_ago)) + return { + 'id': f'email_{i}', 'threadId': f'thread_{i}', + 'from': {'name': sender_name, 'email': sender_email, 'avatar': ''}, + 'to': [{'name': 'Jules Park', 'email': 'jules.park@company.com'}], + 'cc': [], 'bcc': [], 'subject': subject, 'body': body, 'snippet': body[:80], + 'timestamp': ts, 'read': read, 'starred': False, 'important': False, + 'labels': [], 'category': 'primary', 'folder': folder, 'attachments': [], + } + + +GMAIL_STATE = { + 'user': {'userId': 'u1', 'username': 'Jules Park', + 'email': 'jules.park@company.com', + 'avatar': 'https://picsum.photos/200/200?random=1'}, + 'emails': [ + # Decoys only — none start with 'Offer confirmed -' / 'Update on your offer -'. + gmail_email(1, 'David Kim', 'david.kim@company.com', + 'Offer approvals for Senior Backend Engineer', + 'The offer decisions are in the Offer Decisions sheet. Please ' + 'process them today and record the approved offers.', days_ago=1), + gmail_email(2, 'Ava Ng', 'ava.ng@example.com', + 'Re: Onsite follow-up', + 'Thanks again for the onsite — excited about the backend role and ' + 'happy to discuss the offer whenever it is ready.', days_ago=2), + gmail_email(3, 'Finance', 'finance@company.com', + 'Compensation bands refreshed', + 'Updated engineering compensation bands are attached for your ' + 'reference during approvals.', folder='inbox', read=True, days_ago=3), + gmail_email(4, 'Workday Notifications', 'no-reply@workday.com', + 'Weekly hiring summary', + 'Your pipelines have new activity. Log in to review.', + folder='inbox', read=True, days_ago=4), + ], + 'labels': [ + {'id': 'l1', 'name': 'Work', 'color': '#ef4444'}, + {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'}, + {'id': 'l3', 'name': 'Offers', 'color': '#22c55e'}, + {'id': 'l4', 'name': 'Finance', 'color': '#eab308'}, + ], + 'drafts': [], + 'settings': { + 'density': 'default', 'undoSend': 10, + 'signature': '--\nJules Park\nRecruiting Coordinator, Acme Corp', + 'replyBehavior': 'Reply', 'language': 'English (US)', + }, +} + + +# ================================================================== +# GOOGLE SHEETS — 'Offer Decisions' workbook, tab 'Offers'. +# NO 'Approved Offers' tab at injection (Rule 3). +# ================================================================== +OFFERS_TAB = 'Offers' +OUTPUT_TAB = 'Approved Offers' +OFFERS_HEADERS = ['Candidate', 'Recommended Salary', 'Band Max', 'Decision'] +OUTPUT_HEADERS = ['Name', 'Email', 'Salary'] +COL_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F'] + + +def header_cell(text): + return {'value': text, 'formula': text, 'computed': text, + 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}} + + +def text_cell(text): + return {'value': str(text), 'formula': str(text), 'computed': str(text)} + + +def num_cell(n): + return {'value': str(n), 'formula': str(n), 'computed': n} + + +offers_rows_dict = [] +for spec in ROW_SPECS: + offers_rows_dict.append({ + 'Candidate': f"{spec['first']} {spec['last']}", + 'Recommended Salary': spec['salary'], + 'Band Max': BAND_MAX, + 'Decision': spec['decision'], + }) + +offers_data = {} +for col, head in zip(COL_LETTERS, OFFERS_HEADERS): + offers_data[f'{col}1'] = header_cell(head) +for idx, row in enumerate(offers_rows_dict): + r = idx + 2 + offers_data[f'A{r}'] = text_cell(row['Candidate']) + offers_data[f'B{r}'] = num_cell(row['Recommended Salary']) + offers_data[f'C{r}'] = num_cell(row['Band Max']) + offers_data[f'D{r}'] = text_cell(row['Decision']) + +# Answer-key mirror (per-row) for the sheet <-> greenhouse consistency. +_expected_by_name = {} +_hire_set = [] +for spec in ROW_SPECS: + name = f"{spec['first']} {spec['last']}" + email = email_for(spec['first'], spec['last']) + kind = spec['kind'] + action = 'skip' if kind.startswith('skip') else kind + _expected_by_name[name] = { + 'action': action, 'decision': spec['decision'], 'salary': spec['salary'], + 'email': email, + } + if action == 'hire': + _hire_set.append({'name': name, 'email': email, 'salary': spec['salary']}) + +GOOGLE_SHEETS_STATE = { + 'id': 'workbook_offer_decisions', + 'title': 'Offer Decisions', + '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': OFFERS_TAB, + 'data': offers_data, + 'rowCount': 100, + 'colCount': 26, + 'frozenRows': 1, + 'frozenCols': 0, + 'tabColor': None, + 'isHidden': False, + 'columnWidths': {}, + 'rowHeights': {}, + 'filterRange': None, + 'filterCriteria': {}, + 'sortColumn': None, + 'sortDirection': None, + }], + '_task_adapter': { + 'task_id': TASK_ID, + 'variant': 'eval', + 'offers_tab': OFFERS_TAB, + 'output_tab': OUTPUT_TAB, + 'band_max': BAND_MAX, + 'headers_by_sheet': {OFFERS_TAB: OFFERS_HEADERS, OUTPUT_TAB: OUTPUT_HEADERS}, + 'sheet_names': [OFFERS_TAB], + 'expected_by_name': _expected_by_name, + 'hire_set': _hire_set, + }, +} + + +# ================================================================== +# SLACK — #recruiting starts EMPTY (Rule 3); the agent posts + pins. +# ================================================================== +def slack_user(uid, full, disp, email, rnd, title='', status='online'): + return {'userId': uid, 'fullName': full, 'displayName': disp, 'email': email, + 'avatar': f'https://picsum.photos/200/200?random={rnd}', 'title': title, + 'status': status, 'statusMessage': '', 'statusEmoji': '', + 'timeZone': 'America/New_York'} + + +def slack_channel(cid, name, desc, topic, members, created_by, starred=False, unread=0): + return {'channelId': cid, 'name': name, 'description': desc, 'topic': topic, + 'isPrivate': False, 'isStarred': starred, 'members': members, + 'createdBy': created_by, 'createdAt': '2026-04-01T08:00:00Z', + 'pinnedMessages': [], 'unreadCount': unread} + + +def slack_msg(mid, sender, content, ts, reactions=None): + return {'messageId': mid, 'senderId': sender, 'content': content, + 'timestamp': ts, 'reactions': reactions or [], 'isEdited': False, + 'threadId': None, 'attachments': []} + + +SLACK_USERS = [ + slack_user('user_1', 'Jules Park', 'Jules', 'jules.park@company.com', 1, + 'Recruiting Coordinator'), + slack_user('user_2', 'Sarah Chen', 'Sarah', 'sarah.chen@company.com', 2, + 'Recruiter', status='away'), + slack_user('user_3', 'David Kim', 'David', 'david.kim@company.com', 3, + 'VP of Engineering'), + slack_user('user_4', 'Emily Rodriguez', 'Emily', 'emily.rodriguez@company.com', 4, + 'Head of Design'), +] + +SLACK_STATE = { + 'currentUser': SLACK_USERS[0], + 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''}, + 'users': SLACK_USERS, + 'channels': [ + slack_channel('general', 'general', 'Company-wide announcements', + 'Welcome to Acme Corp!', ['user_1', 'user_2', 'user_3', 'user_4'], + 'user_3', starred=True), + slack_channel('random', 'random', 'Non-work banter', 'Coffee and memes', + ['user_1', 'user_2', 'user_3', 'user_4'], 'user_2'), + slack_channel('eng-hiring', 'eng-hiring', 'Engineering hiring coordination', + 'Pipeline syncs, approvals', ['user_1', 'user_3'], 'user_3'), + # TARGET channel — starts empty (Rule 3). + slack_channel('recruiting', 'recruiting', + 'Recruiting team channel — offer decisions, candidate updates', + 'Post one line per offer-approval batch', + ['user_1', 'user_2', 'user_4'], 'user_1', starred=True), + ], + 'messages': { + 'general': [ + slack_msg('m_g_1', 'user_3', + 'Reminder: process the outstanding Senior Backend offers today.', + '2026-06-29T15:30:00Z'), + slack_msg('m_g_2', 'user_4', + 'Offer Decisions sheet is updated with the panel recommendations.', + '2026-06-29T17:02:00Z', + reactions=[{'emoji': '✅', 'users': ['user_1']}]), + ], + 'random': [ + slack_msg('m_r_1', 'user_2', 'Espresso machine is making sad noises again.', + '2026-06-29T13:45:00Z'), + slack_msg('m_r_2', 'user_4', 'Filed a ticket. ETA: eventually.', + '2026-06-29T13:48:00Z'), + ], + 'eng-hiring': [ + slack_msg('m_e_1', 'user_3', + 'Backend loop finished for all offer-stage candidates. Over to you.', + '2026-06-29T13:00:00Z', + reactions=[{'emoji': '\U0001f44d', 'users': ['user_1']}]), + slack_msg('m_e_2', 'user_1', 'On it — will process the offer approvals today.', + '2026-06-29T13:04:00Z'), + ], + 'recruiting': [], + }, + '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': 'recruiting', + }, +} + + +# ================================================================== +# Build-time consistency assertions (fail fast) +# ================================================================== +_offer_apps = [a for a in GH_APPLICATIONS if isinstance(a.get('_offer'), dict)] +_actions = [a['_offer']['action'] for a in _offer_apps] +assert _actions.count('hire') == 2, _actions +assert _actions.count('reject') == 2, _actions +assert _actions.count('leave') == 2, _actions +assert _actions.count('skip') == 2, _actions + +_kinds = [s['kind'] for s in ROW_SPECS] +assert _kinds.count('hire') == 2 and _kinds.count('reject') == 2, _kinds +assert _kinds.count('leave') == 2, _kinds +assert _kinds.count('skip_hired') == 1 and _kinds.count('skip_wrongjob') == 1, _kinds + +# For the routable rows: the sheet Decision+salary must map (via the rule) to the +# SAME action embedded in the greenhouse _offer key -> visible data <-> key agree. +for spec, app in zip(ROW_SPECS, GH_APPLICATIONS[:len(ROW_SPECS)]): + kind = spec['kind'] + if kind in ('hire', 'reject', 'leave'): + r = route(spec['decision'], spec['salary']) + assert r == kind, (spec['cand'], spec['decision'], spec['salary'], r, kind) + assert app['_offer']['action'] == kind + else: # skip rows + assert app['_offer']['action'] == 'skip' + +# hire _offer.approved_salary must equal the sheet's Recommended Salary. +for spec, app in zip(ROW_SPECS, GH_APPLICATIONS[:len(ROW_SPECS)]): + if spec['kind'] == 'hire': + assert app['_offer']['approved_salary'] == spec['salary'] + +# Greenhouse placement of the skip distractors. +_gina = next(a for a in GH_APPLICATIONS if a['candidateId'] == 'cand-7') +assert _gina['jobId'] == 'job-1' and _gina['currentStageId'] == HIRED_STAGE_ID +_hugo = next(a for a in GH_APPLICATIONS if a['candidateId'] == 'cand-8') +assert _hugo['jobId'] == 'job-2' and _hugo['currentStageId'] == JOB2_OFFER_STAGE_ID + +# note_required only for hire/reject. +assert all(a['_offer']['note_required'] for a in _offer_apps + if a['_offer']['action'] in ('hire', 'reject')) +assert all(not a['_offer']['note_required'] for a in _offer_apps + if a['_offer']['action'] in ('leave', 'skip')) + +# The reject reason must be a valid greenhouse rejection reason. +_reasons = {r['name'] for r in GREENHOUSE_STATE['rejectionReasons']} +assert REJECT_REASON in _reasons + +# Rule 3: decision emails absent; Approved Offers tab absent; #recruiting empty; +# no pinned notes on offer-stage candidates. +assert not any( + str(e['subject']).startswith('Offer confirmed -') or + str(e['subject']).startswith('Update on your offer -') + for e in GMAIL_STATE['emails']), 'decision email leaked into initial gmail' +assert all(sh['name'] != OUTPUT_TAB for sh in GOOGLE_SHEETS_STATE['sheets']), \ + "'Approved Offers' tab must be absent at injection" +assert SLACK_STATE['messages']['recruiting'] == [], '#recruiting must start empty' +assert all(ch['pinnedMessages'] == [] for ch in SLACK_STATE['channels']), \ + 'no pinned slack message at injection' +_offer_cands = {a['candidateId'] for a in _offer_apps} +assert not any(n.get('isPinned') and n.get('candidateId') in _offer_cands + for n in GREENHOUSE_STATE['notes']), 'pinned note leaked at injection' + +print('Self-check OK: actions =', _actions, '| hire_set =', _hire_set) + + +# ================================================================== +# Inject + verify + launch +# ================================================================== +APP_STATES = [ + ('http://28.7.184.198:8146', GREENHOUSE_STATE), # greenhouse_mock + ('http://28.7.184.198:8138', GMAIL_STATE), # gmail_mock + ('http://28.7.184.198: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}') + + +# 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_coordinator_006__long/reward.py b/recruit_coordinator_006__long/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9ec8de35dc2bd728d52bc8f0d953010d930ee2 --- /dev/null +++ b/recruit_coordinator_006__long/reward.py @@ -0,0 +1,696 @@ +""" +Reward Script: Process outstanding offer approvals (Senior Backend Engineer) +Task ID: recruit_coordinator_006__long +Mocks: greenhouse_mock,gmail_mock,google_sheets_mock,slack_mock + +The agent processes the OUTSTANDING OFFER APPROVALS for job-1 ('Senior Backend +Engineer'). A Google Sheet 'Offer Decisions' (tab 'Offers') lists each candidate +with Recommended Salary / Band Max / Decision. Per row: + - HIRE (Decision 'Approved' AND salary <= Band Max): Greenhouse Move Stage -> + 'Hired'; email 'Offer confirmed - '; add + PIN a decision note; + append a row (Name, Email, Salary) to a NEW Sheets 'Approved Offers' tab. + - REJECT (Decision 'Declined' OR salary > Band Max): Greenhouse Reject with reason + 'Compensation expectations'; email 'Update on your offer - '; + add + PIN a decision note. + - LEAVE (Decision 'Pending'): unchanged. + - SKIP already-Hired candidate + wrong-job candidate: unchanged. +Then post + PIN a one-line summary to Slack #recruiting. + +Ground truth is a hidden `_offer` dict on each relevant application (the reward +reads it there). All components are POSITIVE and precision-aware; leak lowers a +component toward 0 (never below), so the total is always in [0, 1] and a +do-nothing agent scores exactly 0. + +Weights (sum = 1.0; NO subtracted penalties): + 0.26 move/reject decision-set correctness (positive precision: denom includes + any wrongly-actioned leave/skip row, so a leak lowers it, never below 0) + 0.18 decision email present with the exact subject (over action rows) + 0.10 reject reason == key on rejected rows + 0.20 'Approved Offers' sheet tab (absent at injection) whose rows == the HIRE + set by (name, email, salary) via F1 (extra/wrong rows = FP -> precision v) + 0.16 NEW pinned decision note per action row (diff by id + pinned + keyword) + 0.05 Slack #recruiting summary posted (non-empty, has a digit, offer keyword) + 0.05 that #recruiting summary is PINNED (gated on a real posted message) +""" +import copy +from datetime import datetime +import re +import sys + +import requests + + +try: + with open('/tmp/task_web_sid', encoding='utf-8') as f: + sid = f.read().strip() + if not sid: + raise ValueError('sid is empty') +except Exception as e: + print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') + print('REWARD: 0.0') + sys.exit(0) + + +APP_URLS = {'greenhouse': 'http://28.7.184.198:8146', 'gmail': 'http://28.7.184.198:8138', + 'google_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 _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() + if s.endswith('Z'): + s = s[:-1] + '+00:00' + try: + return datetime.fromisoformat(s) + except Exception: + return None + + +def _normalize_app_name(app): + app = (app or '').strip().lower() + return app[:-5] if app.endswith('_mock') else app + + +def _parse_cell_id(cell_id): + if not isinstance(cell_id, str) or not cell_id: + return None + idx = 0 + while idx < len(cell_id) and cell_id[idx].isalpha(): + idx += 1 + if idx == 0 or idx >= len(cell_id): + return None + col = 0 + for ch in cell_id[:idx].upper(): + col = col * 26 + (ord(ch) - ord('A') + 1) + try: + row = int(cell_id[idx:]) + except ValueError: + return None + return row, col - 1 + + +def _extract_rows_from_workbook(state): + if not isinstance(state, dict): + return None + sheets = state.get('sheets') + if not isinstance(sheets, list): + return None + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} + + out = {} + for sh in sheets: + if not isinstance(sh, dict): + continue + name = sh.get('name') or sh.get('id') or 'Sheet1' + data = sh.get('data') if isinstance(sh.get('data'), dict) else {} + + headers = headers_by_sheet.get(name) + if not headers: + cols = [] + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx != 1: + continue + value = '' + if isinstance(cell, dict): + value = cell.get('value', '') + elif cell is not None: + value = str(cell) + if value is not None and str(value) != '': + cols.append((col_idx, str(value))) + headers = [v for _, v in sorted(cols)] + + if not headers: + continue + + by_row = {} + for cid, cell in data.items(): + rc = _parse_cell_id(cid) + if not rc: + continue + row_idx, col_idx = rc + if row_idx <= 1 or col_idx >= len(headers): + continue + if isinstance(cell, dict): + value = cell.get('value', '') + else: + value = cell + by_row.setdefault(row_idx, {})[headers[col_idx]] = value + + rows = [] + for row_idx in sorted(by_row.keys()): + row = by_row[row_idx] + if not any(str(row.get(h, '')).strip() for h in headers): + continue + rows.append({h: row.get(h, '') for h in headers}) + + out[name] = {'headers': headers, 'rows': rows} + + if not out: + return None + return {'sheets': out} + + +def _materialize_google_sheets(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + maybe_rows = _extract_rows_from_workbook(state) + if maybe_rows is not None: + state['_ui_workbook'] = { + 'sheets': copy.deepcopy(state.get('sheets', [])), + 'title': state.get('title'), + } + state['sheets'] = maybe_rows['sheets'] + + +def _materialize_slack(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + channels = state.get('channels') if isinstance(state.get('channels'), list) else [] + messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} + for ch in channels: + if not isinstance(ch, dict): + continue + cid = ch.get('channelId') or ch.get('id') + if not cid: + continue + msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] + channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] + merged = { + (m.get('messageId') or m.get('id')): dict(m) + for m in channel_msgs + if isinstance(m, dict) + } + for m in msg_list: + if not isinstance(m, dict): + continue + mid = m.get('messageId') or m.get('id') + text = m.get('text') if m.get('text') is not None else m.get('content', '') + merged[mid] = { + 'id': mid, + 'messageId': mid, + 'text': text, + 'content': m.get('content', text), + 'senderId': m.get('senderId'), + 'timestamp': m.get('timestamp'), + 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], + } + ch['messages'] = list(merged.values()) + + +def _owner_name_map(state): + out = {} + users = state.get('users') if isinstance(state.get('users'), list) else [] + for u in users: + if not isinstance(u, dict): + continue + uid = u.get('userId') + if not uid: + continue + name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) + out[uid] = name + return out + + +def _materialize_salesforce(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + owner_names = _owner_name_map(state) + + task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None + if task_leads and isinstance(state.get('leads'), list): + restored = [] + for lead in state['leads']: + if not isinstance(lead, dict): + continue + lid = str(lead.get('leadId') or lead.get('id') or '') + meta = task_leads.get(lid, {}) + restored.append({ + 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), + 'company': lead.get('company', meta.get('company', '')), + 'status': lead.get('status', 'New'), + 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), + 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), + }) + state['leads'] = restored + + task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None + if task_accounts and isinstance(state.get('accounts'), list): + current_by_id = {} + for acc in state['accounts']: + if isinstance(acc, dict): + current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc + + restored_accounts = [] + for aid, meta in task_accounts.items(): + cur = current_by_id.get(str(aid), {}) + restored_accounts.append({ + 'id': meta.get('id') or aid, + 'name': meta.get('name') or cur.get('name', ''), + 'contact': meta.get('contact'), + 'wonWithin7d': bool(meta.get('wonWithin7d', False)), + 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), + }) + state['accounts'] = restored_accounts + + +def _materialize_google_docs(payload): + for key in ('initial_state', 'current_state'): + state = payload.get(key) + if not isinstance(state, dict): + continue + adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} + task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None + if not task_docs: + continue + docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} + restored = [] + for did, meta in task_docs.items(): + cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} + restored.append({ + 'id': meta.get('id') or did, + 'title': cur.get('title', meta.get('title')), + 'vendor': meta.get('vendor'), + 'folder': meta.get('folder'), + 'content': cur.get('content', meta.get('content', '')), + }) + state['documents'] = restored + + +def _adapt_payload_for_reward(app, payload): + app_name = _normalize_app_name(app) + if app_name == 'google_sheets': + _materialize_google_sheets(payload) + elif app_name == 'slack': + _materialize_slack(payload) + elif app_name == 'salesforce': + _materialize_salesforce(payload) + elif app_name == 'google_docs': + _materialize_google_docs(payload) + return payload + + +def go(app_name): + if app_name in _GO_CACHE: + return _GO_CACHE[app_name] + + base = APP_URLS.get(app_name) + if not base: + print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') + print('REWARD: 0.0') + sys.exit(0) + + try: + resp = requests.get(f'{base}/go?sid={sid}', timeout=15) + resp.raise_for_status() + payload = resp.json() + except Exception as e: + print(f'CRITICAL: cannot fetch {app_name} go state: {e}') + print('REWARD: 0.0') + sys.exit(0) + + payload = _adapt_payload_for_reward(app_name, payload) + _GO_CACHE[app_name] = payload + return payload + + +# === Task-specific reward === +TARGET_JOB = 'job-1' + + +def _job_stage_id_by_type(state, job_id, stage_type): + """Resolve a stage id from jobStages by (jobId, stageType) — do not hardcode.""" + for s in (state or {}).get('jobStages', []) or []: + if (isinstance(s, dict) and s.get('jobId') == job_id + and norm(s.get('stageType')) == norm(stage_type)): + return s.get('id') + return None + + +def _current_emails(gmail_payload): + state = gmail_payload.get('current_state') or {} + return [e for e in (state.get('emails') or []) if isinstance(e, dict)] + + +def _subject_present(emails, subject): + """True iff some sent email has an (exact, normalized) matching subject.""" + target = norm(subject) + if not target: + return False + return any(norm(e.get('subject')) == target for e in emails) + + +def _row_get(row, header): + """Case-insensitive lookup of a value in an extracted row dict.""" + if not isinstance(row, dict): + return '' + want = norm(header) + for k, v in row.items(): + if norm(k) == want: + return v + return '' + + +def _to_salary_int(v): + s = re.sub(r'[^0-9.\-]', '', str(v if v is not None else '')) + if not s: + return None + try: + return int(round(float(s))) + except (TypeError, ValueError): + return None + + +def _sheet_tabs(state): + """After materialization state['sheets'] is a dict {name: {headers, rows}}.""" + sheets = state.get('sheets') if isinstance(state, dict) else None + return sheets if isinstance(sheets, dict) else {} + + +def reward(go): + gh = go('greenhouse') + gh_initial = gh.get('initial_state') or {} + gh_current = gh.get('current_state') or {} + gmail = go('gmail') + gs = go('google_sheets') + gs_initial = gs.get('initial_state') or {} + gs_current = gs.get('current_state') or {} + + hired_stage_id = _job_stage_id_by_type(gh_initial, TARGET_JOB, 'hired') + + apps_i = [a for a in (gh_initial.get('applications') or []) if isinstance(a, dict)] + apps_c = {a.get('id'): a for a in (gh_current.get('applications') or []) + if isinstance(a, dict)} + + sent_emails = _gmail_sent_emails(gmail.get('current_state') or {}) + + # Target set: applications carrying the hidden answer key. + targets = [a for a in apps_i if isinstance(a.get('_offer'), dict)] + hire_rows = [a for a in targets if norm(a['_offer'].get('action')) == 'hire'] + reject_rows = [a for a in targets if norm(a['_offer'].get('action')) == 'reject'] + act_rows = hire_rows + reject_rows + nonaction_rows = [a for a in targets + if norm(a['_offer'].get('action')) in ('leave', 'skip')] + + # --- Component 1 (0.26): move/reject decision-set correctness (precision) --- + # num = correct action-outcomes over rows that REQUIRE action. + # denom = #require-action + #wrongly-actioned(leave/skip changed). do-nothing 0. + move_ok = 0 + for a in act_rows: + dec = a['_offer'] + action = norm(dec.get('action')) + cur = apps_c.get(a.get('id')) if isinstance(apps_c.get(a.get('id')), dict) else {} + if action == 'hire': + ok = norm(cur.get('currentStageId')) == norm(dec.get('target_stage_id') or hired_stage_id) + else: # reject + ok = norm(cur.get('status')) == norm(dec.get('target_status') or 'rejected') + move_ok += int(bool(ok)) + + wrongly_actioned = 0 + for a in nonaction_rows: + cur = apps_c.get(a.get('id')) if isinstance(apps_c.get(a.get('id')), dict) else {} + if not cur: + continue + base_stage = norm(a.get('currentStageId')) + base_status = norm(a.get('status')) + if norm(cur.get('currentStageId')) != base_stage or norm(cur.get('status')) != base_status: + wrongly_actioned += 1 + + move_den = len(act_rows) + wrongly_actioned + move_frac = frac(move_ok, move_den) + + # --- Component 2 (0.18): decision email (exact subject) over action rows --- + email_ok = 0 + for a in act_rows: + email_ok += int(_subject_present(sent_emails, a['_offer'].get('email_subject'))) + email_frac = frac(email_ok, len(act_rows)) + + # --- Component 3 (0.10): reject reason on rejected rows --- + reason_ok = 0 + for a in reject_rows: + want = norm(a['_offer'].get('reject_reason') or '') + cur = apps_c.get(a.get('id')) if isinstance(apps_c.get(a.get('id')), dict) else {} + if want and norm(cur.get('rejectionReason')) == want: + reason_ok += 1 + reason_frac = frac(reason_ok, len(reject_rows)) + + # --- Component 4 (0.20): 'Approved Offers' sheet tab (NEW) rows == HIRE set F1 --- + gs_adapter = gs_initial.get('_task_adapter') if isinstance(gs_initial.get('_task_adapter'), dict) else {} + output_tab = gs_adapter.get('output_tab') or 'Approved Offers' + hire_key = gs_adapter.get('hire_set') if isinstance(gs_adapter.get('hire_set'), list) else [] + true_set = set() + for h in hire_key: + if isinstance(h, dict): + true_set.add((norm(h.get('name')), norm(h.get('email')), _to_salary_int(h.get('salary')))) + + initial_tabs = {norm(n) for n in _sheet_tabs(gs_initial).keys()} + current_tabs = _sheet_tabs(gs_current) + # The output tab must be NEWLY created (absent at injection, present now). + tab_is_new = norm(output_tab) in {norm(n) for n in current_tabs.keys()} \ + and norm(output_tab) not in initial_tabs + pred_set = set() + if tab_is_new: + tab_obj = None + for name, obj in current_tabs.items(): + if norm(name) == norm(output_tab): + tab_obj = obj + break + rows = tab_obj.get('rows', []) if isinstance(tab_obj, dict) else [] + for row in rows: + name = _row_get(row, 'Name') + email = _row_get(row, 'Email') + salary = _to_salary_int(_row_get(row, 'Salary')) + if not (str(name).strip() or str(email).strip()): + continue + pred_set.add((norm(name), norm(email), salary)) + sheet_frac = f1(true_set, pred_set) if true_set else 0.0 + + # --- Component 5 (0.16): NEW pinned decision note per action row --- + notes_i = [n for n in (gh_initial.get('notes') or []) if isinstance(n, dict)] + notes_c = [n for n in (gh_current.get('notes') or []) if isinstance(n, dict)] + initial_note_ids = {n.get('id') for n in notes_i} + note_ok = 0 + for a in act_rows: + dec = a['_offer'] + if not dec.get('note_required'): + continue + cand_id = a.get('candidateId') + kws = [norm(k) for k in (dec.get('note_keywords') or []) if k] + hit = False + for n in notes_c: + if n.get('candidateId') != cand_id: + continue + if n.get('id') in initial_note_ids: # not newly added + continue + if not n.get('isPinned'): # must be pinned (hidden toggle) + continue + body = norm(n.get('body')) + if kws and any(k in body for k in kws): + hit = True + break + note_ok += int(hit) + note_frac = frac(note_ok, len(act_rows)) + + # --- Component 6/7 (0.05 + 0.05): Slack #recruiting summary, pinned --- + slack = go('slack') + scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {} + s_adapter = (slack.get('initial_state') or {}).get('_task_adapter') \ + if isinstance((slack.get('initial_state') or {}).get('_task_adapter'), dict) else {} + summary_channel = s_adapter.get('summary_channel') or 'recruiting' + rec_msgs = _slack_channel_messages(scur, summary_channel) + rec_ch = None + for ch in (scur.get('channels') or []): + if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel): + rec_ch = ch + break + pinned_ids = (rec_ch.get('pinnedMessages') or []) if isinstance(rec_ch, dict) else [] + + def _is_summary(msg): + text = (_slack_msg_text(msg) or '').strip() + if not text: + return False + return has_text(text, 'offer', 'hire', 'hired', 'reject', 'approval', 'decision') \ + and bool(re.search(r'\d', text)) + + post_ok = any(_is_summary(m) for m in rec_msgs if isinstance(m, dict)) + pinned_msgs = [m for m in rec_msgs + if isinstance(m, dict) + and (m.get('messageId') or m.get('id')) in set(pinned_ids)] + pin_ok = post_ok and any(_is_summary(m) for m in pinned_msgs) + post_frac = 1.0 if post_ok else 0.0 + pin_frac = 1.0 if pin_ok else 0.0 + + s_move = 0.26 * move_frac + s_email = 0.18 * email_frac + s_reason = 0.10 * reason_frac + s_sheet = 0.20 * sheet_frac + s_note = 0.16 * note_frac + s_post = 0.05 * post_frac + s_pin = 0.05 * pin_frac + score = clamp01(s_move + s_email + s_reason + s_sheet + s_note + s_post + s_pin) + + print( + 'DEBUG_d4918cca ' + f'targets={len(targets)} hire={len(hire_rows)} reject={len(reject_rows)} ' + f'nonaction={len(nonaction_rows)} hired_stage={hired_stage_id} ' + f'move_ok={move_ok}/{len(act_rows)} wrongly_actioned={wrongly_actioned} move_den={move_den} ' + f'email={email_ok}/{len(act_rows)} reason={reason_ok}/{len(reject_rows)} ' + f'tab_new={int(tab_is_new)} true_rows={len(true_set)} pred_rows={len(pred_set)} ' + f'sheet_f1={round(sheet_frac, 4)} note={note_ok}/{len(act_rows)} ' + f'slack_post={post_ok} slack_pin={pin_ok} ' + f's_move={round(s_move, 4)} s_email={round(s_email, 4)} s_reason={round(s_reason, 4)} ' + f's_sheet={round(s_sheet, 4)} s_note={round(s_note, 4)} ' + f's_post={round(s_post, 4)} s_pin={round(s_pin, 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/sre_runbook_003/_cua_gym_vm_bridge.sh b/sre_runbook_003/_cua_gym_vm_bridge.sh new file mode 100644 index 0000000000000000000000000000000000000000..a963d4b148f239bcced094622288aebcd5b27f4c --- /dev/null +++ b/sre_runbook_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/sre_runbook_003/initial_setup.py b/sre_runbook_003/initial_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb4260ba959f4c9479a9273b2a4cd26d3959850 --- /dev/null +++ b/sre_runbook_003/initial_setup.py @@ -0,0 +1,1637 @@ +""" +Initial Setup: se_runbook_linear_b93 +Task ID: sre_runbook_003 +Domain: mock_websites +Mocks: docusign_mock, linear_mock, slack_mock (single shared sid) + +Persona: You are an office worker acting as a technical writer. Your tools for this task are: the team wiki, the Linear issue tracker, team communications. + +Environment / context (initial state + ground truth this setup establishes): +Initial environment (seeded via a single shared session id across all mocks): a team wiki with Engineering/Product spaces and pages; Linear workspace (32 issues across Engineering/Design teams); Slack workspace with channels #general, #engineering, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: new pool-exhaustion runbook page (+0.3); runbook body has concrete remediation (pool + pgbouncer) (+0.25); ENG-6 moved to In Review (+0.25); slack_new_msg (+0.1); Slack names ENG-6 (+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 = { + "docusign_mock": "http://28.7.184.198:8130", + "linear_mock": "http://28.7.184.198:8156", + "slack_mock": "http://28.7.184.198:8178" +} +PRIMARY_URL = 'http://28.7.184.198:8130' + +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 = { 'docusign_mock': { 'users': [ { 'id': 'user-1', + 'username': 'admin', + 'displayName': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=user1'}, + { 'id': 'user-2', + 'username': 'alice', + 'displayName': 'Alice Engineer', + 'email': 'alice@example.com', + 'avatar': 'https://picsum.photos/100/100?random=user2'}, + { 'id': 'user-3', + 'username': 'bob', + 'displayName': 'Bob Manager', + 'email': 'bob@example.com', + 'avatar': 'https://picsum.photos/100/100?random=user3'}], + 'currentUser': { 'id': 'user-1', + 'username': 'admin', + 'displayName': 'Admin User', + 'email': 'admin@example.com', + 'avatar': 'https://picsum.photos/100/100?random=user1'}, + 'spaces': [ { 'id': 'space-1', + 'key': 'ENG', + 'name': 'Engineering', + 'description': 'Technical documentation and engineering ' + 'processes.', + 'icon': 'Code'}, + { 'id': 'space-2', + 'key': 'HR', + 'name': 'Human Resources', + 'description': 'Company policies, onboarding, and ' + 'benefits.', + 'icon': 'Users'}], + 'pages': [ { 'id': 'page-1', + 'spaceId': 'space-1', + 'parentId': None, + 'title': 'Engineering Home', + 'content': '

Welcome to Engineering

This is ' + 'the home of the engineering team.

', + 'authorId': 'user-1', + 'created': '2026-06-08T09:54:16.376Z', + 'updated': '2026-06-08T09:54:16.376Z', + 'version': 1, + 'labels': ['home', 'engineering']}, + { 'id': 'page-2', + 'spaceId': 'space-1', + 'parentId': 'page-1', + 'title': 'Development Guidelines', + 'content': '

Coding Standards

Please follow ' + 'these guidelines...

', + 'authorId': 'user-2', + 'created': '2026-06-08T09:54:16.376Z', + 'updated': '2026-06-08T09:54:16.376Z', + 'version': 1, + 'labels': ['guidelines']}, + { 'id': 'page-3', + 'spaceId': 'space-2', + 'parentId': None, + 'title': 'HR Home', + 'content': '

HR Portal

Welcome to the employee ' + 'portal.

', + 'authorId': 'user-3', + 'created': '2026-06-08T09:54:16.376Z', + 'updated': '2026-06-08T09:54:16.376Z', + 'version': 1, + 'labels': ['hr', 'home']}], + 'comments': [ { 'id': 'comment-1', + 'pageId': 'page-1', + 'userId': 'user-2', + 'content': 'Great start to the documentation!', + 'created': '2026-06-08T09:54:16.376Z'}], + 'versions': [ { 'id': 'v-1', + 'pageId': 'page-1', + 'content': '

Welcome to Engineering

Initial ' + 'draft.

', + 'authorId': 'user-1', + 'created': '2026-06-08T09:54:16.376Z', + 'version': 0}], + 'templates': [ { 'id': 't-1', + 'name': 'Meeting Notes', + 'content': '

Meeting ' + 'Notes

Date
Attendees

Agenda

'}, + { 'id': 't-2', + 'name': 'Project Plan', + 'content': '

Project ' + 'Plan

Overview

Project ' + 'goals...

Timeline

Q1...

'}]}, + 'linear_mock': { 'currentUserId': 'u1', + 'workspace': {'id': 'w1', 'name': 'Acme Corp', 'urlKey': 'acme'}, + 'users': [ { 'id': 'u1', + 'name': 'Alex Morgan', + 'email': 'alex@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u1', + 'displayName': 'Alex', + 'role': 'Admin', + 'active': True}, + { 'id': 'u2', + 'name': 'Jamie Chen', + 'email': 'jamie@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u2', + 'displayName': 'Jamie', + 'role': 'Member', + 'active': True}, + { 'id': 'u3', + 'name': 'Sam Patel', + 'email': 'sam@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u3', + 'displayName': 'Sam', + 'role': 'Member', + 'active': True}, + { 'id': 'u4', + 'name': 'Taylor Kim', + 'email': 'taylor@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u4', + 'displayName': 'Taylor', + 'role': 'Member', + 'active': True}, + { 'id': 'u5', + 'name': 'Jordan Lee', + 'email': 'jordan@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u5', + 'displayName': 'Jordan', + 'role': 'Member', + 'active': True}, + { 'id': 'u6', + 'name': 'Riley Zhang', + 'email': 'riley@acmecorp.com', + 'avatarUrl': 'https://i.pravatar.cc/150?u=u6', + 'displayName': 'Riley', + 'role': 'Guest', + 'active': True}], + 'teams': [ { 'id': 't1', + 'name': 'Engineering', + 'key': 'ENG', + 'icon': '⚙️', + 'color': '#5e6ad2', + 'memberIds': ['u1', 'u2', 'u3', 'u4'], + 'workflowStates': [ { 'id': 'ws_eng_triage', + 'name': 'Triage', + 'category': 'triage', + 'color': '#8a8f98', + 'position': 0, + 'teamId': 't1'}, + { 'id': 'ws_eng_backlog', + 'name': 'Backlog', + 'category': 'backlog', + 'color': '#8a8f98', + 'position': 1, + 'teamId': 't1'}, + { 'id': 'ws_eng_todo', + 'name': 'Todo', + 'category': 'unstarted', + 'color': '#e2e2e3', + 'position': 2, + 'teamId': 't1'}, + { 'id': 'ws_eng_in_progress', + 'name': 'In Progress', + 'category': 'started', + 'color': '#f2c94c', + 'position': 3, + 'teamId': 't1'}, + { 'id': 'ws_eng_in_review', + 'name': 'In Review', + 'category': 'started', + 'color': '#5e6ad2', + 'position': 4, + 'teamId': 't1'}, + { 'id': 'ws_eng_done', + 'name': 'Done', + 'category': 'completed', + 'color': '#27a644', + 'position': 5, + 'teamId': 't1'}, + { 'id': 'ws_eng_canceled', + 'name': 'Canceled', + 'category': 'canceled', + 'color': '#8a8f98', + 'position': 6, + 'teamId': 't1'}], + 'triageEnabled': True, + 'cycleEnabled': True, + 'cycleDuration': 2, + 'activeCycleId': 'c1'}, + { 'id': 't2', + 'name': 'Design', + 'key': 'DES', + 'icon': '🎨', + 'color': '#e5484d', + 'memberIds': ['u1', 'u4', 'u5'], + 'workflowStates': [ { 'id': 'ws_des_triage', + 'name': 'Triage', + 'category': 'triage', + 'color': '#8a8f98', + 'position': 0, + 'teamId': 't2'}, + { 'id': 'ws_des_backlog', + 'name': 'Backlog', + 'category': 'backlog', + 'color': '#8a8f98', + 'position': 1, + 'teamId': 't2'}, + { 'id': 'ws_des_todo', + 'name': 'Todo', + 'category': 'unstarted', + 'color': '#e2e2e3', + 'position': 2, + 'teamId': 't2'}, + { 'id': 'ws_des_in_progress', + 'name': 'In Progress', + 'category': 'started', + 'color': '#f2c94c', + 'position': 3, + 'teamId': 't2'}, + { 'id': 'ws_des_in_review', + 'name': 'In Review', + 'category': 'started', + 'color': '#5e6ad2', + 'position': 4, + 'teamId': 't2'}, + { 'id': 'ws_des_done', + 'name': 'Done', + 'category': 'completed', + 'color': '#27a644', + 'position': 5, + 'teamId': 't2'}, + { 'id': 'ws_des_canceled', + 'name': 'Canceled', + 'category': 'canceled', + 'color': '#8a8f98', + 'position': 6, + 'teamId': 't2'}], + 'triageEnabled': False, + 'cycleEnabled': True, + 'cycleDuration': 1, + 'activeCycleId': 'c4'}], + 'issues': [ { 'id': 'i1', + 'identifier': 'ENG-1', + 'number': 1, + 'title': 'Set up CI/CD pipeline for staging environment', + 'description': 'Configure GitHub Actions to deploy to ' + 'staging on merge to develop branch.\n' + '\n' + '**Acceptance Criteria:**\n' + '- Pipeline triggers on push to develop\n' + '- Runs tests before deploy\n' + '- Sends Slack notification on failure', + 'stateId': 'ws_eng_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u3', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l8'], + 'parentId': None, + 'dueDate': '2026-04-18', + 'subscriberIds': ['u1', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-28T10:00:00Z', + 'updatedAt': '2026-04-09T14:30:00Z', + 'completedAt': None, + 'sortOrder': 100}, + { 'id': 'i2', + 'identifier': 'ENG-2', + 'number': 2, + 'title': 'Fix authentication token refresh race condition', + 'description': 'There is a race condition when multiple ' + 'requests try to refresh the auth token ' + 'simultaneously, causing some requests to ' + 'fail with 401.\n' + '\n' + '**Steps to reproduce:**\n' + '1. Open multiple tabs\n' + '2. Let token expire\n' + '3. Perform simultaneous actions', + 'stateId': 'ws_eng_in_progress', + 'priority': 1, + 'estimate': 3, + 'assigneeId': 'u1', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l1', 'l7'], + 'parentId': None, + 'dueDate': '2026-04-12', + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-29T09:00:00Z', + 'updatedAt': '2026-04-10T09:00:00Z', + 'completedAt': None, + 'sortOrder': 110}, + { 'id': 'i3', + 'identifier': 'ENG-3', + 'number': 3, + 'title': 'Implement user avatar upload endpoint', + 'description': 'Add a POST /api/users/avatar endpoint ' + 'that accepts image files and stores them ' + 'in S3.', + 'stateId': 'ws_eng_todo', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u2', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l2'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-30T11:00:00Z', + 'updatedAt': '2026-04-07T10:00:00Z', + 'completedAt': None, + 'sortOrder': 120}, + { 'id': 'i4', + 'identifier': 'ENG-4', + 'number': 4, + 'title': 'Update API error response format to RFC 7807', + 'description': 'Standardize all API error responses to ' + 'use Problem Details format as defined in ' + 'RFC 7807.', + 'stateId': 'ws_eng_todo', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l3'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-31T08:00:00Z', + 'updatedAt': '2026-04-06T15:00:00Z', + 'completedAt': None, + 'sortOrder': 130}, + { 'id': 'i5', + 'identifier': 'ENG-5', + 'number': 5, + 'title': 'Add rate limiting to public API endpoints', + 'description': 'Implement rate limiting using Redis to ' + 'prevent API abuse. Limits: 100 req/min ' + 'per IP for unauthenticated, 1000 req/min ' + 'for authenticated.', + 'stateId': 'ws_eng_todo', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u3', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l7', 'l8'], + 'parentId': None, + 'dueDate': '2026-04-15', + 'subscriberIds': ['u1', 'u3'], + 'relationIds': [], + 'createdAt': '2026-04-01T09:00:00Z', + 'updatedAt': '2026-04-08T11:00:00Z', + 'completedAt': None, + 'sortOrder': 140}, + { 'id': 'i6', + 'identifier': 'ENG-6', + 'number': 6, + 'title': 'Refactor database connection pooling', + 'description': 'Current connection pool configuration is ' + 'causing connection exhaustion under load. ' + 'Need to tune pool size and implement ' + 'proper connection lifecycle management.', + 'stateId': 'ws_eng_in_progress', + 'priority': 2, + 'estimate': 8, + 'assigneeId': 'u1', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c1', + 'labelIds': ['l6', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-25T14:00:00Z', + 'updatedAt': '2026-04-10T08:00:00Z', + 'completedAt': None, + 'sortOrder': 150}, + { 'id': 'i7', + 'identifier': 'ENG-7', + 'number': 7, + 'title': 'Write integration tests for payment flow', + 'description': 'Create comprehensive integration tests ' + 'covering the complete payment flow from ' + 'cart to confirmation.', + 'stateId': 'ws_eng_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u2', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l5'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-04-02T10:00:00Z', + 'updatedAt': '2026-04-09T16:00:00Z', + 'completedAt': None, + 'sortOrder': 160}, + { 'id': 'i8', + 'identifier': 'ENG-8', + 'number': 8, + 'title': 'Fix mobile viewport breakpoint inconsistencies', + 'description': 'Several UI components render incorrectly ' + 'on mobile screen sizes. Fixed breakpoints ' + 'to use consistent values.', + 'stateId': 'ws_eng_done', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l1'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-03T09:00:00Z', + 'updatedAt': '2026-04-08T17:00:00Z', + 'completedAt': '2026-04-08T17:00:00Z', + 'sortOrder': 170}, + { 'id': 'i9', + 'identifier': 'ENG-9', + 'number': 9, + 'title': 'Add dark mode support to settings page', + 'description': 'Settings page is missing dark mode ' + 'styles. Should use the same color system ' + 'as the rest of the app.', + 'stateId': 'ws_eng_done', + 'priority': 4, + 'estimate': 3, + 'assigneeId': 'u1', + 'creatorId': 'u4', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l2', 'l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-04T11:00:00Z', + 'updatedAt': '2026-04-09T10:00:00Z', + 'completedAt': '2026-04-09T10:00:00Z', + 'sortOrder': 180}, + { 'id': 'i10', + 'identifier': 'ENG-10', + 'number': 10, + 'title': 'Optimize image lazy loading performance', + 'description': 'Implement Intersection Observer-based ' + 'lazy loading for all product images to ' + 'improve initial page load time.', + 'stateId': 'ws_eng_in_progress', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u3', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c1', + 'labelIds': ['l6'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u2', 'u3'], + 'relationIds': [], + 'createdAt': '2026-04-05T09:00:00Z', + 'updatedAt': '2026-04-10T10:00:00Z', + 'completedAt': None, + 'sortOrder': 190}, + { 'id': 'i11', + 'identifier': 'ENG-11', + 'number': 11, + 'title': 'Implement WebSocket reconnection logic', + 'description': 'WebSocket connections drop silently when ' + 'network is interrupted. Need exponential ' + 'backoff reconnect logic.', + 'stateId': 'ws_eng_backlog', + 'priority': 2, + 'estimate': 5, + 'assigneeId': None, + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l2', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-20T10:00:00Z', + 'updatedAt': '2026-03-20T10:00:00Z', + 'completedAt': None, + 'sortOrder': 200}, + { 'id': 'i12', + 'identifier': 'ENG-12', + 'number': 12, + 'title': 'Add CSV export for analytics dashboard', + 'description': 'Users need ability to export analytics ' + 'data as CSV for external reporting.', + 'stateId': 'ws_eng_backlog', + 'priority': 4, + 'estimate': 3, + 'assigneeId': None, + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l2'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3'], + 'relationIds': [], + 'createdAt': '2026-03-22T14:00:00Z', + 'updatedAt': '2026-03-22T14:00:00Z', + 'completedAt': None, + 'sortOrder': 210}, + { 'id': 'i13', + 'identifier': 'ENG-13', + 'number': 13, + 'title': 'Migrate user preferences to new schema', + 'description': 'User preference storage needs to be ' + 'migrated from legacy JSON blob to ' + 'properly normalized schema.', + 'stateId': 'ws_eng_backlog', + 'priority': 3, + 'estimate': 5, + 'assigneeId': 'u2', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l3'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-23T09:00:00Z', + 'updatedAt': '2026-03-23T09:00:00Z', + 'completedAt': None, + 'sortOrder': 220}, + { 'id': 'i14', + 'identifier': 'ENG-14', + 'number': 14, + 'title': 'Create API documentation with OpenAPI spec', + 'description': 'Write comprehensive OpenAPI 3.0 spec for ' + 'all public API endpoints, including ' + 'request/response schemas and examples.', + 'stateId': 'ws_eng_backlog', + 'priority': 3, + 'estimate': 8, + 'assigneeId': None, + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l5'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u2'], + 'relationIds': [], + 'createdAt': '2026-03-24T11:00:00Z', + 'updatedAt': '2026-03-24T11:00:00Z', + 'completedAt': None, + 'sortOrder': 230}, + { 'id': 'i15', + 'identifier': 'ENG-15', + 'number': 15, + 'title': 'Fix memory leak in real-time notification ' + 'service', + 'description': 'Notification service has a memory leak ' + 'causing server restarts every ~48 hours. ' + 'Profiling shows event listeners are not ' + 'being cleaned up.', + 'stateId': 'ws_eng_backlog', + 'priority': 1, + 'estimate': 5, + 'assigneeId': 'u3', + 'creatorId': 'u4', + 'teamId': 't1', + 'projectId': None, + 'cycleId': None, + 'labelIds': ['l1', 'l6'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3', 'u4'], + 'relationIds': [], + 'createdAt': '2026-03-26T15:00:00Z', + 'updatedAt': '2026-03-26T15:00:00Z', + 'completedAt': None, + 'sortOrder': 240}, + { 'id': 'i16', + 'identifier': 'ENG-16', + 'number': 16, + 'title': 'Add end-to-end encryption for file uploads', + 'description': 'Implement client-side encryption before ' + 'upload and decryption on download for ' + 'sensitive file attachments.', + 'stateId': 'ws_eng_backlog', + 'priority': 2, + 'estimate': 13, + 'assigneeId': None, + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': None, + 'cycleId': None, + 'labelIds': ['l7'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-27T09:00:00Z', + 'updatedAt': '2026-03-27T09:00:00Z', + 'completedAt': None, + 'sortOrder': 250}, + { 'id': 'i17', + 'identifier': 'ENG-17', + 'number': 17, + 'title': 'Set up error monitoring with Sentry integration', + 'description': 'Integrate Sentry for error tracking and ' + 'performance monitoring in both frontend ' + 'and backend services.', + 'stateId': 'ws_eng_backlog', + 'priority': 3, + 'estimate': 3, + 'assigneeId': None, + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': None, + 'labelIds': ['l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u3'], + 'relationIds': [], + 'createdAt': '2026-03-28T10:00:00Z', + 'updatedAt': '2026-03-28T10:00:00Z', + 'completedAt': None, + 'sortOrder': 260}, + { 'id': 'i18', + 'identifier': 'ENG-18', + 'number': 18, + 'title': 'Design new landing page layout', + 'description': 'Create the new homepage design with ' + 'improved hero section, feature ' + 'highlights, and social proof.', + 'stateId': 'ws_eng_done', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u4', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': 'c2', + 'labelIds': ['l2', 'l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u4'], + 'relationIds': [], + 'createdAt': '2026-03-10T09:00:00Z', + 'updatedAt': '2026-03-28T16:00:00Z', + 'completedAt': '2026-03-28T16:00:00Z', + 'sortOrder': 270}, + { 'id': 'i19', + 'identifier': 'ENG-19', + 'number': 19, + 'title': 'Implement search indexing service', + 'description': 'Set up Elasticsearch to index all issue ' + 'content for full-text search ' + 'capabilities.', + 'stateId': 'ws_eng_done', + 'priority': 1, + 'estimate': 8, + 'assigneeId': 'u1', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': ['l2', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u2'], + 'relationIds': [], + 'createdAt': '2026-03-12T10:00:00Z', + 'updatedAt': '2026-03-29T14:00:00Z', + 'completedAt': '2026-03-29T14:00:00Z', + 'sortOrder': 280}, + { 'id': 'i20', + 'identifier': 'ENG-20', + 'number': 20, + 'title': 'Fix pagination cursor bug in API', + 'description': 'Cursor-based pagination returns incorrect ' + 'results when sorting by non-unique ' + 'fields.', + 'stateId': 'ws_eng_done', + 'priority': 2, + 'estimate': 3, + 'assigneeId': 'u2', + 'creatorId': 'u3', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': ['l1'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u2', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-14T11:00:00Z', + 'updatedAt': '2026-03-27T15:00:00Z', + 'completedAt': '2026-03-27T15:00:00Z', + 'sortOrder': 290}, + { 'id': 'i21', + 'identifier': 'ENG-21', + 'number': 21, + 'title': 'Add request logging middleware', + 'description': 'Implement structured logging middleware ' + 'that captures request/response details, ' + 'timing, and error information.', + 'stateId': 'ws_eng_done', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u3', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': ['l5', 'l8'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u3'], + 'relationIds': [], + 'createdAt': '2026-03-16T09:00:00Z', + 'updatedAt': '2026-03-26T12:00:00Z', + 'completedAt': '2026-03-26T12:00:00Z', + 'sortOrder': 300}, + { 'id': 'i22', + 'identifier': 'ENG-22', + 'number': 22, + 'title': 'Remove deprecated v1 API routes', + 'description': 'Clean up legacy v1 API routes that are no ' + 'longer used. Migration guide has been ' + 'published.', + 'stateId': 'ws_eng_canceled', + 'priority': 4, + 'estimate': None, + 'assigneeId': 'u1', + 'creatorId': 'u1', + 'teamId': 't1', + 'projectId': 'p2', + 'cycleId': 'c2', + 'labelIds': [], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1'], + 'relationIds': [], + 'createdAt': '2026-03-18T10:00:00Z', + 'updatedAt': '2026-03-25T09:00:00Z', + 'completedAt': '2026-03-25T09:00:00Z', + 'sortOrder': 310}, + { 'id': 'i23', + 'identifier': 'DES-1', + 'number': 1, + 'title': 'Design onboarding flow mockups', + 'description': 'Create high-fidelity mockups for the new ' + 'user onboarding experience, covering ' + 'account setup, team invitation, and first ' + 'issue creation.', + 'stateId': 'ws_des_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u5', + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u4', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-07T09:00:00Z', + 'updatedAt': '2026-04-10T11:00:00Z', + 'completedAt': None, + 'sortOrder': 100}, + { 'id': 'i24', + 'identifier': 'DES-2', + 'number': 2, + 'title': 'Create component library documentation', + 'description': 'Document all UI components in Storybook ' + 'with usage examples, prop descriptions, ' + 'and accessibility notes.', + 'stateId': 'ws_des_todo', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u4', + 'creatorId': 'u5', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l5'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-07T10:00:00Z', + 'updatedAt': '2026-04-07T10:00:00Z', + 'completedAt': None, + 'sortOrder': 110}, + { 'id': 'i25', + 'identifier': 'DES-3', + 'number': 3, + 'title': 'Redesign notification center UI', + 'description': 'The current notification center is ' + 'cluttered and hard to scan. Design a ' + 'cleaner, more focused inbox experience.', + 'stateId': 'ws_des_in_progress', + 'priority': 2, + 'estimate': 5, + 'assigneeId': 'u5', + 'creatorId': 'u1', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l2', 'l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-08T09:00:00Z', + 'updatedAt': '2026-04-10T14:00:00Z', + 'completedAt': None, + 'sortOrder': 120}, + { 'id': 'i26', + 'identifier': 'DES-4', + 'number': 4, + 'title': 'Audit accessibility compliance (WCAG 2.1)', + 'description': 'Conduct full accessibility audit of the ' + 'application against WCAG 2.1 AA ' + 'standards. Document all failures and ' + 'create remediation plan.', + 'stateId': 'ws_des_todo', + 'priority': 1, + 'estimate': 8, + 'assigneeId': 'u1', + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': 'c4', + 'labelIds': ['l3'], + 'parentId': None, + 'dueDate': '2026-04-13', + 'subscriberIds': ['u1', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-08T11:00:00Z', + 'updatedAt': '2026-04-08T11:00:00Z', + 'completedAt': None, + 'sortOrder': 130}, + { 'id': 'i27', + 'identifier': 'DES-5', + 'number': 5, + 'title': 'Design mobile app icon and splash screen', + 'description': 'Create app icon following Apple and ' + 'Google guidelines, plus splash screen ' + 'animations.', + 'stateId': 'ws_des_done', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u5', + 'teamId': 't2', + 'projectId': 'p3', + 'cycleId': 'c4', + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4', 'u5'], + 'relationIds': [], + 'createdAt': '2026-04-07T14:00:00Z', + 'updatedAt': '2026-04-09T17:00:00Z', + 'completedAt': '2026-04-09T17:00:00Z', + 'sortOrder': 140}, + { 'id': 'i28', + 'identifier': 'DES-6', + 'number': 6, + 'title': 'Create illustration set for empty states', + 'description': 'Design a cohesive set of illustrations ' + 'for all empty state screens in the ' + 'application.', + 'stateId': 'ws_des_backlog', + 'priority': 4, + 'estimate': None, + 'assigneeId': None, + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4'], + 'relationIds': [], + 'createdAt': '2026-03-25T10:00:00Z', + 'updatedAt': '2026-03-25T10:00:00Z', + 'completedAt': None, + 'sortOrder': 200}, + { 'id': 'i29', + 'identifier': 'DES-7', + 'number': 7, + 'title': 'Design dark mode color palette variants', + 'description': 'Expand the design system to include dark ' + 'mode variants for all semantic colors.', + 'stateId': 'ws_des_backlog', + 'priority': 3, + 'estimate': None, + 'assigneeId': 'u5', + 'creatorId': 'u1', + 'teamId': 't2', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l4'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u1', 'u5'], + 'relationIds': [], + 'createdAt': '2026-03-26T09:00:00Z', + 'updatedAt': '2026-03-26T09:00:00Z', + 'completedAt': None, + 'sortOrder': 210}, + { 'id': 'i30', + 'identifier': 'DES-8', + 'number': 8, + 'title': 'Prototype interactive data visualization', + 'description': 'Build an interactive prototype of the new ' + 'analytics dashboard with filterable ' + 'charts.', + 'stateId': 'ws_des_backlog', + 'priority': 3, + 'estimate': None, + 'assigneeId': None, + 'creatorId': 'u4', + 'teamId': 't2', + 'projectId': 'p3', + 'cycleId': None, + 'labelIds': ['l2'], + 'parentId': None, + 'dueDate': None, + 'subscriberIds': ['u4'], + 'relationIds': [], + 'createdAt': '2026-03-28T11:00:00Z', + 'updatedAt': '2026-03-28T11:00:00Z', + 'completedAt': None, + 'sortOrder': 220}, + { 'id': 'i31', + 'identifier': 'ENG-23', + 'number': 23, + 'title': 'Design avatar upload UI component', + 'description': 'Create the modal dialog and drag-and-drop ' + 'area for avatar uploads.', + 'stateId': 'ws_eng_todo', + 'priority': 3, + 'estimate': 2, + 'assigneeId': 'u4', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l4'], + 'parentId': 'i3', + 'dueDate': None, + 'subscriberIds': ['u2', 'u4'], + 'relationIds': [], + 'createdAt': '2026-04-05T10:00:00Z', + 'updatedAt': '2026-04-05T10:00:00Z', + 'completedAt': None, + 'sortOrder': 320}, + { 'id': 'i32', + 'identifier': 'ENG-24', + 'number': 24, + 'title': 'Implement S3 upload service', + 'description': 'Build the backend service for handling ' + 'multipart uploads to S3 with presigned ' + 'URLs.', + 'stateId': 'ws_eng_in_progress', + 'priority': 3, + 'estimate': 3, + 'assigneeId': 'u2', + 'creatorId': 'u2', + 'teamId': 't1', + 'projectId': 'p1', + 'cycleId': None, + 'labelIds': ['l8'], + 'parentId': 'i3', + 'dueDate': None, + 'subscriberIds': ['u2'], + 'relationIds': [], + 'createdAt': '2026-04-05T10:30:00Z', + 'updatedAt': '2026-04-09T11:00:00Z', + 'completedAt': None, + 'sortOrder': 330}], + 'labels': [ { 'id': 'l1', + 'name': 'Bug', + 'color': '#eb5757', + 'teamId': None}, + { 'id': 'l2', + 'name': 'Feature', + 'color': '#5e6ad2', + 'teamId': None}, + { 'id': 'l3', + 'name': 'Improvement', + 'color': '#27a644', + 'teamId': None}, + { 'id': 'l4', + 'name': 'Design', + 'color': '#f2994a', + 'teamId': None}, + { 'id': 'l5', + 'name': 'Documentation', + 'color': '#8a8f98', + 'teamId': None}, + { 'id': 'l6', + 'name': 'Performance', + 'color': '#bb6bd9', + 'teamId': None}, + { 'id': 'l7', + 'name': 'Security', + 'color': '#e5484d', + 'teamId': None}, + { 'id': 'l8', + 'name': 'Infrastructure', + 'color': '#56b4be', + 'teamId': None}], + 'projects': [ { 'id': 'p1', + 'name': 'Website Redesign', + 'description': 'Complete overhaul of the marketing ' + 'website with new brand identity and ' + 'improved performance.', + 'icon': '🌐', + 'color': '#5e6ad2', + 'status': 'started', + 'health': 'onTrack', + 'leadId': 'u1', + 'memberIds': ['u1', 'u2', 'u4', 'u5'], + 'teamIds': ['t1', 't2'], + 'targetDate': '2026-05-31', + 'startDate': '2026-03-01', + 'progress': 65, + 'createdAt': '2026-03-01T09:00:00Z', + 'updatedAt': '2026-04-09T14:00:00Z'}, + { 'id': 'p2', + 'name': 'API v2 Migration', + 'description': 'Migrate all public API endpoints to v2 ' + 'with improved authentication and error ' + 'handling.', + 'icon': '🔌', + 'color': '#f2994a', + 'status': 'started', + 'health': 'atRisk', + 'leadId': 'u2', + 'memberIds': ['u1', 'u2', 'u3'], + 'teamIds': ['t1'], + 'targetDate': '2026-04-30', + 'startDate': '2026-02-15', + 'progress': 30, + 'createdAt': '2026-02-15T09:00:00Z', + 'updatedAt': '2026-04-08T11:00:00Z'}, + { 'id': 'p3', + 'name': 'Mobile App Launch', + 'description': 'Design and development of the companion ' + 'mobile app for iOS and Android.', + 'icon': '📱', + 'color': '#27a644', + 'status': 'planned', + 'health': None, + 'leadId': 'u4', + 'memberIds': ['u4', 'u5'], + 'teamIds': ['t2'], + 'targetDate': '2026-07-31', + 'startDate': '2026-05-01', + 'progress': 0, + 'createdAt': '2026-04-01T09:00:00Z', + 'updatedAt': '2026-04-01T09:00:00Z'}], + 'cycles': [ { 'id': 'c1', + 'number': 5, + 'name': 'Cycle 5', + 'teamId': 't1', + 'startsAt': '2026-03-31', + 'endsAt': '2026-04-13', + 'isActive': True, + 'isCompleted': False, + 'progress': 20}, + { 'id': 'c2', + 'number': 4, + 'name': 'Cycle 4', + 'teamId': 't1', + 'startsAt': '2026-03-17', + 'endsAt': '2026-03-30', + 'isActive': False, + 'isCompleted': True, + 'progress': 100}, + { 'id': 'c3', + 'number': 6, + 'name': 'Cycle 6', + 'teamId': 't1', + 'startsAt': '2026-04-14', + 'endsAt': '2026-04-27', + 'isActive': False, + 'isCompleted': False, + 'progress': 0}, + { 'id': 'c4', + 'number': 3, + 'name': 'Cycle 3', + 'teamId': 't2', + 'startsAt': '2026-04-07', + 'endsAt': '2026-04-13', + 'isActive': True, + 'isCompleted': False, + 'progress': 20}], + 'comments': [ { 'id': 'cm1', + 'body': "I've started working on this. The GitHub " + 'Actions workflow is configured and should be ' + 'ready for review by EOD.', + 'issueId': 'i1', + 'userId': 'u3', + 'createdAt': '2026-04-08T10:00:00Z', + 'updatedAt': '2026-04-08T10:00:00Z', + 'parentId': None}, + { 'id': 'cm2', + 'body': 'Looks good! Make sure to add the Slack webhook ' + 'secret to the environment variables.', + 'issueId': 'i1', + 'userId': 'u1', + 'createdAt': '2026-04-08T11:30:00Z', + 'updatedAt': '2026-04-08T11:30:00Z', + 'parentId': None}, + { 'id': 'cm3', + 'body': 'Done, added it to the secrets manager. The ' + 'pipeline is green now.', + 'issueId': 'i1', + 'userId': 'u3', + 'createdAt': '2026-04-08T14:00:00Z', + 'updatedAt': '2026-04-08T14:00:00Z', + 'parentId': 'cm2'}, + { 'id': 'cm4', + 'body': 'I reproduced the race condition. It happens ' + 'when the token expires within the same 100ms ' + 'window as multiple fetch calls. We need to ' + 'implement a mutex or queue mechanism.', + 'issueId': 'i2', + 'userId': 'u1', + 'createdAt': '2026-04-09T09:30:00Z', + 'updatedAt': '2026-04-09T09:30:00Z', + 'parentId': None}, + { 'id': 'cm5', + 'body': 'Could we use a refresh promise singleton ' + 'pattern? That way concurrent refreshes share ' + 'the same promise.', + 'issueId': 'i2', + 'userId': 'u2', + 'createdAt': '2026-04-09T10:15:00Z', + 'updatedAt': '2026-04-09T10:15:00Z', + 'parentId': None}, + { 'id': 'cm6', + 'body': "Yes, that's the plan. I'll implement that " + 'approach.', + 'issueId': 'i2', + 'userId': 'u1', + 'createdAt': '2026-04-09T10:45:00Z', + 'updatedAt': '2026-04-09T10:45:00Z', + 'parentId': 'cm5'}, + { 'id': 'cm7', + 'body': 'Code review complete. The PR looks solid ' + 'overall. A few minor comments:\n' + '1. The pool size should be configurable via ' + 'env var\n' + '2. Add connection timeout handling\n' + '3. The error logging format could be more ' + 'structured', + 'issueId': 'i6', + 'userId': 'u2', + 'createdAt': '2026-04-09T14:00:00Z', + 'updatedAt': '2026-04-09T14:00:00Z', + 'parentId': None}, + { 'id': 'cm8', + 'body': 'All feedback addressed. Pool size is now ' + 'configurable with `DB_POOL_SIZE` env var.', + 'issueId': 'i6', + 'userId': 'u1', + 'createdAt': '2026-04-10T08:30:00Z', + 'updatedAt': '2026-04-10T08:30:00Z', + 'parentId': None}, + { 'id': 'cm9', + 'body': 'Payment flow tests are at 85% coverage. ' + 'Remaining 15% is edge cases around declined ' + 'cards and network timeouts.', + 'issueId': 'i7', + 'userId': 'u2', + 'createdAt': '2026-04-09T16:00:00Z', + 'updatedAt': '2026-04-09T16:00:00Z', + 'parentId': None}, + { 'id': 'cm10', + 'body': 'Great progress! Make sure to include a test ' + 'for the 3D Secure redirect flow.', + 'issueId': 'i7', + 'userId': 'u1', + 'createdAt': '2026-04-09T16:45:00Z', + 'updatedAt': '2026-04-09T16:45:00Z', + 'parentId': None}, + { 'id': 'cm11', + 'body': 'This is blocking the launch of the mobile ' + 'responsive design. Can we prioritize it?', + 'issueId': 'i5', + 'userId': 'u3', + 'createdAt': '2026-04-08T09:00:00Z', + 'updatedAt': '2026-04-08T09:00:00Z', + 'parentId': None}, + { 'id': 'cm12', + 'body': 'Agreed, adding to the current cycle. @u3 can ' + 'you pair with @u4 on this?', + 'issueId': 'i5', + 'userId': 'u1', + 'createdAt': '2026-04-08T09:30:00Z', + 'updatedAt': '2026-04-08T09:30:00Z', + 'parentId': None}, + { 'id': 'cm13', + 'body': 'The onboarding mockups are taking shape! ' + 'Initial screens are in Figma. Would love ' + 'feedback from the eng team on feasibility.', + 'issueId': 'i23', + 'userId': 'u5', + 'createdAt': '2026-04-09T11:00:00Z', + 'updatedAt': '2026-04-09T11:00:00Z', + 'parentId': None}, + { 'id': 'cm14', + 'body': 'The animation on the welcome screen might be ' + "tricky with our current setup. Let's discuss " + "in tomorrow's sync.", + 'issueId': 'i23', + 'userId': 'u1', + 'createdAt': '2026-04-09T14:30:00Z', + 'updatedAt': '2026-04-09T14:30:00Z', + 'parentId': None}, + { 'id': 'cm15', + 'body': 'The notification redesign looks great! Much ' + 'cleaner than the current version. One ' + 'suggestion: add a "Mark all as read" button at ' + 'the top.', + 'issueId': 'i25', + 'userId': 'u1', + 'createdAt': '2026-04-10T09:00:00Z', + 'updatedAt': '2026-04-10T09:00:00Z', + 'parentId': None}, + { 'id': 'cm16', + 'body': 'Good call! Added that to the designs. Also ' + 'thinking about adding swipe gestures for ' + 'mobile.', + 'issueId': 'i25', + 'userId': 'u5', + 'createdAt': '2026-04-10T10:30:00Z', + 'updatedAt': '2026-04-10T10:30:00Z', + 'parentId': None}, + { 'id': 'cm17', + 'body': 'The performance numbers are looking promising. ' + 'Initial LCP improved by 35% with lazy loading.', + 'issueId': 'i10', + 'userId': 'u3', + 'createdAt': '2026-04-10T10:00:00Z', + 'updatedAt': '2026-04-10T10:00:00Z', + 'parentId': None}], + 'notifications': [ { 'id': 'n1', + 'type': 'issue_assigned', + 'actorId': 'u2', + 'issueId': 'i2', + 'projectId': None, + 'title': 'Jamie Chen assigned you to ENG-2', + 'body': 'Fix authentication token refresh race ' + 'condition', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-10T09:00:00Z'}, + { 'id': 'n2', + 'type': 'comment', + 'actorId': 'u3', + 'issueId': 'i1', + 'projectId': None, + 'title': 'Sam Patel commented on ENG-1', + 'body': 'Done, added it to the secrets manager. ' + 'The pipeline is green now.', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T14:00:00Z'}, + { 'id': 'n3', + 'type': 'issue_mention', + 'actorId': 'u1', + 'issueId': 'i5', + 'projectId': None, + 'title': 'Alex Morgan mentioned you in ENG-5', + 'body': 'can you pair with @u3 on this?', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T09:30:00Z'}, + { 'id': 'n4', + 'type': 'issue_status_changed', + 'actorId': 'u4', + 'issueId': 'i8', + 'projectId': None, + 'title': 'ENG-8 moved to Done', + 'body': 'Taylor Kim moved Fix mobile viewport ' + 'breakpoint inconsistencies to Done', + 'isRead': False, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T17:00:00Z'}, + { 'id': 'n5', + 'type': 'comment', + 'actorId': 'u2', + 'issueId': 'i6', + 'projectId': None, + 'title': 'Jamie Chen commented on ENG-6', + 'body': 'Code review complete. The PR looks solid ' + 'overall.', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-09T14:00:00Z'}, + { 'id': 'n6', + 'type': 'issue_assigned', + 'actorId': 'u4', + 'issueId': 'i26', + 'projectId': None, + 'title': 'Taylor Kim assigned you to DES-4', + 'body': 'Audit accessibility compliance (WCAG 2.1)', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T11:00:00Z'}, + { 'id': 'n7', + 'type': 'issue_status_changed', + 'actorId': 'u3', + 'issueId': 'i1', + 'projectId': None, + 'title': 'ENG-1 moved to In Progress', + 'body': 'Sam Patel moved Set up CI/CD pipeline to ' + 'In Progress', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-08T10:00:00Z'}, + { 'id': 'n8', + 'type': 'project_update', + 'actorId': 'u2', + 'issueId': None, + 'projectId': 'p2', + 'title': 'API v2 Migration health changed to At ' + 'Risk', + 'body': 'Jamie Chen updated project health. ' + 'Timeline may need adjustment due to scope ' + 'changes.', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-09T11:00:00Z'}, + { 'id': 'n9', + 'type': 'issue_mention', + 'actorId': 'u5', + 'issueId': 'i23', + 'projectId': None, + 'title': 'Jordan Lee mentioned you in DES-1', + 'body': 'Would love feedback from the eng team on ' + 'feasibility.', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-09T11:00:00Z'}, + { 'id': 'n10', + 'type': 'issue_assigned', + 'actorId': 'u1', + 'issueId': 'i9', + 'projectId': None, + 'title': 'You were assigned ENG-9', + 'body': 'Add dark mode support to settings page', + 'isRead': True, + 'isSnoozed': False, + 'isArchived': False, + 'createdAt': '2026-04-04T11:00:00Z'}], + 'views': [ { 'id': 'v1', + 'name': 'High Priority Bugs', + 'icon': '🐛', + 'filters': {'priority': [1, 2], 'labelIds': ['l1']}, + 'groupBy': 'status', + 'sortBy': 'priority', + 'layout': 'list', + 'teamId': None, + 'creatorId': 'u1'}, + { 'id': 'v2', + 'name': 'My In Progress', + 'icon': '🔥', + 'filters': {'assigneeId': 'u1', 'stateCategory': 'started'}, + 'groupBy': None, + 'sortBy': 'updated', + 'layout': 'list', + 'teamId': None, + 'creatorId': 'u1'}], + 'favorites': [ { 'id': 'f1', + 'type': 'project', + 'targetId': 'p1', + 'userId': 'u1', + 'sortOrder': 0}, + { 'id': 'f2', + 'type': 'view', + 'targetId': 'v1', + 'userId': 'u1', + 'sortOrder': 1}, + { 'id': 'f3', + 'type': 'cycle', + 'targetId': 'c1', + 'userId': 'u1', + 'sortOrder': 2}], + 'issueRelations': [ { 'id': 'r1', + 'issueId': 'i2', + 'relatedIssueId': 'i5', + 'type': 'blocks'}, + { 'id': 'r2', + 'issueId': 'i5', + 'relatedIssueId': 'i2', + 'type': 'blocked_by'}, + { 'id': 'r3', + 'issueId': 'i6', + 'relatedIssueId': 'i1', + 'type': 'relates_to'}, + { 'id': 'r4', + 'issueId': 'i25', + 'relatedIssueId': 'i9', + 'type': 'relates_to'}], + 'issueCounters': {'t1': 24, 't2': 8}, + 'sidebarCollapsed': False, + 'teamSectionsExpanded': {'t1': True, 't2': True}}, + '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_4', + 'content': 'pool exhaustion again ' + 'last night during the ' + 'spike', + 'timestamp': '2026-06-08T08:00:00Z', + 'threadId': None, + 'reactions': [], + 'attachments': [], + 'isEdited': False}, + { 'messageId': 'e2', + 'senderId': 'user_2', + 'content': 'we really need a runbook ' + 'for this', + '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/sre_runbook_003/reward.py b/sre_runbook_003/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..803c847c3b6a92f1ea8661e2a8cebd23725d360b --- /dev/null +++ b/sre_runbook_003/reward.py @@ -0,0 +1,115 @@ +""" +Reward Script: se_runbook_linear_b93 +Task ID: sre_runbook_003 +Domain: mock_websites +Mocks: docusign_mock, linear_mock, slack_mock +Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0): + - [0.3] new pool-exhaustion runbook page + - [0.25] runbook body has concrete remediation (pool + pgbouncer) + - [0.25] ENG-6 moved to In Review + - [0.1] slack_new_msg + - [0.1] Slack names ENG-6 +""" +import re +import sys + +import requests + +MOCK_URLS = { + "docusign_mock": "http://28.7.184.198:8130", + "linear_mock": "http://28.7.184.198:8156", + "slack_mock": "http://28.7.184.198:8178" +} +SEED = { + "slack_mock:general": [], + "slack_mock:engineering": [ + "e1", + "e2" + ], + "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 wiki page in space space-1 about (new pool-exhaustion runbook page) +c0_seed = {p.get('id') for p in ((STATES['docusign_mock'].get('initial_state') or {}).get('pages') or [])} +c0_new = [p for p in (cur('docusign_mock').get('pages') or []) if p.get('id') not in c0_seed and p.get('spaceId') == 'space-1' and any(t in _lc(p.get('title','')) for t in ['connection pool', 'pool exhaustion', 'db connection'])] +globals()['c0_target'] = c0_new[0] if c0_new else None +if c0_new: + print('PASS: new pool-exhaustion runbook page (0.3)') + total += 0.3 +else: + print('FAIL: new pool-exhaustion runbook page') + +# c1: a new wiki page in space space-1 whose body mentions (runbook body has concrete remediation (pool + pgbouncer)) +c1_seed = {p.get('id') for p in ((STATES['docusign_mock'].get('initial_state') or {}).get('pages') or [])} +c1_new = [p for p in (cur('docusign_mock').get('pages') or []) if p.get('id') not in c1_seed and p.get('spaceId') == 'space-1'] +c1_txt = _lc(' '.join(p.get('content','') for p in c1_new)) +if c1_new and all(t in c1_txt for t in ['pool', 'pgbouncer']): + print('PASS: runbook body has concrete remediation (pool + pgbouncer) (0.25)') + total += 0.25 +else: + print('FAIL: runbook body has concrete remediation (pool + pgbouncer)') + +# c2: linear issue i6 stateId == 'ws_eng_in_review' +c2_i = next((i for i in (cur('linear_mock').get('issues') or []) if i.get('id') == 'i6'), None) +if c2_i and c2_i.get('stateId') == 'ws_eng_in_review': + print('PASS: ENG-6 moved to In Review (0.25)') + total += 0.25 +else: + print('FAIL: ENG-6 moved to In Review (got ' + str(c2_i.get('stateId') if c2_i else 'missing') + ')') + +# c3: new message by user_1 in #engineering +c3_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c3_seed = set(SEED.get('slack_mock:engineering', [])) +c3_new = [m for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1'] +c3_blob = _lc(' '.join((m.get('content') or '') for m in c3_new)) +if c3_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') + +# c4: slack #engineering contains (Slack names ENG-6) +c4_msgs = (cur('slack_mock').get('messages') or {}).get('engineering', []) or [] +c4_seed = set(SEED.get('slack_mock:engineering', [])) +c4_blob = _lc(' '.join((m.get('content') or '') for m in c4_msgs if m.get('messageId') not in c4_seed and m.get('senderId') == 'user_1')) +if all(t in c4_blob for t in ['eng-6']): + print('PASS: Slack names ENG-6 (0.1)') + total += 0.1 +else: + print('FAIL: Slack names ENG-6') + +final = round(min(total, 1.0), 4) +print(f'\nScore: {total}/1.0') +print(f'REWARD: {final}') diff --git a/sre_runbook_003/reward_label.json b/sre_runbook_003/reward_label.json new file mode 100644 index 0000000000000000000000000000000000000000..a9710a98ec6860eb9466fee44d3354f8325d1659 --- /dev/null +++ b/sre_runbook_003/reward_label.json @@ -0,0 +1,65 @@ +{ + "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ec747150-73ca-5180-93dd-76d3d8125555/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:25:53", + "label": { + "task_id": "sre_runbook_003", + "domain": "mock_websites", + "summary": "验证在多个mock服务中完成运维手册创建、Linear工单状态更新及Slack通知的综合性任务", + "is_placeholder": false, + "data_sources": [ + "docusign_mock", + "linear_mock", + "slack_mock", + "/tmp/task_web_sid" + ], + "scoring_components": [ + { + "name": "c0: new pool-exhaustion runbook page", + "weight": 0.3, + "description": "在docusign_mock的space-1空间中创建了关于连接池耗尽的新wiki页面", + "check_logic": "对比initial_state与current_state中的pages,找出id不在初始集合中且spaceId为'space-1'的新页面,检查其title(转小写)是否包含'connection pool'、'pool exhaustion'或'db connection'之一", + "pass_condition": "存在至少一个符合条件的新页面" + }, + { + "name": "c1: runbook body has concrete remediation (pool + pgbouncer)", + "weight": 0.25, + "description": "新wiki页面的正文包含具体的修复措施关键词", + "check_logic": "获取space-1中所有新页面的content,拼接后转小写,检查是否同时包含'pool'和'pgbouncer'", + "pass_condition": "c1_new非空且内容中同时包含'pool'和'pgbouncer'" + }, + { + "name": "c2: ENG-6 moved to In Review", + "weight": 0.25, + "description": "Linear中id为i6的工单状态已移至In Review", + "check_logic": "在linear_mock的current_state.issues中查找id为'i6'的issue,检查其stateId是否等于'ws_eng_in_review'", + "pass_condition": "issue i6存在且stateId为'ws_eng_in_review'" + }, + { + "name": "c3: new message by user_1 in #engineering", + "weight": 0.1, + "description": "Slack的engineering频道中有user_1发送的新消息", + "check_logic": "对比SEED中slack_mock:engineering的初始消息id集合,在current_state.messages.engineering中找出messageId不在seed中且senderId为'user_1'的新消息", + "pass_condition": "存在至少一条user_1发送的新消息" + }, + { + "name": "c4: Slack names ENG-6", + "weight": 0.1, + "description": "Slack新消息内容中提到了ENG-6", + "check_logic": "将user_1在engineering频道发送的所有新消息的content拼接并转小写,检查是否包含'eng-6'", + "pass_condition": "user_1的新消息内容(转小写)包含'eng-6'" + } + ], + "total_max_score": 1.0, + "score_aggregation": "各组件分数相加,最终通过min(total, 1.0)钳制到上限1.0,并四舍五入到4位小数", + "failure_modes": [ + "无法从/tmp/task_web_sid读取sid或sid为空时,打印CRITICAL并输出REWARD: 0.0后退出", + "无法从任一mock服务(docusign_mock、linear_mock、slack_mock)获取状态时,打印CRITICAL并输出REWARD: 0.0后退出" + ], + "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话id,然后依次向三个mock服务请求当前状态。接着按顺序检查5个评分组件:1) 检查docusign_mock中space-1是否新建了标题含连接池相关关键词的wiki页面(0.3分);2) 检查这些新页面内容是否同时提及pool和pgbouncer(0.25分);3) 检查linear_mock中issue i6的状态是否为ws_eng_in_review(0.25分);4) 检查slack_mock的engineering频道是否有user_1发送的新消息(0.1分);5) 检查这些新消息内容是否包含eng-6(0.1分)。每个组件通过则累加对应分数,失败仅不加分不退出。最后将总分钳制在1.0以内并四舍五入输出。", + "confidence": 1.0 + }, + "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. 文件头注释:\n - Reward Script: se_runbook_linear_b93\n - Task ID: ec747150-73ca-5180-93dd-76d3d8125555\n - Domain: mock_websites\n - Mocks: docusign_mock, linear_mock, slack_mock\n - Scoring total = 1.0\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:docusign_mock, linear_mock, slack_mock\n - SEED 定义了 slack 的初始消息\n\n3. 评分组件:\n - c0: 0.3 - new pool-exhaustion runbook page\n - 检查 docusign_mock 中是否有新页面(id 不在 initial_state.pages 中)\n - spaceId == 'space-1'\n - 标题包含 'connection pool', 'pool exhaustion', 'db connection' 之一(不区分大小写)\n \n - c1: 0.25 - runbook body has concrete remediation (pool + pgbouncer)\n - 检查 docusign_mock 中 space-1 的新页面\n - 内容(content)不区分大小写地包含 'pool' 和 'pgbouncer'\n \n - c2: 0.25 - ENG-6 moved to In Review\n - 检查 linear_mock 中 id 为 'i6' 的 issue\n - stateId == 'ws_eng_in_review'\n \n - c3: 0.1 - slack_new_msg (new message by user_1 in #engineering)\n - 检查 slack_mock 中 engineering 频道的新消息(不在 SEED 中)\n - senderId == 'user_1'\n \n - c4: 0.1 - Slack names ENG-6\n - 检查 slack_mock 中 engineering 频道 user_1 发送的新消息内容\n - 包含 'eng-6'(不区分大小写)\n\n4. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加逻辑\n\n5. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n6. 不是占位脚本,有实际检查逻辑。\n\n7. task_id: 从注释看是 \"ec747150-73ca-5180-93dd-76d3d8125555\",但 docstring 中 Reward Script 行有 \"se_runbook_linear_b93\"。根据要求\"从文件 docstring 中提取的任务 ID\",注释第一行是 Reward Script: se_runbook_linear_b93,第二行是 Task ID: ec747150... 所以 task_id 应该是 \"ec747150-73ca-5180-93dd-76d3d8125555\"。\n\n8. domain: mock_websites\n\n9. data_sources: docusign_mock, linear_mock, slack_mock, /tmp/task_web_sid\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"ec747150-73ca-5180-93dd-76d3d8125555\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在多个mock服务中完成运维手册创建、Linear工单状态更新及Slack通知的综合性任务\",\n \"is_placeholder\": false,\n \"data_sources\": [\"docusign_mock\", \"linear_mock\", \"slack_mock\", \"/tmp/task_web_sid\"],\n \"scoring_components\": [\n {\n \"name\": \"c0: new pool-exhaustion runbook page\",\n \"weight\": 0.3,\n \"description\": \"在docusign_mock的space-1空间中创建了关于连接池耗尽的新wiki页面\",\n \"check_logic\": \"对比initial_state与current_state中的pages,找出id不在初始集合中且spaceId为'space-1'的新页面,检查其title(转小写)是否包含'connection pool'、'pool exhaustion'或'db connection'之一\",\n \"pass_condition\": \"存在至少一个符合条件的新页面\"\n },\n {\n \"name\": \"c1: runbook body has concrete remediation (pool + pgbouncer)\",\n \"weight\": 0.25,\n \"description\": \"新wiki页面的正文包含具体的修复措施关键词\",\n \"check_logic\": \"获取space-1中所有新页面的content,拼接后转小写,检查是否同时包含'pool'和'pgbouncer'\",\n \"pass_condition\": \"c1_new非空且内容中同时包含'pool'和'pgbouncer'\"\n },\n {\n \"name\": \"c2: ENG-6 moved to In Review\",\n \"weight\": 0.25,\n \"description\": \"Linear中id为i6的工单状态已移至In Review\",\n \"check_logic\": \"在linear_mock的current_state.issues中查找id为'i6'的issue,检查其stateId是否等于'ws_eng_in_review'\",\n \"pass_condition\": \"issue i6存在且stateId为'ws_eng_in_review'\"\n },\n {\n \"name\": \"c3: new message by user_1 in #engineering\",\n \"weight\": 0.1,\n \"description\": \"Slack的engineering频道中有user_1发送的新消息\",\n \"check_logic\": \"对比SEED中slack_mock:engineering的初始消息id集合,在current_state.messages.engineering中找出messageId不在seed中且senderId为'user_1'的新消息\",\n \"pass_condition\": \"存在至少一条user_1发送的新消息\"\n },\n {\n \"name\": \"c4: Slack names ENG-6\",\n \"weight\": 0.1,\n \"description\": \"Slack新消息内容中提到了ENG-6\",\n \"check_logic\": \"将user_1在engineering频道发送的所有新消息的content拼接并转小写,检查是否包含'eng-6'\",\n \"pass_condition\": \"user_1的新消息内容(转小写)包含'eng-6'\"\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或sid为空时,打印CRITICAL并输出REWARD: 0.0后退出\",\n \"无法从任一mock服务(docusign_mock、linear_mock、slack_mock)获取状态时,打印CRITICAL并输出REWARD: 0.0后退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话id,然后依次向三个mock服务请求当前状态。接着按顺序检查5个评分组件:1) 检查docusign_mock中space-1是否新建了标题含连接池相关关键词的wiki页面(0.3分);2) 检查这些新页面内容是否同时提及pool和pgbouncer(0.25分);3) 检查linear_mock中issue i6的状态是否为ws_eng_in_review(0.25分);4) 检查slack_mock的engineering频道是否有user_1发送的新消息(0.1分);5) 检查这些新消息内容是否包含eng-6(0.1分)。每个组件通过则累加对应分数,失败仅不加分不退出。最后将总分钳制在1.0以内并四舍五入输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出一个 JSON 对象,不要输出 Markdown 代码块标记,不要输出额外解释,不要输出思考过程,不要输出 thinking 标签。\n- 输出的第一个字符必须是 {,最后一个字符必须是 }。\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样。\n- weight 字段填写代码中显式给出的分值。\n\n确认 task_id:docstring 中明确写了 \"Task ID: ec747150-73ca-5180-93dd-76d3d8125555\",所以用这个。\n\n确认 domain:mock_websites。\n\n确认 is_placeholder:false,因为有实际检查。\n\n确认 data_sources:包含三个 mock 和 sid 文件。\n\n确认 score_aggregation:代码中是 total 累加,然后 final = round(min(total, 1.0), 4)。\n\n确认 failure_modes:sid 读取失败和 mock 拉取失败都会导致 sys.exit(0) 并输出 0.0。\n\n看起来都正确。 {\n \"task_id\": \"ec747150-73ca-5180-93dd-76d3d8125555\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在多个mock服务中完成运维手册创建、Linear工单状态更新及Slack通知的综合性任务\",\n \"is_placeholder\": false,\n \"data_sources\": [\"docusign_mock\", \"linear_mock\", \"slack_mock\", \"/tmp/task_web_sid\"],\n \"scoring_components\": [\n {\n \"name\": \"c0: new pool-exhaustion runbook page\",\n \"weight\": 0.3,\n \"description\": \"在docusign_mock的space-1空间中创建了关于连接池耗尽的新wiki页面\",\n \"check_logic\": \"对比initial_state与current_state中的pages,找出id不在初始集合中且spaceId为'space-1'的新页面,检查其title(转小写)是否包含'connection pool'、'pool exhaustion'或'db connection'之一\",\n \"pass_condition\": \"存在至少一个符合条件的新页面\"\n },\n {\n \"name\": \"c1: runbook body has concrete remediation (pool + pgbouncer)\",\n \"weight\": 0.25,\n \"description\": \"新wiki页面的正文包含具体的修复措施关键词\",\n \"check_logic\": \"获取space-1中所有新页面的content,拼接后转小写,检查是否同时包含'pool'和'pgbouncer'\",\n \"pass_condition\": \"c1_new非空且内容中同时包含'pool'和'pgbouncer'\"\n },\n {\n \"name\": \"c2: ENG-6 moved to In Review\",\n \"weight\": 0.25,\n \"description\": \"Linear中id为i6的工单状态已移至In Review\",\n \"check_logic\": \"在linear_mock的current_state.issues中查找id为'i6'的issue,检查其stateId是否等于'ws_eng_in_review'\",\n \"pass_condition\": \"issue i6存在且stateId为'ws_eng_in_review'\"\n },\n {\n \"name\": \"c3: new message by user_1 in #engineering\",\n \"weight\": 0.1,\n \"description\": \"Slack的engineering频道中有user_1发送的新消息\",\n \"check_logic\": \"对比SEED中slack_mock:engineering的初始消息id集合,在current_state.messages.engineering中找出messageId不在seed中且senderId为'user_1'的新消息\",\n \"pass_condition\": \"存在至少一条user_1发送的新消息\"\n },\n {\n \"name\": \"c4: Slack names ENG-6\",\n \"weight\": 0.1,\n \"description\": \"Slack新消息内容中提到了ENG-6\",\n \"check_logic\": \"将user_1在engineering频道发送的所有新消息的content拼接并转小写,检查是否包含'eng-6'\",\n \"pass_condition\": \"user_1的新消息内容(转小写)包含'eng-6'\"\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或sid为空时,打印CRITICAL并输出REWARD: 0.0后退出\",\n \"无法从任一mock服务(docusign_mock、linear_mock、slack_mock)获取状态时,打印CRITICAL并输出REWARD: 0.0后退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话id,然后依次向三个mock服务请求当前状态。接着按顺序检查5个评分组件:1) 检查docusign_mock中space-1是否新建了标题含连接池相关关键词的wiki页面(0.3分);2) 检查这些新页面内容是否同时提及pool和pgbouncer(0.25分);3) 检查linear_mock中issue i6的状态是否为ws_eng_in_review(0.25分);4) 检查slack_mock的engineering频道是否有user_1发送的新消息(0.1分);5) 检查这些新消息内容是否包含eng-6(0.1分)。每个组件通过则累加对应分数,失败仅不加分不退出。最后将总分钳制在1.0以内并四舍五入输出。\",\n \"confidence\": 1.0\n}" +}