Download ar_remittance_008__long/reward.py from tencent/OSWorkerBench: direct link, hf CLI and curl.
- Browser
- Download file 25 kB
-
https://huggingface.co/datasets/tencent/OSWorkerBench/resolve/main/ar_remittance_008__long/reward.py
- Command line
-
hf download hf://datasets/tencent/OSWorkerBench/ar_remittance_008__long/reward.py
-
curl -L -o reward.py https://huggingface.co/datasets/tencent/OSWorkerBench/resolve/main/ar_remittance_008__long/reward.py
25 kB
| """ | |
| Reward Script: T06 — QuickBooks AR aging report into Google Sheets (+ Gmail reconcile) | |
| Task ID: ar_remittance_008__long | |
| Mocks: quickbooks_mock,google_sheets_mock,gmail_mock | |
| Scoring (all components 0 at do-nothing; reconcile invoices ship unpaid): | |
| 0.40 detail rows == expected_rows as an ORDERED list (DaysOverdue desc), | |
| matching on (Customer, InvoiceNumber, Total, Bucket); frac of correctly-placed rows | |
| 0.15 DaysOverdue + Bucket values correct per row (avg of two per-row sub-checks) | |
| 0.20 per-bucket SUM rows match expected_summary (5 buckets, col A label + col C sum, exact) | |
| 0.10 Grand Total row ('Grand Total' label + col C sum == grand_total) | |
| 0.15 the two Gmail-announced invoices marked Paid via 'Receive payment' (status-gated) | |
| (− modest over-inclusion penalty for Paid/Draft distractor invoice rows, capped 0.10) | |
| Answer key: google_sheets.initial_state._task_adapter.expected_rows / expected_summary / | |
| grand_total / reconcile_invoice_numbers (primary) + quickbooks invoices[*]._age. | |
| """ | |
| import copy | |
| import datetime as _dt | |
| import re | |
| import sys | |
| import requests | |
| try: | |
| with open('/tmp/task_web_sid', encoding='utf-8') as f: | |
| sid = f.read().strip() | |
| if not sid: | |
| raise ValueError('sid is empty') | |
| except Exception as e: | |
| print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}') | |
| print('REWARD: 0.0') | |
| sys.exit(0) | |
| APP_URLS = {'quickbooks': 'http://28.7.184.198:8172', 'google_sheets': 'http://28.7.184.198:8145'} | |
| _GO_CACHE = {} | |
| def clamp01(x): | |
| return max(0.0, min(1.0, float(x))) | |
| def frac(num, den): | |
| return 0.0 if den == 0 else num / den | |
| def f1(true_set, pred_set): | |
| if not true_set and not pred_set: | |
| return 1.0 | |
| tp = len(true_set & pred_set) | |
| if tp == 0: | |
| return 0.0 | |
| prec = tp / len(pred_set) | |
| rec = tp / len(true_set) | |
| return 2 * prec * rec / (prec + rec) | |
| def by_id(items, key='id'): | |
| return {it.get(key): it for it in (items or []) if isinstance(it, dict)} | |
| def has_text(haystack, *needles): | |
| s = (haystack or '').lower() | |
| return any(n.lower() in s for n in needles) | |
| def norm(s): | |
| return (str(s) if s is not None else '').strip().lower() | |
| def _to_float(v): | |
| try: | |
| return float(v) | |
| except (TypeError, ValueError): | |
| return 0.0 | |
| def _msg_text(m): | |
| return m.get('content') or m.get('text') or '' | |
| def _slack_channel_messages(slack_state, channel_name): | |
| # Slack messages may live under channels[*].messages OR the top-level | |
| # messages[channelId] map — read both. | |
| if not isinstance(slack_state, dict): | |
| return [] | |
| channels = slack_state.get('channels') if isinstance(slack_state.get('channels'), list) else [] | |
| messages_map = slack_state.get('messages') if isinstance(slack_state.get('messages'), dict) else {} | |
| out = [] | |
| for ch in channels: | |
| if not isinstance(ch, dict): | |
| continue | |
| if norm(ch.get('name')) != norm(channel_name): | |
| continue | |
| cid = ch.get('channelId') or ch.get('id') | |
| for m in (ch.get('messages') if isinstance(ch.get('messages'), list) else []): | |
| if isinstance(m, dict): | |
| out.append(m) | |
| if cid and isinstance(messages_map.get(cid), list): | |
| for m in messages_map[cid]: | |
| if isinstance(m, dict): | |
| out.append(m) | |
| return out | |
| def _sheet_rows(sheet): | |
| if not isinstance(sheet, dict): | |
| return [] | |
| rows = sheet.get('rows', []) | |
| return rows if isinstance(rows, list) else [] | |
| def _sheet_tabs(sheets): | |
| if isinstance(sheets, dict): | |
| return sheets | |
| if isinstance(sheets, list): | |
| out = {} | |
| for sh in sheets: | |
| if not isinstance(sh, dict): | |
| continue | |
| name = sh.get('name') or sh.get('id') | |
| if name: | |
| out[name] = sh | |
| return out | |
| return {} | |
| def _normalize_app_name(app): | |
| app = (app or '').strip().lower() | |
| return app[:-5] if app.endswith('_mock') else app | |
| def _parse_cell_id(cell_id): | |
| if not isinstance(cell_id, str) or not cell_id: | |
| return None | |
| idx = 0 | |
| while idx < len(cell_id) and cell_id[idx].isalpha(): | |
| idx += 1 | |
| if idx == 0 or idx >= len(cell_id): | |
| return None | |
| col = 0 | |
| for ch in cell_id[:idx].upper(): | |
| col = col * 26 + (ord(ch) - ord('A') + 1) | |
| try: | |
| row = int(cell_id[idx:]) | |
| except ValueError: | |
| return None | |
| return row, col - 1 | |
| def _extract_rows_from_workbook(state): | |
| if not isinstance(state, dict): | |
| return None | |
| sheets = state.get('sheets') | |
| if not isinstance(sheets, list): | |
| return None | |
| adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} | |
| headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {} | |
| out = {} | |
| for sh in sheets: | |
| if not isinstance(sh, dict): | |
| continue | |
| name = sh.get('name') or sh.get('id') or 'Sheet1' | |
| data = sh.get('data') if isinstance(sh.get('data'), dict) else {} | |
| headers = headers_by_sheet.get(name) | |
| if not headers: | |
| cols = [] | |
| for cid, cell in data.items(): | |
| rc = _parse_cell_id(cid) | |
| if not rc: | |
| continue | |
| row_idx, col_idx = rc | |
| if row_idx != 1: | |
| continue | |
| value = '' | |
| if isinstance(cell, dict): | |
| value = cell.get('value', '') | |
| elif cell is not None: | |
| value = str(cell) | |
| if value is not None and str(value) != '': | |
| cols.append((col_idx, str(value))) | |
| headers = [v for _, v in sorted(cols)] | |
| if not headers: | |
| continue | |
| by_row = {} | |
| for cid, cell in data.items(): | |
| rc = _parse_cell_id(cid) | |
| if not rc: | |
| continue | |
| row_idx, col_idx = rc | |
| if row_idx <= 1 or col_idx >= len(headers): | |
| continue | |
| if isinstance(cell, dict): | |
| value = cell.get('value', '') | |
| else: | |
| value = cell | |
| by_row.setdefault(row_idx, {})[headers[col_idx]] = value | |
| rows = [] | |
| for row_idx in sorted(by_row.keys()): | |
| row = by_row[row_idx] | |
| if not any(str(row.get(h, '')).strip() for h in headers): | |
| continue | |
| rows.append({h: row.get(h, '') for h in headers}) | |
| out[name] = {'headers': headers, 'rows': rows} | |
| if not out: | |
| return None | |
| return {'sheets': out} | |
| def _materialize_google_sheets(payload): | |
| for key in ('initial_state', 'current_state'): | |
| state = payload.get(key) | |
| if not isinstance(state, dict): | |
| continue | |
| maybe_rows = _extract_rows_from_workbook(state) | |
| if maybe_rows is not None: | |
| state['_ui_workbook'] = { | |
| 'sheets': copy.deepcopy(state.get('sheets', [])), | |
| 'title': state.get('title'), | |
| } | |
| state['sheets'] = maybe_rows['sheets'] | |
| def _materialize_slack(payload): | |
| for key in ('initial_state', 'current_state'): | |
| state = payload.get(key) | |
| if not isinstance(state, dict): | |
| continue | |
| channels = state.get('channels') if isinstance(state.get('channels'), list) else [] | |
| messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {} | |
| for ch in channels: | |
| if not isinstance(ch, dict): | |
| continue | |
| cid = ch.get('channelId') or ch.get('id') | |
| if not cid: | |
| continue | |
| msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else [] | |
| channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else [] | |
| merged = { | |
| (m.get('messageId') or m.get('id')): dict(m) | |
| for m in channel_msgs | |
| if isinstance(m, dict) | |
| } | |
| for m in msg_list: | |
| if not isinstance(m, dict): | |
| continue | |
| mid = m.get('messageId') or m.get('id') | |
| text = m.get('text') if m.get('text') is not None else m.get('content', '') | |
| merged[mid] = { | |
| 'id': mid, | |
| 'messageId': mid, | |
| 'text': text, | |
| 'content': m.get('content', text), | |
| 'senderId': m.get('senderId'), | |
| 'timestamp': m.get('timestamp'), | |
| 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [], | |
| } | |
| ch['messages'] = list(merged.values()) | |
| def _owner_name_map(state): | |
| out = {} | |
| users = state.get('users') if isinstance(state.get('users'), list) else [] | |
| for u in users: | |
| if not isinstance(u, dict): | |
| continue | |
| uid = u.get('userId') | |
| if not uid: | |
| continue | |
| name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid) | |
| out[uid] = name | |
| return out | |
| def _materialize_salesforce(payload): | |
| for key in ('initial_state', 'current_state'): | |
| state = payload.get(key) | |
| if not isinstance(state, dict): | |
| continue | |
| adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} | |
| owner_names = _owner_name_map(state) | |
| task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None | |
| if task_leads and isinstance(state.get('leads'), list): | |
| restored = [] | |
| for lead in state['leads']: | |
| if not isinstance(lead, dict): | |
| continue | |
| lid = str(lead.get('leadId') or lead.get('id') or '') | |
| meta = task_leads.get(lid, {}) | |
| restored.append({ | |
| 'id': meta.get('id') or lead.get('leadId') or lead.get('id'), | |
| 'company': lead.get('company', meta.get('company', '')), | |
| 'status': lead.get('status', 'New'), | |
| 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'), | |
| 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')), | |
| }) | |
| state['leads'] = restored | |
| task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None | |
| if task_accounts and isinstance(state.get('accounts'), list): | |
| current_by_id = {} | |
| for acc in state['accounts']: | |
| if isinstance(acc, dict): | |
| current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc | |
| restored_accounts = [] | |
| for aid, meta in task_accounts.items(): | |
| cur = current_by_id.get(str(aid), {}) | |
| restored_accounts.append({ | |
| 'id': meta.get('id') or aid, | |
| 'name': meta.get('name') or cur.get('name', ''), | |
| 'contact': meta.get('contact'), | |
| 'wonWithin7d': bool(meta.get('wonWithin7d', False)), | |
| 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')), | |
| }) | |
| state['accounts'] = restored_accounts | |
| def _materialize_google_docs(payload): | |
| for key in ('initial_state', 'current_state'): | |
| state = payload.get(key) | |
| if not isinstance(state, dict): | |
| continue | |
| adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {} | |
| task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None | |
| if not task_docs: | |
| continue | |
| docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {} | |
| restored = [] | |
| for did, meta in task_docs.items(): | |
| cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {} | |
| restored.append({ | |
| 'id': meta.get('id') or did, | |
| 'title': cur.get('title', meta.get('title')), | |
| 'vendor': meta.get('vendor'), | |
| 'folder': meta.get('folder'), | |
| 'content': cur.get('content', meta.get('content', '')), | |
| }) | |
| state['documents'] = restored | |
| def _adapt_payload_for_reward(app, payload): | |
| app_name = _normalize_app_name(app) | |
| if app_name == 'google_sheets': | |
| _materialize_google_sheets(payload) | |
| elif app_name == 'slack': | |
| _materialize_slack(payload) | |
| elif app_name == 'salesforce': | |
| _materialize_salesforce(payload) | |
| elif app_name == 'google_docs': | |
| _materialize_google_docs(payload) | |
| return payload | |
| def go(app_name): | |
| if app_name in _GO_CACHE: | |
| return _GO_CACHE[app_name] | |
| base = APP_URLS.get(app_name) | |
| if not base: | |
| print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)') | |
| print('REWARD: 0.0') | |
| sys.exit(0) | |
| try: | |
| resp = requests.get(f'{base}/go?sid={sid}', timeout=15) | |
| resp.raise_for_status() | |
| payload = resp.json() | |
| except Exception as e: | |
| print(f'CRITICAL: cannot fetch {app_name} go state: {e}') | |
| print('REWARD: 0.0') | |
| sys.exit(0) | |
| payload = _adapt_payload_for_reward(app_name, payload) | |
| _GO_CACHE[app_name] = payload | |
| return payload | |
| # === Task-specific reward === | |
| # | |
| # The agent reads QuickBooks open invoices (Sent/Overdue only), buckets them by | |
| # days overdue (today = 2026-04-30), and writes an AR-aging report into the | |
| # 'AR Aging' tab of the Google Sheet: | |
| # - one detail row per qualifying invoice (Customer, InvoiceNumber, Total, | |
| # DueDate, DaysOverdue, Bucket), sorted by DaysOverdue DESC, and | |
| # - a summary block: one row per bucket (label in col A, SUM of Total in col C) | |
| # in fixed bucket order, then a 'Grand Total' row (sum in col C). | |
| # | |
| # Ground truth lives in google_sheets.initial_state._task_adapter (expected_rows, | |
| # expected_summary, grand_total). QuickBooks invoices carry a hidden `_age` on the | |
| # Sent/Overdue invoices; we read it to recover the qualifying-invoice set used for | |
| # the distractor (Paid/Draft) over-inclusion guard. | |
| def reward(go): | |
| TOL = 0.01 # penny tolerance for currency / sums | |
| W_DETAIL = 0.40 | |
| W_VALUES = 0.15 | |
| W_SUMMARY = 0.20 | |
| W_GRAND = 0.10 | |
| W_RECEIVE = 0.15 # reconcile invoices marked Paid via 'Receive payment' | |
| PENALTY_PER_DISTRACTOR = 0.05 | |
| PENALTY_CAP = 0.10 | |
| # ---- helpers for raw cell-grid reading ---- | |
| def _cell_disp(cell): | |
| # Resolve a cell to its displayed value: prefer `computed` when `value` | |
| # is a formula (=SUM(...)) or empty. | |
| if isinstance(cell, dict): | |
| comp = cell.get('computed') | |
| val = cell.get('value', '') | |
| if isinstance(val, str) and val.strip().startswith('='): | |
| if comp is not None and str(comp).strip() != '': | |
| return comp | |
| return val | |
| if (val is None or str(val).strip() == '') and comp is not None: | |
| return comp | |
| return val | |
| return cell | |
| def _to_num(v): | |
| if v is None: | |
| return None | |
| if isinstance(v, bool): | |
| return None | |
| if isinstance(v, (int, float)): | |
| return float(v) | |
| s = str(v).strip() | |
| if not s: | |
| return None | |
| s = s.replace('$', '').replace(',', '').strip() | |
| if s in ('', '-', '+'): | |
| return None | |
| try: | |
| return float(s) | |
| except Exception: | |
| return None | |
| def _s(v): | |
| if v is None: | |
| return '' | |
| return str(v).strip() | |
| def _raw_sheet(state, name): | |
| if not isinstance(state, dict): | |
| return None | |
| candidates = [] | |
| ui = state.get('_ui_workbook') | |
| if isinstance(ui, dict) and isinstance(ui.get('sheets'), list): | |
| candidates = ui['sheets'] | |
| elif isinstance(state.get('sheets'), list): | |
| candidates = state['sheets'] | |
| for sh in candidates: | |
| if not isinstance(sh, dict): | |
| continue | |
| if norm(sh.get('name')) == norm(name) or norm(sh.get('id')) == norm(name): | |
| return sh | |
| if len(candidates) == 1 and isinstance(candidates[0], dict): | |
| return candidates[0] | |
| return None | |
| def _grid(sheet): | |
| grid = {} | |
| data = sheet.get('data') if isinstance(sheet, dict) else None | |
| if not isinstance(data, dict): | |
| return grid | |
| for cid, cell in data.items(): | |
| rc = _parse_cell_id(cid) | |
| if not rc: | |
| continue | |
| r, c = rc # r 1-based, c 0-based | |
| grid.setdefault(r, {})[c] = _cell_disp(cell) | |
| return grid | |
| # ---- 1) Pull answer key (primary) from sheets adapter ---- | |
| gs = go('google_sheets') | |
| gs_init = gs.get('initial_state', {}) if isinstance(gs.get('initial_state'), dict) else {} | |
| gs_cur = gs.get('current_state', {}) if isinstance(gs.get('current_state'), dict) else {} | |
| adapter = gs_init.get('_task_adapter', {}) if isinstance(gs_init.get('_task_adapter'), dict) else {} | |
| expected_rows = adapter.get('expected_rows') if isinstance(adapter.get('expected_rows'), list) else [] | |
| expected_summary = adapter.get('expected_summary') if isinstance(adapter.get('expected_summary'), list) else [] | |
| grand_total_truth = adapter.get('grand_total') | |
| bucket_order = adapter.get('bucket_order') if isinstance(adapter.get('bucket_order'), list) else \ | |
| ['Current', '1-30', '31-60', '61-90', '90+'] | |
| target_sheet = adapter.get('target_sheet') or 'AR Aging' | |
| bucket_label_set = {norm(b) for b in bucket_order} | |
| # ---- secondary key: qualifying invoice numbers from QB `_age` ---- | |
| qb_payload = go('quickbooks') | |
| qb_init = qb_payload.get('initial_state', {}) or {} | |
| qb_cur = qb_payload.get('current_state', {}) or {} | |
| qb_inv = qb_init.get('invoices', []) or [] | |
| qualifying_nums = {norm(inv.get('number')) for inv in qb_inv | |
| if isinstance(inv, dict) and '_age' in inv} | |
| # expected detail invoice numbers (string) — used for distractor detection | |
| expected_nums = {norm(er.get('InvoiceNumber')) for er in expected_rows | |
| if isinstance(er, dict)} | |
| if not expected_nums: | |
| expected_nums = qualifying_nums | |
| n = len(expected_rows) | |
| if n == 0: | |
| print('DEBUG_T06_AR_AGING fatal=no_expected_rows total=0.0') | |
| return 0.0 | |
| # ---- 2) Parse agent output grid for the AR Aging tab ---- | |
| sheet = _raw_sheet(gs_cur, target_sheet) | |
| grid = _grid(sheet) if sheet is not None else {} | |
| # Columns: A=0 Customer, B=1 InvoiceNumber, C=2 Total, D=3 DueDate, | |
| # E=4 DaysOverdue, F=5 Bucket | |
| detail_rows = [] # ordered list of agent detail rows (dicts) | |
| summary_cells = {} # bucket-label-norm -> total float | |
| grand_total_val = None | |
| distractor_detail = 0 | |
| for r in sorted(grid.keys()): | |
| if r <= 1: | |
| continue # header row | |
| row = grid[r] | |
| a = _s(row.get(0)) | |
| b = _s(row.get(1)) | |
| a_norm = norm(a) | |
| is_grand = ('grand' in a_norm and 'total' in a_norm) | |
| is_bucket_label = a_norm in bucket_label_set | |
| if is_grand: | |
| gv = _to_num(row.get(2)) | |
| if gv is not None: | |
| grand_total_val = gv | |
| continue | |
| if is_bucket_label and not b: | |
| cv = _to_num(row.get(2)) | |
| if a_norm not in summary_cells and cv is not None: | |
| summary_cells[a_norm] = cv | |
| continue | |
| if b: | |
| # detail (invoice) row | |
| inv_num = b | |
| detail_rows.append({ | |
| 'Customer': a, | |
| 'InvoiceNumber': inv_num, | |
| 'Total': _to_num(row.get(2)), | |
| 'DueDate': _s(row.get(3)), | |
| 'DaysOverdue': _to_num(row.get(4)), | |
| 'Bucket': _s(row.get(5)), | |
| }) | |
| if norm(inv_num) not in expected_nums: | |
| distractor_detail += 1 | |
| # else: blank / unrecognized row -> ignore | |
| # ---- 3) Component 1 (0.45): ordered detail match on (Customer, InvoiceNumber, Total, Bucket) ---- | |
| hits_detail = 0 | |
| for i, exp in enumerate(expected_rows): | |
| if i >= len(detail_rows): | |
| continue | |
| got = detail_rows[i] | |
| exp_total = _to_num(exp.get('Total')) | |
| got_total = got.get('Total') | |
| total_ok = (got_total is not None and exp_total is not None | |
| and abs(got_total - exp_total) <= TOL) | |
| if (norm(got.get('Customer')) == norm(exp.get('Customer')) | |
| and norm(got.get('InvoiceNumber')) == norm(exp.get('InvoiceNumber')) | |
| and total_ok | |
| and norm(got.get('Bucket')) == norm(exp.get('Bucket'))): | |
| hits_detail += 1 | |
| s_detail = W_DETAIL * frac(hits_detail, n) | |
| # ---- 4) Component 2 (0.20): DaysOverdue + Bucket correct per row (avg two sub-checks) ---- | |
| hits_days = 0 | |
| hits_bucket = 0 | |
| for i, exp in enumerate(expected_rows): | |
| if i >= len(detail_rows): | |
| continue | |
| got = detail_rows[i] | |
| exp_days = exp.get('DaysOverdue') | |
| got_days = got.get('DaysOverdue') | |
| try: | |
| if got_days is not None and exp_days is not None and \ | |
| int(round(float(got_days))) == int(round(float(exp_days))): | |
| hits_days += 1 | |
| except Exception: | |
| pass | |
| if norm(got.get('Bucket')) == norm(exp.get('Bucket')): | |
| hits_bucket += 1 | |
| s_values = W_VALUES * 0.5 * (frac(hits_days, n) + frac(hits_bucket, n)) | |
| # ---- 5) Component 3 (0.25): per-bucket SUM rows == expected_summary ---- | |
| n_buckets = len(expected_summary) | |
| hits_summary = 0 | |
| for item in expected_summary: | |
| if not isinstance(item, dict): | |
| continue | |
| blabel = norm(item.get('bucket')) | |
| btot = _to_num(item.get('total')) | |
| got = summary_cells.get(blabel) | |
| if got is not None and btot is not None and abs(got - btot) <= TOL: | |
| hits_summary += 1 | |
| s_summary = W_SUMMARY * frac(hits_summary, n_buckets) if n_buckets else 0.0 | |
| # ---- 6) Component 4 (0.10): Grand Total ---- | |
| gt_truth = _to_num(grand_total_truth) | |
| grand_ok = (grand_total_val is not None and gt_truth is not None | |
| and abs(grand_total_val - gt_truth) <= TOL) | |
| s_grand = W_GRAND * (1.0 if grand_ok else 0.0) | |
| # ---- 6b) Component 5 (0.15): reconcile invoices marked Paid via 'Receive payment' ---- | |
| # The two invoices named in the Gmail notice must be status 'Paid' in QB | |
| # current_state. They ship UNPAID (Sent), so a do-nothing agent scores 0 here. | |
| recon_numbers = set() | |
| adapter_recon = adapter.get('reconcile_invoice_numbers') if isinstance(adapter, dict) else None | |
| if isinstance(adapter_recon, list): | |
| recon_numbers = {str(x) for x in adapter_recon} | |
| if not recon_numbers: | |
| # fallback: invoices carrying the hidden _receive_payment flag in QB initial_state | |
| for inv in (qb_init.get('invoices', []) or []): | |
| if isinstance(inv, dict) and inv.get('_receive_payment'): | |
| recon_numbers.add(str(inv.get('number'))) | |
| qb_cur_invoices = qb_cur.get('invoices', []) or [] | |
| cur_status_by_num = {} | |
| for inv in qb_cur_invoices: | |
| if isinstance(inv, dict): | |
| cur_status_by_num[str(inv.get('number'))] = norm(inv.get('status')) | |
| recv_ok = sum(1 for num in recon_numbers if cur_status_by_num.get(num) == 'paid') | |
| s_receive = W_RECEIVE * frac(recv_ok, len(recon_numbers)) if recon_numbers else 0.0 | |
| # ---- 7) Over-inclusion guard: penalize Paid/Draft distractor rows ---- | |
| penalty = min(PENALTY_CAP, PENALTY_PER_DISTRACTOR * distractor_detail) | |
| raw = s_detail + s_values + s_summary + s_grand + s_receive - penalty | |
| score = clamp01(raw) | |
| print( | |
| 'DEBUG_T06_AR_AGING ' | |
| f'n_exp={n} n_detail={len(detail_rows)} qual_nums={len(qualifying_nums)} ' | |
| f'detail_hits={hits_detail}/{n} days_hits={hits_days}/{n} bucket_hits={hits_bucket}/{n} ' | |
| f'summary_hits={hits_summary}/{n_buckets} grand_ok={int(grand_ok)} ' | |
| f'recv_ok={recv_ok}/{len(recon_numbers)} ' | |
| f'distractors={distractor_detail} penalty={round(penalty, 4)} ' | |
| f'w_detail={round(s_detail, 4)} w_values={round(s_values, 4)} ' | |
| f'w_summary={round(s_summary, 4)} w_grand={round(s_grand, 4)} w_receive={round(s_receive, 4)} ' | |
| f'raw={round(raw, 4)} total={round(score, 4)}' | |
| ) | |
| return score | |
| try: | |
| score = float(reward(go)) | |
| except Exception as exc: | |
| print(f'ERROR: reward() raised {exc!r}') | |
| score = 0.0 | |
| score = clamp01(score) | |
| print(f'\nREWARD: {round(score, 4)}') | |