JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
96.5 kB
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from functools import lru_cache
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules
from typing import Any as ext_Any
import hashlib as mod_hashlib
import json as mod_json
import jsonschema as mod_jsonschema
import rescopebench.stream_engine as mod_engine
from .spec import CASE_DIR, DATA_RETEST_TASKS, DATA_RETEST_ORDER, DATA_POST_AUTHORITY, DATA_TOOLS_2, DATA_PROFILE_BY_RULE, DATA_TASK_IDS, DATA_WRITE_TOOLS, DATA_ENTITY_ID_FIELDS, DATA_APPROVAL_ROLES, DATA_REPLACEMENTS, DATA_PRE_AUTHORITY, DATA_TOOL_BY_NAME, DATA_READ_COSTS, DATA_SCHEDULE_2, DATA_ACTOR_GRANTS, DATA_TASK_BLUEPRINT, DATA_STRUCTURE_ATOMS, DATA_STRUCTURE_TRACKS, DATA_TASK_BLUEPRINT_2, DATA_TASK_BLUEPRINT_3
def fn_public_task(task_id):
packet = fn_public_task_2(task_id)
if task_id in DATA_RETEST_TASKS:
packet['targets'] = [packet['targets'][i] for i in DATA_RETEST_ORDER]
token = fn__opaque('EV', 'scf-lead-retest-lifecycle-evolution-v2', task_id, packet['targets'], length=12)
packet['task_id'] = token.upper()
return packet
def fn__authority_candidates(atom_id, current):
stale = DATA_PRE_AUTHORITY[atom_id]
foreign_scope = fn__opaque_2('funding-scope', atom_id, 'foreign', length=14)
foreign_chain = fn__opaque_2('approval-chain', atom_id, 'foreign', length=14)
routes = [{'funding_scope_id': current['funding_scope_id'], 'submission_channel': current['submission_channel'], 'approval_chain_ref': current['approval_chain_ref'], 'route_status': 'eligible'}, {'funding_scope_id': foreign_scope, 'submission_channel': 'operations_console', 'approval_chain_ref': foreign_chain, 'route_status': 'eligible'}]
if stale != current:
routes.append({'funding_scope_id': stale['funding_scope_id'], 'submission_channel': stale['submission_channel'], 'approval_chain_ref': stale['approval_chain_ref'], 'route_status': 'retired'})
routes.sort(key=lambda row: row['funding_scope_id'])
delegations = []
for row in current['delegations']:
delegations.append({'role': row['role'], 'principal_ref': 'current-finance-operator', 'delegation_id': row['delegation_id'], 'scope_id': row['scope_id'], 'approval_chain_ref': current['approval_chain_ref'], 'status': 'active'})
if stale != current:
for row in stale['delegations']:
delegations.append({'role': row['role'], 'principal_ref': 'current-finance-operator', 'delegation_id': row['delegation_id'], 'scope_id': row['scope_id'], 'approval_chain_ref': stale['approval_chain_ref'], 'status': 'revoked'})
for role in DATA_APPROVAL_ROLES:
delegations.append({'role': role, 'principal_ref': 'external-finance-operator', 'delegation_id': fn__opaque_2('delegation', atom_id, 'foreign', role, length=14), 'scope_id': foreign_scope, 'approval_chain_ref': foreign_chain, 'status': 'active'})
return {'routes': routes, 'delegations': delegations}
def fn_approval_task_ids(target, authority):
slug = str(target['invoice_id']).removeprefix('invoice-')
namespace = authority['approval_namespace']
return [f"approval-{slug}-{namespace}-{role.replace('_', '-')}-{index:03d}" for (index, role) in enumerate(DATA_APPROVAL_ROLES, 1)]
def fn__hash(value):
payload = mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
return mod_hashlib.sha256(payload.encode('utf-8')).hexdigest()
def fn__normalize(result):
value = ext_deepcopy(result)
data = value.setdefault('data', {})
if value.get('status') == 'error' and (not data.get('error_code')):
message = str(value.get('message') or '')
data['status'] = 'failed'
data['error_code'] = message.split(':', 1)[0] if message else 'OPERATION_FAILED'
elif value.get('status') == 'success':
data.setdefault('status', 'succeeded')
data.setdefault('error_code', None)
return value
def fn__success(**data):
return {'status': 'success', 'data': {'status': 'succeeded', 'error_code': None, **ext_deepcopy(data)}, 'message': 'OK'}
def fn__money(value):
return round(float(value or 0), 2)
def fn_activate_coverage(snapshot, task_id, current_terms):
"""Replace only the newly released, previously inaccessible work records."""
result = ext_deepcopy(snapshot)
old_targets = fn_stream_targets(task_id)
targets = fn_stream_targets_2(task_id)
for slot in DATA_REPLACEMENTS.get(task_id, {}):
(old, new) = (old_targets[slot - 1], targets[slot - 1])
for decoy in (False, True):
old_invoice = fn__invoice_row(old, decoy=decoy)
new_invoice = fn__invoice_row(new, decoy=decoy)
existing = [r for r in result['entities']['invoice'] if r['invoice_id'] == old_invoice['invoice_id']]
if existing != [old_invoice]:
raise ValueError('Coverage replacement cannot discard changed business records')
fn_replace_one(result['entities']['invoice'], 'invoice_id', old_invoice['invoice_id'], new_invoice)
released = result['release_by_invoice'].pop(old_invoice['invoice_id'])
if released != new['position']:
raise ValueError('Replacement changes invoice release timing')
result['release_by_invoice'][new_invoice['invoice_id']] = released
item = next((r for r in result['work_items'] if r['request_reference'] == old['request_reference']))
replacement = ext_deepcopy(item)
for (field, target_field) in {'work_queue_id': 'queue_id', 'request_reference': 'request_reference', 'buyer_legal_name': 'buyer_name', 'buyer_region': 'buyer_region', 'supplier_legal_name': 'supplier_name', 'supplier_country': 'supplier_country', 'supplier_industry': 'supplier_industry', 'invoice_number': 'invoice_number', 'invoice_id': 'invoice_id', 'currency': 'currency', 'requested_amount': 'requested_amount'}.items():
replacement[field] = new[target_field]
fn_replace_one(result['work_items'], 'request_reference', old['request_reference'], replacement)
fn_replace_one(result['all_targets'], 'target_id', old['target_id'], new)
released = result['release_by_request'].pop(old['request_reference'])
if released != new['position']:
raise ValueError('Replacement changes request release timing')
result['release_by_request'][new['request_reference']] = released
active = ext_deepcopy(new)
(active['advance_rate_percent'], active['discount_rate_percent']) = current_terms[new['rule_atom_id']]
result['targets'][slot - 1] = active
limits = {row['credit_limit_id']: row for row in result['entities']['credit_limit']}
result['task_baseline_limits'] = {target['credit_limit_id']: {key: float(limits[target['credit_limit_id']][key]) for key in ('used_amount', 'available_amount')} for target in result['targets']}
return result
def fn_public_task_2(task_id):
task = fn_public_task_3(task_id)
task['completion'].pop('verification_required')
task['completion'].pop('verification_evidence')
task['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'finalize_factoring_advance completion_receipt', 'proves': "the submitted advance's completed settlement and matched reconciliation"}
task['budget']['mechanism'] = task['budget']['mechanism'].replace('Exact timeline verification costs 1.', 'An exact invoice_id-only timeline request for your own successful settlement in this episode returns only that completion receipt for zero work units and zero call/write quota; other timeline reads cost 1.')
return task
def fn__opaque(prefix, *parts, length=12):
seed = '|'.join((str(part) for part in parts))
value = mod_hashlib.sha256(f'scf-authority-v5|{seed}'.encode('utf-8')).hexdigest()
return f'{prefix}-{value[:length]}'
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__fixture():
base = fn__fixture_3()
entities = ext_deepcopy(base['entities'])
entities['invoice'] = []
for (index, row) in enumerate(entities['credit_limit'], 1):
row['limit_amount'] = 100000.0
row['used_amount'] = float(index * 100)
row['available_amount'] = float(100000 - index * 100)
for index in range(5, 17):
rows = fn__profile_entities(DATA_PROFILE_BY_RULE[f'R{index:02d}'], index)
for (entity_type, values) in rows.items():
entities[entity_type].extend(values)
targets = [row for task_id in DATA_TASK_IDS for row in fn_stream_targets(task_id)]
for target in targets:
for invoice in (fn__invoice_row(target), fn__invoice_row(target, decoy=True)):
entities['invoice'].append(invoice)
fixture = {'entities': entities, 'queues': ext_deepcopy(base['queues']), 'work_items': [{'work_queue_id': target['queue_id'], 'request_reference': target['request_reference'], 'buyer_legal_name': target['buyer_name'], 'buyer_region': target['buyer_region'], 'supplier_legal_name': target['supplier_name'], 'supplier_country': target['supplier_country'], 'supplier_industry': target['supplier_industry'], 'invoice_number': target['invoice_number'], 'invoice_id': target['invoice_id'], 'currency': target['currency'], 'requested_amount': target['requested_amount'], 'instruction': 'Use the current program maximum advance rate, standard discount, and current funding authority, then settle the factoring advance.'} for target in targets], 'targets': targets, 'release_by_invoice': {}, 'release_by_request': {}}
for target in targets:
fixture['release_by_invoice'][target['invoice_id']] = target['position']
fixture['release_by_invoice'][f"invoice-decoy-{target['invoice_id'].removeprefix('invoice-')}"] = target['position']
fixture['release_by_request'][target['request_reference']] = target['position']
fixture['baseline_limits'] = {row['credit_limit_id']: {'used_amount': row['used_amount'], 'available_amount': row['available_amount']} for row in fixture['entities']['credit_limit']}
return fixture
def fn__error(code, message):
return {'status': 'error', 'data': {'status': 'failed', 'error_code': code}, 'message': message}
def fn__opaque_2(prefix, *parts, length=12):
seed = '|'.join((str(part) for part in parts))
value = mod_hashlib.sha256(f'scf-authority-v3|{seed}'.encode('utf-8')).hexdigest()
return f'{prefix}-{value[:length]}'
def fn_stream_targets(task_id):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown stream task: {task_id}')
return tuple((ext_deepcopy(row) for row in fn__catalog()[task_id]))
def fn_opaque_event_id(task_id):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown stream task: {task_id}')
refs = [row['request_reference'] for row in fn_stream_targets(task_id)]
return fn__opaque('EV', task_id, refs, length=12).upper()
def fn_stream_targets_2(task_id):
targets = list(fn_stream_targets(task_id))
for (slot, pair) in DATA_REPLACEMENTS.get(task_id, {}).items():
targets[slot - 1] = fn__target(DATA_TASK_IDS.index(task_id) + 1, slot, *pair)
return tuple(targets)
def fn__invoice_row(target, *, decoy=False):
suffix = target['invoice_id'].removeprefix('invoice-')
amount = target['requested_amount'] + (111.0 if decoy else 0.0)
return {'invoice_id': f'invoice-decoy-{suffix}' if decoy else target['invoice_id'], 'invoice_number': f"DECOY-{target['invoice_number']}" if decoy else target['invoice_number'], 'buyer_id': target['buyer_id'], 'supplier_id': target['supplier_id'], 'program_id': target['program_id'], 'credit_limit_id': target['credit_limit_id'], 'currency': target['currency'], 'description': 'Ineligible comparison invoice' if decoy else 'Assigned finance invoice', 'gross_amount': amount, 'approved_amount': amount, 'paid_amount': 0.0, 'outstanding_amount': amount, 'status': 'disputed' if decoy else 'approved', 'payment_status': 'unpaid', 'eligible_for_factoring': not decoy, 'issue_date': f"2026-06-{target['position']:02d}T09:00:00Z", 'due_date': '2026-11-15T09:00:00Z', 'approved_at': '2026-06-01T09:00:00Z', 'created_at': f"2026-06-{target['position']:02d}T09:00:00Z", 'updated_at': f"2026-06-{target['position']:02d}T09:00:00Z"}
def fn_replace_one(rows, key, old_value, replacement):
matches = [i for (i, row) in enumerate(rows) if row[key] == old_value]
if len(matches) != 1:
raise ValueError(f'Expected one unopened fixture record for {key}')
rows[matches[0]] = ext_deepcopy(replacement)
def fn_public_task_3(task_id):
task = fn_public_task_4(task_id)
if task_id not in DATA_REPLACEMENTS:
return task
for slot in DATA_REPLACEMENTS[task_id]:
target = fn_stream_targets_2(task_id)[slot - 1]
task['targets'][slot - 1].update({key: target[key] for key in ('request_reference', 'service_band', 'routing_track')})
task['task_id'] = 'EV-' + mod_engine.digest(['scf-authority-lifecycle-evolution-v1', task_id, task['targets']])[:12].upper()
return task
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__fixture_2():
base = fn__fixture_3()
entities = ext_deepcopy(base['entities'])
entities['invoice'] = []
for (index, row) in enumerate(entities['credit_limit'], 1):
row['limit_amount'] = 100000.0
row['used_amount'] = float(index * 100)
row['available_amount'] = float(100000 - index * 100)
for index in range(5, 17):
rows = fn__profile_entities(DATA_PROFILE_BY_RULE[f'R{index:02d}'], index)
for (entity_type, values) in rows.items():
entities[entity_type].extend(values)
targets = [row for task_id in DATA_TASK_IDS for row in fn_stream_targets_3(task_id)]
for target in targets:
for invoice in (fn__invoice_row(target), fn__invoice_row(target, decoy=True)):
entities['invoice'].append(invoice)
fixture = {'entities': entities, 'queues': ext_deepcopy(base['queues']), 'work_items': [{'work_queue_id': target['queue_id'], 'request_reference': target['request_reference'], 'buyer_legal_name': target['buyer_name'], 'buyer_region': target['buyer_region'], 'supplier_legal_name': target['supplier_name'], 'supplier_country': target['supplier_country'], 'supplier_industry': target['supplier_industry'], 'invoice_number': target['invoice_number'], 'invoice_id': target['invoice_id'], 'currency': target['currency'], 'requested_amount': target['requested_amount'], 'instruction': 'Use the current program maximum advance rate, standard discount, and current funding authority, then settle the factoring advance.'} for target in targets], 'targets': targets, 'release_by_invoice': {}, 'release_by_request': {}}
for target in targets:
fixture['release_by_invoice'][target['invoice_id']] = target['position']
fixture['release_by_invoice'][f"invoice-decoy-{target['invoice_id'].removeprefix('invoice-')}"] = target['position']
fixture['release_by_request'][target['request_reference']] = target['position']
fixture['baseline_limits'] = {row['credit_limit_id']: {'used_amount': row['used_amount'], 'available_amount': row['available_amount']} for row in fixture['entities']['credit_limit']}
return fixture
def fn__fixture_3():
entities = {name: [] for name in DATA_ENTITY_ID_FIELDS}
queues = [('FQ-4V', 'SB-ALPHA', 'Domestic intake'), ('FQ-7K', 'SB-ALPHA', 'Domestic exception desk'), ('FQ-2M', 'SB-BRAVO', 'Food supply intake'), ('FQ-9P', 'SB-BRAVO', 'Food supply overflow'), ('FQ-5R', 'SB-CHARLIE', 'Healthcare intake'), ('FQ-8C', 'SB-CHARLIE', 'Healthcare exception desk'), ('FQ-3H', 'SB-DELTA', 'International intake'), ('FQ-6X', 'SB-DELTA', 'International overflow')]
buyer_rows = [('buyer-7q2m', 'Aster Retail Cooperative', 'west', 'low', 'USD', 'active'), ('buyer-3m8k', 'Beacon Foods Network', 'southeast', 'medium', 'EUR', 'active'), ('buyer-9k4d', 'Cedar Medical Group', 'northeast', 'low', 'GBP', 'active'), ('buyer-5t1p', 'Delta Hospitality Holdings', 'emea', 'medium', 'EUR', 'active'), ('buyer-1a6n', 'Atlas Retail Services', 'west', 'high', 'USD', 'watchlist'), ('buyer-8w3c', 'Bayside Foods Cooperative', 'southeast', 'high', 'EUR', 'paused'), ('buyer-2f7r', 'Civic Health Partners', 'northeast', 'medium', 'GBP', 'watchlist'), ('buyer-6j5x', 'Dover Lodging Group', 'emea', 'high', 'EUR', 'paused')]
for (buyer_id, name, region, risk, currency, status) in buyer_rows:
entities['buyer'].append({'buyer_id': buyer_id, 'legal_name': name, 'status': status, 'risk_tier': risk, 'region': region, 'credit_rating': 'A' if risk == 'low' else 'BBB', 'default_currency': currency, 'payment_terms_days': 30, 'created_at': '2026-01-01T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'})
supplier_rows = [('supplier-4h9v', 'Northwind Packaging Ltd', 'US', 'packaging', 'active', 'verified'), ('supplier-8c2q', 'Blue Harbor Produce GmbH', 'DE', 'produce', 'active', 'verified'), ('supplier-6p5s', 'Silverline Medical Supply', 'GB', 'medical', 'active', 'verified'), ('supplier-2r7n', 'Orchard Linen Works', 'NL', 'textiles', 'active', 'verified'), ('supplier-1x4b', 'Pioneer Packaging Co', 'US', 'packaging', 'active', 'expired'), ('supplier-7d3f', 'Greenbank Produce GmbH', 'DE', 'produce', 'suspended', 'verified'), ('supplier-9l6a', 'Riverside Medical Supply', 'GB', 'medical', 'active', 'under_review'), ('supplier-5g8e', 'Harbor Linen Works', 'NL', 'textiles', 'active', 'expired')]
for (index, (supplier_id, name, country, industry, status, kyc_status)) in enumerate(supplier_rows, start=1):
entities['supplier'].append({'supplier_id': supplier_id, 'legal_name': name, 'status': status, 'country': country, 'industry': industry, 'primary_contact': f'Contact {index}', 'contact_email': f'contact{index}@example.test', 'preferred_currency': 'USD', 'created_at': '2026-01-01T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'})
entities['supplier_kyc_profile'].append({'supplier_kyc_profile_id': f'supplier-kyc-{index:02d}', 'supplier_id': supplier_id, 'status': kyc_status, 'risk_score': 10 + index, 'risk_band': 'low' if kyc_status == 'verified' else 'high', 'beneficial_owner_verified': kyc_status == 'verified', 'sanctions_screen_status': 'clear', 'tax_document_status': 'accepted', 'reviewed_at': '2026-05-01T09:00:00Z', 'next_review_at': '2026-12-01T09:00:00Z', 'created_at': '2026-04-30T09:00:00Z', 'updated_at': '2026-05-01T09:00:00Z'})
target_specs = [{'target_id': 'finance-outcome-a', 'request_reference': 'SCF-ALPHA-271', 'service_band': 'SB-ALPHA', 'queue_id': 'FQ-7K', 'buyer_id': 'buyer-7q2m', 'buyer_name': 'Aster Retail Cooperative', 'buyer_region': 'west', 'supplier_id': 'supplier-4h9v', 'supplier_name': 'Northwind Packaging Ltd', 'supplier_country': 'US', 'supplier_industry': 'packaging', 'program_id': 'program-4n7x', 'credit_limit_id': 'limit-8v2h', 'invoice_id': 'invoice-7v2q', 'invoice_number': 'AP-2609-1042', 'currency': 'USD', 'requested_amount': 1200.0, 'advance_rate_percent': 0.713, 'discount_rate_percent': 0.017, 'waterfall_id': 'payment-waterfall-6k1r-active'}, {'target_id': 'finance-outcome-b', 'request_reference': 'SCF-BRAVO-684', 'service_band': 'SB-BRAVO', 'queue_id': 'FQ-2M', 'buyer_id': 'buyer-3m8k', 'buyer_name': 'Beacon Foods Network', 'buyer_region': 'southeast', 'supplier_id': 'supplier-8c2q', 'supplier_name': 'Blue Harbor Produce GmbH', 'supplier_country': 'DE', 'supplier_industry': 'produce', 'program_id': 'program-9c3w', 'credit_limit_id': 'limit-2q9m', 'invoice_id': 'invoice-3k8p', 'invoice_number': 'BF-2609-2087', 'currency': 'EUR', 'requested_amount': 1450.0, 'advance_rate_percent': 0.827, 'discount_rate_percent': 0.023, 'waterfall_id': 'payment-waterfall-3d8p-active'}, {'target_id': 'finance-outcome-c', 'request_reference': 'SCF-CHARLIE-395', 'service_band': 'SB-CHARLIE', 'queue_id': 'FQ-8C', 'buyer_id': 'buyer-9k4d', 'buyer_name': 'Cedar Medical Group', 'buyer_region': 'northeast', 'supplier_id': 'supplier-6p5s', 'supplier_name': 'Silverline Medical Supply', 'supplier_country': 'GB', 'supplier_industry': 'medical', 'program_id': 'program-2b6f', 'credit_limit_id': 'limit-7m4c', 'invoice_id': 'invoice-9d4n', 'invoice_number': 'CM-2609-3314', 'currency': 'GBP', 'requested_amount': 980.0, 'advance_rate_percent': 0.764, 'discount_rate_percent': 0.014, 'waterfall_id': 'payment-waterfall-8h5t-active'}, {'target_id': 'finance-outcome-d', 'request_reference': 'SCF-DELTA-812', 'service_band': 'SB-DELTA', 'queue_id': 'FQ-3H', 'buyer_id': 'buyer-5t1p', 'buyer_name': 'Delta Hospitality Holdings', 'buyer_region': 'emea', 'supplier_id': 'supplier-2r7n', 'supplier_name': 'Orchard Linen Works', 'supplier_country': 'NL', 'supplier_industry': 'textiles', 'program_id': 'program-5j1s', 'credit_limit_id': 'limit-4x6b', 'invoice_id': 'invoice-2f7m', 'invoice_number': 'DH-2609-4471', 'currency': 'EUR', 'requested_amount': 1730.0, 'advance_rate_percent': 0.891, 'discount_rate_percent': 0.019, 'waterfall_id': 'payment-waterfall-1q7v-active'}]
queue_rows = [{'work_queue_id': queue_id, 'service_band': band, 'label': label} for (queue_id, band, label) in queues]
work_items = []
for target in target_specs:
work_items.append({'work_queue_id': target['queue_id'], 'request_reference': target['request_reference'], 'buyer_legal_name': target['buyer_name'], 'buyer_region': target['buyer_region'], 'supplier_legal_name': target['supplier_name'], 'supplier_country': target['supplier_country'], 'supplier_industry': target['supplier_industry'], 'invoice_number': target['invoice_number'], 'currency': target['currency'], 'requested_amount': target['requested_amount'], 'instruction': 'Use the current program maximum advance rate and standard discount, then settle the factoring advance.'})
for (index, target) in enumerate(target_specs, start=1):
entities['program'].extend([{'program_id': target['program_id'], 'buyer_id': target['buyer_id'], 'program_name': f'Current program {index}', 'program_type': 'invoice_factoring', 'currency': target['currency'], 'status': 'active', 'max_advance_rate_percent': target['advance_rate_percent'], 'base_discount_rate_percent': target['discount_rate_percent'], 'settlement_terms_days': 15, 'created_at': '2026-01-01T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'}, {'program_id': f'program-decoy-{index}', 'buyer_id': target['buyer_id'], 'program_name': f'Retired program {index}', 'program_type': 'invoice_factoring', 'currency': target['currency'], 'status': 'closed', 'max_advance_rate_percent': round(target['advance_rate_percent'] - 0.1, 3), 'base_discount_rate_percent': round(target['discount_rate_percent'] + 0.01, 3), 'settlement_terms_days': 30, 'created_at': '2025-01-01T09:00:00Z', 'updated_at': '2025-12-01T09:00:00Z'}])
baseline_used = float(200 * index)
limit_amount = float(10000 + index * 1000)
entities['credit_limit'].append({'credit_limit_id': target['credit_limit_id'], 'buyer_id': target['buyer_id'], 'supplier_id': target['supplier_id'], 'program_id': target['program_id'], 'currency': target['currency'], 'limit_amount': limit_amount, 'used_amount': baseline_used, 'available_amount': limit_amount - baseline_used, 'status': 'active', 'risk_grade': 'strong', 'approved_by': 'Credit Committee', 'effective_from': '2026-01-01T09:00:00Z', 'effective_until': None, 'created_at': '2026-01-01T09:00:00Z', 'updated_at': '2026-05-20T09:00:00Z'})
entities['invoice'].extend([{'invoice_id': target['invoice_id'], 'invoice_number': target['invoice_number'], 'buyer_id': target['buyer_id'], 'supplier_id': target['supplier_id'], 'program_id': target['program_id'], 'credit_limit_id': target['credit_limit_id'], 'currency': target['currency'], 'description': f'T01 target invoice {index}', 'gross_amount': target['requested_amount'], 'approved_amount': target['requested_amount'], 'paid_amount': 0.0, 'outstanding_amount': target['requested_amount'], 'status': 'approved', 'payment_status': 'unpaid', 'eligible_for_factoring': True, 'issue_date': '2026-05-01T09:00:00Z', 'due_date': '2026-10-15T09:00:00Z', 'approved_at': '2026-05-02T09:00:00Z', 'created_at': '2026-05-01T09:00:00Z', 'updated_at': '2026-05-02T09:00:00Z'}, {'invoice_id': f'invoice-decoy-{index}', 'invoice_number': f'DECOY-2609-{index:04d}', 'buyer_id': target['buyer_id'], 'supplier_id': target['supplier_id'], 'program_id': target['program_id'], 'credit_limit_id': target['credit_limit_id'], 'currency': target['currency'], 'description': f'Ineligible comparison invoice {index}', 'gross_amount': target['requested_amount'] + 111.0, 'approved_amount': target['requested_amount'] + 111.0, 'paid_amount': 0.0, 'outstanding_amount': target['requested_amount'] + 111.0, 'status': 'disputed', 'payment_status': 'unpaid', 'eligible_for_factoring': False, 'issue_date': '2026-04-01T09:00:00Z', 'due_date': '2026-09-15T09:00:00Z', 'approved_at': '2026-04-02T09:00:00Z', 'created_at': '2026-04-01T09:00:00Z', 'updated_at': '2026-04-02T09:00:00Z'}])
allocation_rules = [{'rank': 1, 'allocation_target': 'platform_fee', 'percentage': 0.02}, {'rank': 2, 'allocation_target': 'funder_advance', 'percentage': 0.9}, {'rank': 3, 'allocation_target': 'supplier_reserve', 'percentage': 0.07}, {'rank': 4, 'allocation_target': 'buyer_rebate', 'percentage': 0.01}]
entities['payment_waterfall'].extend([{'payment_waterfall_id': target['waterfall_id'], 'program_id': target['program_id'], 'buyer_id': target['buyer_id'], 'currency': target['currency'], 'name': f'Current allocation {index}', 'status': 'active', 'priority_rules': allocation_rules, 'reserve_release_days': 30, 'effective_from': '2026-05-01T09:00:00Z', 'effective_until': None, 'created_at': '2026-05-01T09:00:00Z', 'updated_at': '2026-05-01T09:00:00Z'}, {'payment_waterfall_id': f'payment-waterfall-retired-{index}', 'program_id': target['program_id'], 'buyer_id': target['buyer_id'], 'currency': target['currency'], 'name': f'Retired allocation {index}', 'status': 'retired', 'priority_rules': allocation_rules, 'reserve_release_days': 45, 'effective_from': '2025-01-01T09:00:00Z', 'effective_until': '2026-04-30T09:00:00Z', 'created_at': '2025-01-01T09:00:00Z', 'updated_at': '2026-04-30T09:00:00Z'}])
baseline_limits = {row['credit_limit_id']: {'used_amount': row['used_amount'], 'available_amount': row['available_amount']} for row in entities['credit_limit']}
return {'entities': entities, 'queues': queue_rows, 'work_items': work_items, 'targets': target_specs, 'baseline_limits': baseline_limits}
def fn__profile_entities(profile, index):
timestamp = '2026-05-20T09:00:00Z'
buyer = {'buyer_id': profile['buyer_id'], 'legal_name': profile['buyer_name'], 'status': 'active', 'risk_tier': profile['buyer_risk'], 'region': profile['buyer_region'], 'credit_rating': 'A' if profile['buyer_risk'] == 'low' else 'BBB', 'default_currency': profile['currency'], 'payment_terms_days': 30, 'created_at': '2026-01-01T09:00:00Z', 'updated_at': timestamp}
supplier = {'supplier_id': profile['supplier_id'], 'legal_name': profile['supplier_name'], 'status': 'active', 'country': profile['supplier_country'], 'industry': profile['supplier_industry'], 'primary_contact': f'Operations contact {index}', 'contact_email': f'ops{index}@example.test', 'preferred_currency': profile['currency'], 'created_at': '2026-01-01T09:00:00Z', 'updated_at': timestamp}
kyc = {'supplier_kyc_profile_id': f'supplier-kyc-stream-{index:02d}', 'supplier_id': profile['supplier_id'], 'status': 'verified', 'risk_score': 10 + index, 'risk_band': 'low', 'beneficial_owner_verified': True, 'sanctions_screen_status': 'clear', 'tax_document_status': 'accepted', 'reviewed_at': '2026-05-01T09:00:00Z', 'next_review_at': '2026-12-01T09:00:00Z', 'created_at': '2026-04-30T09:00:00Z', 'updated_at': '2026-05-01T09:00:00Z'}
program = {'program_id': profile['program_id'], 'buyer_id': profile['buyer_id'], 'program_name': f'Current finance program {index:02d}', 'program_type': 'invoice_factoring', 'currency': profile['currency'], 'status': 'active', 'max_advance_rate_percent': profile['advance_rate_percent'], 'base_discount_rate_percent': profile['discount_rate_percent'], 'settlement_terms_days': 15, 'created_at': '2026-01-01T09:00:00Z', 'updated_at': timestamp}
closed_program = {**program, 'program_id': f'program-retired-stream-{index:02d}', 'program_name': f'Retired finance program {index:02d}', 'status': 'closed', 'max_advance_rate_percent': round(profile['advance_rate_percent'] - 0.08, 3), 'base_discount_rate_percent': round(profile['discount_rate_percent'] + 0.01, 3), 'settlement_terms_days': 30, 'updated_at': '2025-12-01T09:00:00Z'}
limit = {'credit_limit_id': profile['credit_limit_id'], 'buyer_id': profile['buyer_id'], 'supplier_id': profile['supplier_id'], 'program_id': profile['program_id'], 'currency': profile['currency'], 'limit_amount': 100000.0, 'used_amount': float(index * 100), 'available_amount': float(100000 - index * 100), 'status': 'active', 'risk_grade': 'strong', 'approved_by': 'Credit Committee', 'effective_from': '2026-01-01T09:00:00Z', 'effective_until': None, 'created_at': '2026-01-01T09:00:00Z', 'updated_at': timestamp}
allocation = [{'rank': 1, 'allocation_target': 'platform_fee', 'percentage': 0.02}, {'rank': 2, 'allocation_target': 'funder_advance', 'percentage': 0.9}, {'rank': 3, 'allocation_target': 'supplier_reserve', 'percentage': 0.07}, {'rank': 4, 'allocation_target': 'buyer_rebate', 'percentage': 0.01}]
waterfall = {'payment_waterfall_id': profile['waterfall_id'], 'program_id': profile['program_id'], 'buyer_id': profile['buyer_id'], 'currency': profile['currency'], 'name': f'Current allocation {index:02d}', 'status': 'active', 'priority_rules': allocation, 'reserve_release_days': 30, 'effective_from': '2026-05-01T09:00:00Z', 'effective_until': None, 'created_at': '2026-05-01T09:00:00Z', 'updated_at': '2026-05-01T09:00:00Z'}
retired = {**waterfall, 'payment_waterfall_id': f'payment-waterfall-retired-stream-{index:02d}', 'name': f'Retired allocation {index:02d}', 'status': 'retired', 'reserve_release_days': 45, 'effective_from': '2025-01-01T09:00:00Z', 'effective_until': '2026-04-30T09:00:00Z', 'updated_at': '2026-04-30T09:00:00Z'}
return {'buyer': [buyer], 'supplier': [supplier], 'supplier_kyc_profile': [kyc], 'program': [program, closed_program], 'credit_limit': [limit], 'payment_waterfall': [waterfall, retired]}
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__catalog():
result = {task_id: tuple((fn__target(position, slot, structure_id, rule_id) for (slot, (structure_id, rule_id)) in enumerate(DATA_TASK_BLUEPRINT[task_id], 1))) for (position, task_id) in enumerate(DATA_TASK_IDS, 1)}
flattened = [row for task in result.values() for row in task]
for key in ('target_id', 'request_reference', 'invoice_id', 'invoice_number'):
if len({row[key] for row in flattened}) != 64:
raise ValueError(f'stream target field is not unique: {key}')
return result
def fn__target(position, slot, structure_id, rule_id):
profile = DATA_PROFILE_BY_RULE[rule_id]
(queue_id, service_band) = DATA_STRUCTURE_ATOMS[structure_id]
token = fn__opaque('x', position, slot, structure_id, rule_id, length=14).split('-', 1)[1]
amount = float(850 + (position * 173 + slot * 67 + int(rule_id[1:]) * 41) % 1150)
return {'position': position, 'slot': slot, 'target_id': f'finance-outcome-{token}', 'request_reference': f'SCF-{token[:5].upper()}-{token[5:10].upper()}', 'service_band': service_band, 'routing_track': DATA_STRUCTURE_TRACKS[structure_id], 'queue_id': queue_id, 'buyer_id': profile['buyer_id'], 'buyer_name': profile['buyer_name'], 'buyer_region': profile['buyer_region'], 'supplier_id': profile['supplier_id'], 'supplier_name': profile['supplier_name'], 'supplier_country': profile['supplier_country'], 'supplier_industry': profile['supplier_industry'], 'program_id': profile['program_id'], 'credit_limit_id': profile['credit_limit_id'], 'invoice_id': f'invoice-{token}', 'invoice_number': f'IV-{token[:6].upper()}-{token[6:10].upper()}', 'currency': profile['currency'], 'requested_amount': amount, 'advance_rate_percent': profile['advance_rate_percent'], 'discount_rate_percent': profile['discount_rate_percent'], 'waterfall_id': profile['waterfall_id'], 'structure_atom_id': structure_id, 'rule_atom_id': rule_id}
def fn_public_task_4(task_id):
return {'schema': 'rescopebench-supply-chain-finance-task/v5', 'case_id': 'supply_chain_finance_c_05_10_53', 'task_id': fn_opaque_event_id(task_id), 'objective': 'Complete as many listed invoice-finance requests as possible in listed priority order. Use current public evidence for each request and preserve credit, approval, payment, ledger, and reconciliation invariants.', 'targets': [{'request_reference': target['request_reference'], 'service_band': target['service_band'], 'routing_track': target['routing_track'], 'requirement': 'Fund the full eligible invoice balance under current program terms and authority, then complete settlement and matched reconciliation.'} for target in fn_stream_targets(task_id)], 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True, 'verification_evidence': 'the successful finalize_factoring_advance completion_receipt; a duplicate timeline read is optional'}, 'budget': {'kind': 'finance_work_units', 'allowance': 73, 'mechanism': 'Exact queue lookup costs 2; funding-authority and credit-delegation inspections cost 7 each; bounded lists cost 2 plus returned rows; submit costs 5 and finalize costs 10. Exact timeline verification costs 1. A failed admitted submit costs 6.'}, 'status': 'candidate_model_validation', 'runnable': True}
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__fixture_4():
fixture = fn__fixture_3()
entities = ext_deepcopy(fixture['entities'])
queues = ext_deepcopy(fixture['queues'])
for (index, row) in enumerate(entities['credit_limit'], 1):
row['limit_amount'] = 100000.0
row['used_amount'] = float(index * 100)
row['available_amount'] = float(100000 - index * 100)
for index in range(5, 17):
rows = fn__profile_entities(DATA_PROFILE_BY_RULE[f'R{index:02d}'], index)
for (entity_type, values) in rows.items():
entities[entity_type].extend(values)
for task_id in DATA_TASK_IDS[1:]:
for target in fn_stream_targets_4(task_id):
entities['invoice'].extend((fn__invoice_row(target), fn__invoice_row(target, decoy=True)))
targets = [row for task_id in DATA_TASK_IDS for row in fn_stream_targets_4(task_id)]
work_items = [{'work_queue_id': target['queue_id'], 'request_reference': target['request_reference'], 'buyer_legal_name': target['buyer_name'], 'buyer_region': target['buyer_region'], 'supplier_legal_name': target['supplier_name'], 'supplier_country': target['supplier_country'], 'supplier_industry': target['supplier_industry'], 'invoice_number': target['invoice_number'], 'invoice_id': target['invoice_id'], 'currency': target['currency'], 'requested_amount': target['requested_amount'], 'instruction': 'Use the current program maximum advance rate, standard discount, and current funding authority, then settle the factoring advance.'} for target in targets]
baseline_limits = {row['credit_limit_id']: {'used_amount': row['used_amount'], 'available_amount': row['available_amount']} for row in entities['credit_limit']}
release_by_invoice: dict[str, int] = {}
release_by_request: dict[str, int] = {}
for target in targets:
release_by_invoice[target['invoice_id']] = target['position']
release_by_invoice[f"invoice-decoy-{target['invoice_id'].removeprefix('invoice-')}"] = target['position']
release_by_request[target['request_reference']] = target['position']
return {'entities': entities, 'queues': queues, 'work_items': work_items, 'targets': targets, 'baseline_limits': baseline_limits, 'release_by_invoice': release_by_invoice, 'release_by_request': release_by_request}
def fn_stream_targets_3(task_id):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown stream task: {task_id}')
return tuple((ext_deepcopy(row) for row in fn__catalog_2()[task_id]))
def fn_stream_targets_4(task_id):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown stream task: {task_id}')
return tuple((ext_deepcopy(row) for row in fn__catalog_3()[task_id]))
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__catalog_2():
result = {task_id: tuple((fn__target_2(position, slot, structure_id, rule_id) for (slot, (structure_id, rule_id)) in enumerate(DATA_TASK_BLUEPRINT_2[task_id], 1))) for (position, task_id) in enumerate(DATA_TASK_IDS, 1)}
flattened = [row for task in result.values() for row in task]
for key in ('target_id', 'request_reference', 'invoice_id', 'invoice_number'):
if len({row[key] for row in flattened}) != 64:
raise ValueError(f'stream target field is not unique: {key}')
return result
@lru_cache(**{'maxsize': 1, 'typed': False})
def fn__catalog_3():
result = {task_id: tuple((fn__target_3(position, slot, structure_id, rule_id) for (slot, (structure_id, rule_id)) in enumerate(DATA_TASK_BLUEPRINT_3[task_id], 1))) for (position, task_id) in enumerate(DATA_TASK_IDS, 1)}
flattened = [row for task in result.values() for row in task]
for key in ('target_id', 'request_reference', 'invoice_id', 'invoice_number'):
if len({row[key] for row in flattened}) != 64:
raise ValueError(f'stream target field is not unique: {key}')
return result
def fn__target_2(position, slot, structure_id, rule_id):
profile = DATA_PROFILE_BY_RULE[rule_id]
(queue_id, service_band) = DATA_STRUCTURE_ATOMS[structure_id]
token = fn__opaque_3('x', position, slot, structure_id, rule_id, length=14).split('-', 1)[1]
amount = float(850 + (position * 173 + slot * 67 + int(rule_id[1:]) * 41) % 1150)
return {'position': position, 'slot': slot, 'target_id': f'finance-outcome-{token}', 'request_reference': f'SCF-{token[:5].upper()}-{token[5:10].upper()}', 'service_band': service_band, 'routing_track': DATA_STRUCTURE_TRACKS[structure_id], 'queue_id': queue_id, 'buyer_id': profile['buyer_id'], 'buyer_name': profile['buyer_name'], 'buyer_region': profile['buyer_region'], 'supplier_id': profile['supplier_id'], 'supplier_name': profile['supplier_name'], 'supplier_country': profile['supplier_country'], 'supplier_industry': profile['supplier_industry'], 'program_id': profile['program_id'], 'credit_limit_id': profile['credit_limit_id'], 'invoice_id': f'invoice-{token}', 'invoice_number': f'IV-{token[:6].upper()}-{token[6:10].upper()}', 'currency': profile['currency'], 'requested_amount': amount, 'advance_rate_percent': profile['advance_rate_percent'], 'discount_rate_percent': profile['discount_rate_percent'], 'waterfall_id': profile['waterfall_id'], 'structure_atom_id': structure_id, 'rule_atom_id': rule_id}
def fn__target_3(position, slot, structure_id, rule_id):
profile = DATA_PROFILE_BY_RULE[rule_id]
(queue_id, service_band) = DATA_STRUCTURE_ATOMS[structure_id]
if position == 1:
original = ext_deepcopy(fn__fixture_3()['targets'][slot - 1])
original.update({'position': position, 'slot': slot, 'structure_atom_id': structure_id, 'rule_atom_id': rule_id, 'routing_track': DATA_STRUCTURE_TRACKS[structure_id]})
return original
token = fn__opaque_2('x', position, slot, structure_id, rule_id, length=14).split('-', 1)[1]
amount = float(850 + (position * 173 + slot * 67 + int(rule_id[1:]) * 41) % 1150)
return {'position': position, 'slot': slot, 'target_id': f'finance-outcome-{token}', 'request_reference': f'SCF-{token[:5].upper()}-{token[5:10].upper()}', 'service_band': service_band, 'routing_track': DATA_STRUCTURE_TRACKS[structure_id], 'queue_id': queue_id, 'buyer_id': profile['buyer_id'], 'buyer_name': profile['buyer_name'], 'buyer_region': profile['buyer_region'], 'supplier_id': profile['supplier_id'], 'supplier_name': profile['supplier_name'], 'supplier_country': profile['supplier_country'], 'supplier_industry': profile['supplier_industry'], 'program_id': profile['program_id'], 'credit_limit_id': profile['credit_limit_id'], 'invoice_id': f'invoice-{token}', 'invoice_number': f'IV-{token[:6].upper()}-{token[6:10].upper()}', 'currency': profile['currency'], 'requested_amount': amount, 'advance_rate_percent': profile['advance_rate_percent'], 'discount_rate_percent': profile['discount_rate_percent'], 'waterfall_id': profile['waterfall_id'], 'structure_atom_id': structure_id, 'rule_atom_id': rule_id}
def fn__opaque_3(prefix, *parts, length=12):
seed = '|'.join((str(part) for part in parts))
value = mod_hashlib.sha256(f'scf-authority-v4|{seed}'.encode('utf-8')).hexdigest()
return f'{prefix}-{value[:length]}'
class World:
def _prior_targets_complete(self, target):
return True
def snapshot(self):
value = self._scf_lead_retest_world_snapshot()
if not getattr(self, '_restoring_independent', False):
value['independent_settlement_contract'] = 'scf-independent-settlements-evolution-v3'
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('independent_settlement_contract', None) != 'scf-independent-settlements-evolution-v3':
raise ValueError('SCF independent-settlement snapshot version differs')
self._restoring_independent = True
try:
self._scf_lead_retest_world_restore(value)
finally:
self._restoring_independent = False
if self.snapshot() != snapshot:
raise ValueError('SCF independent-settlement snapshot did not round trip')
def activate_task(self, task_id, **kwargs):
result = self._scf_evolution_activate_task(task_id, **kwargs)
if task_id in DATA_RETEST_TASKS:
self._targets = [self._targets[i] for i in DATA_RETEST_ORDER]
for (slot, row) in enumerate(self._targets, 1):
row['slot'] = slot
result['data']['event_id'] = fn_public_task(task_id)['task_id']
return result
def __init__(self, *args, **kwargs):
self._own_settlements = {}
self._supply_chain_finance_authority_init(*args, **kwargs)
def dispatch(self, name, arguments, actor_id='operator-t01-scf'):
exact = name == 'get_invoice_timeline' and isinstance(arguments, dict) and (set(arguments) == {'invoice_id'}) and isinstance(arguments['invoice_id'], str) and (actor_id == 'operator-t01-scf')
issued = self._own_settlements.get(arguments['invoice_id']) if exact else None
if issued is not None and issued['task_id'] == self._task_id:
before = self.business_hash()
result = {'status': 'success', 'data': {'invoice_id': arguments['invoice_id'], 'confirmation_only': True, 'completion_receipt': ext_deepcopy(issued['receipt']), 'budget': self._budget_receipt(0)}, 'message': 'Receipt for your completed settlement in this episode.'}
self._record_event(name, actor_id, result, before, before, 0)
return result
result = self._supply_chain_finance_authority_dispatch(name, arguments, actor_id)
if name == 'finalize_factoring_advance' and result.get('status') == 'success':
request = self._state.get_entity('factoring_request', arguments['factoring_request_id'], 'factoring_request_id')
self._own_settlements[request['invoice_id']] = {'task_id': self._task_id, 'receipt': ext_deepcopy(result['data']['completion_receipt'])}
return result
def _submit(self, arguments):
outside = self._active_target_by_invoice(arguments['invoice_id']) is None
result = self._supply_chain_finance_authority_submit(arguments)
if outside and result.get('data', {}).get('error_code') == 'INVOICE_NOT_FOUND':
result['data']['error_code'] = 'INVOICE_OUTSIDE_CURRENT_REQUESTS'
result['message'] = "This invoice is not among the current event's requested invoices."
return result
@staticmethod
def _public_receipt(kind, *parts):
payload = '|'.join((str(part) for part in parts))
token = mod_hashlib.sha256(f'scf-v5-receipt|{kind}|{payload}'.encode('utf-8')).hexdigest()
return f'{kind}-{token[:20]}'
def _finalize(self, arguments, actor_id):
result = self._supply_chain_finance_authority_finalize(arguments, actor_id)
if result.get('status') != 'success':
return result
result['data']['completion_receipt'] = {'receipt_id': self._public_receipt('completion', arguments['factoring_request_id'], arguments['payment_amount']), 'factoring_request_id': arguments['factoring_request_id'], 'status': 'settled_and_reconciled', 'verification_complete': True}
return result
def cost(self, before, action, result, after):
if action['tool'] == 'get_invoice_timeline':
return 1
if action['tool'] == 'submit_factoring_request' and result.get('status') != 'success':
return 6
return self._supply_chain_finance_authority_cost(before, action, result, after)
def grade(self, task_id):
grade = self._persistent_supply_chain_finance_adapter_grade(task_id)
for deliverable in grade['deliverables']:
deliverable['diagnostic_score'] = deliverable['score']
deliverable['score'] = 25.0 if deliverable['score'] == 25.0 else 0.0
grade['score'] = sum((row['score'] for row in grade['deliverables']))
grade['completed_artifacts'] = int(grade['score'] // 25.0)
return grade
def apply_drift(self):
before = self.business_hash()
if 'evt-finance-authority-rotation-2026-09-v5' in self._applied_boundary_events:
return {'event_id': 'evt-finance-authority-rotation-2026-09-v5', 'applied': False, 'idempotent_noop': True, 'before_world_sha256': before, 'after_world_sha256': before}
self.authority_moved = True
self.authority = ext_deepcopy(DATA_POST_AUTHORITY)
self._applied_boundary_events.append('evt-finance-authority-rotation-2026-09-v5')
after = self.business_hash()
return {'event_id': 'evt-finance-authority-rotation-2026-09-v5', 'applied': True, 'idempotent_noop': False, 'before_world_sha256': before, 'after_world_sha256': after}
def public_tool_schemas(self, role):
return ext_deepcopy(DATA_TOOLS_2) if role == 'supply_chain_finance_operations' else []
def _active_target_by_request(self, request_reference):
return next((row for row in self._targets if row['request_reference'] == request_reference), None)
def _active_target_by_invoice(self, invoice_id):
return next((row for row in self._targets if row['invoice_id'] == invoice_id), None)
def _inspect_queue(self, arguments):
result = World._persistent_supply_chain_finance_adapter_inspect_queue(self, arguments)
target = self._active_target_by_request(arguments['request_reference'])
if result.get('status') == 'success' and result['data'].get('found') and target:
result['data']['request']['invoice_id'] = target['invoice_id']
return result
def _inspect_funding_authority(self, arguments):
target = self._active_target_by_request(arguments['request_reference'])
if target is None or target['queue_id'] != arguments['work_queue_id']:
return {'status': 'success', 'data': {'status': 'succeeded', 'error_code': None, 'found': False, 'funding_route_candidates': []}, 'message': 'No matching request authority was found'}
candidates = fn__authority_candidates(target['structure_atom_id'], self.authority[target['structure_atom_id']])
return {'status': 'success', 'data': {'status': 'succeeded', 'error_code': None, 'found': True, 'funding_route_candidates': ext_deepcopy(candidates['routes'])}, 'message': 'Funding authority candidates inspected'}
def _inspect_credit_limit(self, arguments):
result = World._persistent_supply_chain_finance_adapter_execute(self, 'inspect_credit_limit', arguments, 'operator-t01-scf')
target = next((row for row in self._targets if row['credit_limit_id'] == arguments['credit_limit_id']), None)
if result.get('status') == 'success' and target:
candidates = fn__authority_candidates(target['structure_atom_id'], self.authority[target['structure_atom_id']])
result['data']['approval_delegation_candidates'] = ext_deepcopy(candidates['delegations'])
return result
def _rename_approval_tasks(self, target, authority, raw_ids):
expected = fn_approval_task_ids(target, authority)
if len(raw_ids) != len(expected):
raise ValueError('raw approval chain does not contain four tasks')
delegate_by_role = {row['role']: row for row in authority['delegations']}
renamed = []
for (old_id, new_id) in zip(raw_ids, expected):
task = self._state.get_entity('approval_task', old_id, 'approval_task_id')
if task is None:
raise ValueError('raw approval task is missing')
delegate = delegate_by_role[task['approver_role']]
updated = self._state.update_entity('approval_task', old_id, {'approval_task_id': new_id, 'authority_scope_id': authority['funding_scope_id'], 'approval_chain_ref': authority['approval_chain_ref'], 'delegation_id': delegate['delegation_id'], 'delegated_principal_id': delegate['principal_id'], 'delegation_status': delegate['status']}, id_field='approval_task_id')
if updated is None:
raise ValueError('approval task rename failed')
renamed.append(new_id)
return renamed
def _execute(self, name, arguments, actor_id):
if name == 'inspect_finance_work_queue':
return self._inspect_queue(arguments)
if name == 'inspect_funding_authority':
return self._inspect_funding_authority(arguments)
if name == 'inspect_credit_limit':
return self._inspect_credit_limit(arguments)
if name == 'submit_factoring_request':
return self._submit(arguments)
if name == 'finalize_factoring_advance':
return self._finalize(arguments, actor_id)
return World._persistent_supply_chain_finance_adapter_execute(self, name, arguments, actor_id)
def business_hash(self):
return fn__hash({'entities': self._state.snapshot()['entities'], 'boundary_events': self._applied_boundary_events, 'authority': self.authority})
@property
def applied_boundary_events(self):
return tuple(self._applied_boundary_events)
@property
def current_terms(self):
result = {}
for (rule_id, profile) in DATA_PROFILE_BY_RULE.items():
program = self._state.get_entity('program', profile['program_id'], 'program_id')
if program is None:
raise ValueError(f'missing program for {rule_id}')
result[rule_id] = (float(program['max_advance_rate_percent']), float(program['base_discount_rate_percent']))
return result
def task_targets(self):
return [{'target_id': row['target_id'], 'request_reference': row['request_reference'], 'service_band': row['service_band']} for row in self._targets]
def current_episode_events(self):
return ext_deepcopy(self._events[self._episode_event_start:])
def _active_position(self):
return DATA_TASK_IDS.index(self._task_id) + 1 if self._task_id in DATA_TASK_IDS else 0
def _visible_state(self):
position = self._active_position()
entities = self._state.snapshot()['entities']
entities['invoice'] = [row for row in entities['invoice'] if self._release_by_invoice.get(row['invoice_id'], 0) <= position]
visible_invoice_ids = {row['invoice_id'] for row in entities['invoice']}
for entity_type in ('factoring_request', 'approval_task', 'early_payment_offer', 'payment', 'reconciliation_item', 'dispute'):
entities[entity_type] = [row for row in entities[entity_type] if row.get('invoice_id') in visible_invoice_ids]
return MemoryState(entities)
def _search_invoices(self, arguments):
result = self._logic.LOGIC_BY_TOOL['search_invoices'](self._visible_state(), **ext_deepcopy(arguments))
_normalize = fn__normalize
normalized = _normalize(result)
if normalized.get('status') == 'success':
for item in normalized['data'].get('invoices', []):
invoice = self._state.get_entity('invoice', item['invoice_id'], 'invoice_id') or {}
item['credit_limit_id'] = invoice.get('credit_limit_id')
item['currency'] = invoice.get('currency')
return normalized
def lineage_hash(self):
return fn__hash(self.snapshot())
def semantic_hash(self, snapshot=None):
return fn__hash(snapshot if snapshot is not None else self.snapshot())
def close(self):
return None
def business_events(self, since=0):
if not isinstance(since, int) or isinstance(since, bool) or since < 0:
raise ValueError('since must be a non-negative integer')
return ext_deepcopy(self._events[since:])
def configure_fault_injection(self, tool_name, after_mutations=1):
if tool_name not in DATA_WRITE_TOOLS or after_mutations < 1:
raise ValueError('fault injection requires a write tool and positive mutation count')
self._state.configure_fault(tool_name, after_mutations)
def _business_hash(self):
return fn__hash(self._state.snapshot())
def _budget_receipt(self, charged):
return {'charged_work_units': charged, 'work_units_used': self._work_units, 'work_units_remaining': self._work_unit_limit - self._work_units, 'call_attempts_used': self._calls, 'call_attempts_remaining': 64 - self._calls, 'write_attempts_used': self._writes, 'write_attempts_remaining': 10 - self._writes}
def _record_event(self, name, actor_id, result, before_hash, after_hash, charged):
self._events.append({'sequence': len(self._events) + 1, 'channel': 'learner', 'tool': name, 'actor_id': actor_id, 'status': result.get('status'), 'error_code': result.get('data', {}).get('error_code'), 'state_hash_before': before_hash, 'state_hash_after': after_hash, **self._budget_receipt(charged)})
def _raw(self, name, arguments):
function = self._logic.LOGIC_BY_TOOL[name]
return fn__normalize(function(self._state, **ext_deepcopy(arguments)))
def _list_queues(self, arguments):
rows = self._queues
if arguments.get('service_band'):
rows = [row for row in rows if row['service_band'] == arguments['service_band']]
offset = arguments.get('offset', 0)
limit = arguments.get('limit', 8)
page = rows[offset:offset + limit]
return fn__success(work_queues=page, count=len(page), total_count=len(rows), offset=offset, limit=limit)
def _require_success(self, result):
if result.get('status') != 'success':
raise Abort(result)
return result['data']
def _result_rows(self, name, result):
if result.get('status') != 'success':
return 0
data = result.get('data', {})
key_by_tool = {'list_finance_work_queues': 'work_queues', 'list_buyers': 'buyers', 'list_suppliers': 'suppliers', 'list_programs': 'programs', 'search_invoices': 'invoices', 'get_invoice_timeline': 'timeline'}
key = key_by_tool.get(name)
return len(data.get(key, [])) if key else 0
def _assert_invariants(self):
for (entity_type, id_field) in DATA_ENTITY_ID_FIELDS.items():
rows = self._state.list_entities(entity_type)
identifiers = [row.get(id_field) for row in rows]
if None in identifiers or len(identifiers) != len(set(identifiers)):
raise ValueError(f'{entity_type} identities are missing or duplicated')
limits = {row['credit_limit_id']: row for row in self._state.list_entities('credit_limit')}
invoices = {row['invoice_id']: row for row in self._state.list_entities('invoice')}
requests = self._state.list_entities('factoring_request')
tasks = {row['approval_task_id']: row for row in self._state.list_entities('approval_task')}
payments = {row['payment_id']: row for row in self._state.list_entities('payment')}
waterfalls = {row['payment_waterfall_id']: row for row in self._state.list_entities('payment_waterfall')}
for (limit_id, limit) in limits.items():
if fn__money(limit['used_amount'] + limit['available_amount']) != fn__money(limit['limit_amount']):
raise ValueError(f'credit limit {limit_id} does not conserve capacity')
baseline = self._baseline_limits.get(limit_id)
if baseline is None:
continue
reserved = sum((fn__money(request.get('requested_amount')) for request in requests if invoices.get(request.get('invoice_id'), {}).get('credit_limit_id') == limit_id and request.get('status') in {'submitted', 'approved', 'funded'}))
if fn__money(limit['used_amount']) != fn__money(baseline['used_amount'] + reserved):
raise ValueError(f'credit limit {limit_id} reservation is inconsistent')
for request in requests:
invoice = invoices.get(request.get('invoice_id'))
if invoice is None:
raise ValueError('factoring request references an unknown invoice')
linked = [tasks.get(task_id) for task_id in request.get('approval_task_ids', [])]
if len(linked) != 4 or any((task is None for task in linked)):
raise ValueError('factoring request does not have four approval tasks')
if {task['approver_role'] for task in linked} != set(DATA_APPROVAL_ROLES):
raise ValueError('factoring request approval roles are incomplete')
if request.get('status') in {'approved', 'funded'}:
if any((task.get('status') != 'approved' for task in linked)):
raise ValueError('approved request has incomplete approval state')
if any((task.get('assigned_to') != 'operator-t01-scf' for task in linked)):
raise ValueError('approval decision is not bound to the authenticated actor')
for payment in payments.values():
invoice = invoices.get(payment.get('invoice_id'))
waterfall = waterfalls.get(payment.get('payment_waterfall_id'))
if invoice is None or waterfall is None:
raise ValueError('payment references an unknown invoice or waterfall')
if payment.get('status') == 'settled':
if waterfall.get('status') != 'active':
raise ValueError('settled payment references a retired waterfall')
allocation = payment.get('allocation_breakdown') or {}
if fn__money(sum((float(value) for value in allocation.values()))) != fn__money(payment['amount']):
raise ValueError('payment allocation does not conserve value')
for invoice in invoices.values():
if fn__money(invoice.get('paid_amount') + invoice.get('outstanding_amount')) != fn__money(invoice.get('gross_amount')):
raise ValueError('invoice paid and outstanding amounts do not conserve value')
def _supply_chain_finance_authority_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-supply-chain-finance-authority/v5':
raise ValueError('unsupported authority-v5 snapshot schema')
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-supply-chain-finance-authority/v4'
self._supply_chain_finance_authority_restore_2(base)
def _scf_lead_retest_world_snapshot(self):
value = self._scf_evolution_snapshot()
value['lead_retest_contract'] = 'scf-lead-retest-lifecycle-evolution-v2'
return value
def _scf_lead_retest_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('lead_retest_contract', None) != 'scf-lead-retest-lifecycle-evolution-v2':
raise ValueError('SCF lead-retest snapshot version differs')
self._scf_evolution_restore(value)
if self.snapshot() != snapshot:
raise ValueError('SCF lead-retest snapshot did not round trip')
def _scf_evolution_activate_task(self, task_id, *, apply_boundary=True):
before = self.snapshot()
try:
index = len(self._activated_tasks)
if index >= len(DATA_TASK_IDS) or DATA_TASK_IDS[index] != task_id:
raise ValueError('out-of-order SCF activation')
if task_id == 'T13' and apply_boundary:
self.apply_drift()
result = World._supply_chain_finance_authority_activate_task(self, task_id, apply_boundary=False)
if task_id in DATA_REPLACEMENTS:
self.restore(fn_activate_coverage(self.snapshot(), task_id, self.current_terms))
self._own_settlements = {}
result['data']['event_id'] = fn_public_task_2(task_id)['task_id']
return result
except Exception:
self.restore(before)
raise
def _supply_chain_finance_authority_init(self, source_root=None, source=None, work_unit_limit=73):
self._supply_chain_finance_authority_init_2(source_root=source_root, source=source, work_unit_limit=work_unit_limit)
fixture = ext_deepcopy(fn__fixture())
self._state = MemoryState(fixture['entities'])
self._queues = fixture['queues']
self._work_items = fixture['work_items']
self._all_targets = fixture['targets']
self._release_by_invoice = fixture['release_by_invoice']
self._release_by_request = fixture['release_by_request']
self._initial_limits = fixture['baseline_limits']
self._targets = []
self._baseline_limits = ext_deepcopy(self._initial_limits)
self._task_baseline_limits = {}
self._task_id = None
self._activated_tasks = []
self._applied_boundary_events = []
self._events = []
self._episode_event_start = 0
self._calls = 0
self._writes = 0
self._work_units = 0
self.authority_moved = False
self.authority = ext_deepcopy(DATA_PRE_AUTHORITY)
self._assert_invariants()
def _supply_chain_finance_authority_dispatch(self, name, arguments, actor_id='operator-t01-scf'):
if self._task_id is None:
return fn__error('TASK_NOT_ACTIVE', 'activate a task before dispatch')
tool = DATA_TOOL_BY_NAME.get(name)
if tool is None:
return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
if actor_id != 'operator-t01-scf':
return fn__error('ACTOR_NOT_AUTHORIZED', 'actor is not an authorized finance operator')
try:
mod_jsonschema.validate(arguments, tool['input_schema'])
except mod_jsonschema.ValidationError:
return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public tool schema')
if self._calls >= 64:
return fn__error('CALL_LIMIT_EXHAUSTED', 'task safety call limit is exhausted')
if name in DATA_WRITE_TOOLS and self._writes >= 10:
return fn__error('WRITE_LIMIT_EXHAUSTED', 'task write-attempt limit is exhausted')
before_state = self._state.snapshot()
before_hash = self.business_hash()
self._state.begin_tool(name)
try:
result = self._execute(name, ext_deepcopy(arguments), actor_id)
if result.get('status') != 'success':
raise Abort(result)
if name in DATA_WRITE_TOOLS:
self._assert_invariants()
except Abort as exc:
self._state.restore(before_state)
result = exc.result
except Exception:
self._state.restore(before_state)
result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without committing state')
finally:
self._state.end_tool()
after_state = self._state.snapshot()
charged = self.cost(before_state, {'tool': name, 'arguments': ext_deepcopy(arguments)}, result, after_state)
if self._work_units + charged > self._work_unit_limit:
self._state.restore(before_state)
result = fn__error('WORK_BUDGET_EXHAUSTED', 'the remaining work units cannot fund this operation')
result['data']['budget'] = self._budget_receipt(0)
return result
self._calls += 1
self._work_units += charged
if name in DATA_WRITE_TOOLS:
self._writes += 1
after_hash = self.business_hash()
result.setdefault('data', {})['budget'] = self._budget_receipt(charged)
self._record_event(name, actor_id, result, before_hash, after_hash, charged)
return ext_deepcopy(result)
def _supply_chain_finance_authority_submit(self, arguments):
result = self._supply_chain_finance_authority_submit_2(arguments)
if result.get('status') != 'success':
return result
requested = float(arguments['requested_amount'])
discount = float(arguments['fee_rate_percent'])
result['data']['settlement_quote'] = {'factoring_request_id': result['data']['factoring_request_id'], 'offered_amount': requested, 'discount_rate_percent': discount, 'payment_amount': round(requested * (1 - discount), 2), 'quote_status': 'current'}
result['data']['submission_receipt_id'] = self._public_receipt('submission', result['data']['factoring_request_id'], requested, discount)
return result
def _supply_chain_finance_authority_finalize(self, arguments, actor_id):
request = self._state.get_entity('factoring_request', arguments['factoring_request_id'], 'factoring_request_id')
if request is None:
return World._supply_chain_finance_adapter_finalize(self, arguments, actor_id)
tasks = [self._state.get_entity('approval_task', task_id, 'approval_task_id') for task_id in arguments['approval_task_ids']]
if any((task is None for task in tasks)) or any((task.get('authority_scope_id') != request.get('funding_scope_id') or task.get('approval_chain_ref') != request.get('approval_chain_ref') or task.get('delegated_principal_id') != actor_id or (task.get('delegation_status') != 'active') for task in tasks)):
return fn__error('APPROVAL_AUTHORITY_MISMATCH', 'the supplied approval authority is not valid for this request scope')
return World._supply_chain_finance_adapter_finalize(self, arguments, actor_id)
def _supply_chain_finance_authority_cost(self, before, action, result, after):
if action['tool'] in DATA_READ_COSTS:
return DATA_READ_COSTS[action['tool']]
return World._supply_chain_finance_adapter_cost(self, before, action, result, after)
def _persistent_supply_chain_finance_adapter_grade(self, task_id):
if task_id != self._task_id:
raise ValueError('only the active task can be graded')
active = self._task_id
persistent_baselines = self._baseline_limits
self._task_id = 'T01'
self._baseline_limits = self._task_baseline_limits
try:
grade = self._supply_chain_finance_adapter_grade('T01')
finally:
self._task_id = active
self._baseline_limits = persistent_baselines
grade['task_id'] = task_id
return grade
def _persistent_supply_chain_finance_adapter_inspect_queue(self, arguments):
queue = next((row for row in self._queues if row['work_queue_id'] == arguments['work_queue_id']), None)
if queue is None:
return fn__error('WORK_QUEUE_NOT_FOUND', 'finance work queue does not exist')
position = self._active_position()
item = next((row for row in self._work_items if self._release_by_request[row['request_reference']] <= position and row['work_queue_id'] == arguments['work_queue_id'] and (row['request_reference'] == arguments['request_reference'])), None)
return {'status': 'success', 'data': {'status': 'succeeded', 'error_code': None, 'work_queue': ext_deepcopy(queue), 'found': item is not None, 'request': ext_deepcopy(item)}, 'message': 'OK'}
def _persistent_supply_chain_finance_adapter_execute(self, name, arguments, actor_id):
if name == 'get_invoice_timeline':
invoice_id = arguments.get('invoice_id')
if self._release_by_invoice.get(invoice_id, 0) > self._active_position():
return fn__error('INVOICE_NOT_FOUND', 'invoice not found')
_normalize = fn__normalize
return _normalize(self._logic.LOGIC_BY_TOOL[name](self._visible_state(), **ext_deepcopy(arguments)))
if name == 'submit_factoring_request':
invoice_id = arguments.get('invoice_id')
if self._release_by_invoice.get(invoice_id, 0) > self._active_position():
return fn__error('INVOICE_NOT_FOUND', 'invoice not found')
return self._supply_chain_finance_adapter_execute(name, arguments, actor_id)
def _supply_chain_finance_authority_restore_2(self, snapshot):
if snapshot.get('schema') != 'rescopebench-supply-chain-finance-authority/v4':
raise ValueError('unsupported authority-v4 snapshot schema')
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-supply-chain-finance-authority/v3'
self._supply_chain_finance_authority_restore_3(base)
def _scf_evolution_snapshot(self):
value = self._supply_chain_finance_authority_snapshot()
value['evolution_contract'] = {'case_version': 'scf-authority-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2)}
value['own_settlement_receipts'] = ext_deepcopy(self._own_settlements)
return value
def _scf_evolution_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('evolution_contract', None) != {'case_version': 'scf-authority-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2}:
raise ValueError('SCF evolution contract differs')
self._own_settlements = value.pop('own_settlement_receipts')
self._supply_chain_finance_authority_restore(value)
def _supply_chain_finance_authority_activate_task(self, task_id, *, apply_boundary=True):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown stream task: {task_id}')
expected = DATA_TASK_IDS[len(self._activated_tasks)] if len(self._activated_tasks) < 16 else None
if task_id != expected:
raise ValueError(f'expected {expected}, received {task_id}')
if task_id == 'T09' and apply_boundary:
self.apply_drift()
current_terms = self.current_terms
self._targets = []
for target in fn_stream_targets(task_id):
active = ext_deepcopy(target)
(active['advance_rate_percent'], active['discount_rate_percent']) = current_terms[target['rule_atom_id']]
self._targets.append(active)
self._task_baseline_limits = {}
for target in self._targets:
limit = self._state.get_entity('credit_limit', target['credit_limit_id'], 'credit_limit_id')
if limit is None:
raise ValueError('active target references a missing credit limit')
self._task_baseline_limits[target['credit_limit_id']] = {'used_amount': float(limit['used_amount']), 'available_amount': float(limit['available_amount'])}
self._task_id = task_id
self._activated_tasks.append(task_id)
self._episode_event_start = len(self._events)
self._calls = 0
self._writes = 0
self._work_units = 0
self._assert_invariants()
return {'status': 'success', 'data': {'status': 'succeeded', 'event_id': fn_opaque_event_id(task_id), 'work_unit_limit': self._work_unit_limit}, 'message': 'Finance work packet activated'}
def _supply_chain_finance_authority_init_2(self, source_root=None, source=None, work_unit_limit=70):
self._supply_chain_finance_authority_init_3(source_root=source_root, source=source, work_unit_limit=work_unit_limit)
fixture = ext_deepcopy(fn__fixture_2())
self._state = MemoryState(fixture['entities'])
self._queues = fixture['queues']
self._work_items = fixture['work_items']
self._all_targets = fixture['targets']
self._release_by_invoice = fixture['release_by_invoice']
self._release_by_request = fixture['release_by_request']
self._initial_limits = fixture['baseline_limits']
self._targets = []
self._baseline_limits = ext_deepcopy(self._initial_limits)
self._task_baseline_limits = {}
self._task_id = None
self._activated_tasks = []
self._applied_boundary_events = []
self._events = []
self._episode_event_start = 0
self._calls = 0
self._writes = 0
self._work_units = 0
self.authority_moved = False
self.authority = ext_deepcopy(DATA_PRE_AUTHORITY)
self._assert_invariants()
def _supply_chain_finance_authority_submit_2(self, arguments):
target = self._active_target_by_invoice(arguments['invoice_id'])
if target is None:
return fn__error('INVOICE_NOT_FOUND', 'invoice not found')
if not self._prior_targets_complete(target):
return fn__error('PRIOR_TARGET_INCOMPLETE', 'complete earlier listed requests before starting this request')
profile_fields = ('buyer_id', 'supplier_id', 'program_id', 'credit_limit_id')
if any((arguments.get(field) != target[field] for field in profile_fields)):
return fn__error('FINANCE_PROFILE_BINDING_MISMATCH', 'the supplied finance profile is not valid for this invoice')
authority = self.authority[target['structure_atom_id']]
authority_fields = ('funding_scope_id', 'submission_channel', 'approval_chain_ref')
if any((arguments.get(field) != authority[field] for field in authority_fields)):
return fn__error('FUNDING_AUTHORITY_SCOPE_MISMATCH', 'the supplied funding authority is not valid for this request scope')
business_arguments = {key: ext_deepcopy(arguments[key]) for key in ('invoice_id', 'requested_amount', 'advance_rate_percent', 'fee_rate_percent', 'submission_channel')}
result = World._supply_chain_finance_adapter_submit(self, business_arguments)
if result.get('status') != 'success':
return result
request_id = result['data']['factoring_request_id']
renamed = self._rename_approval_tasks(target, authority, list(result['data']['approval_task_ids']))
self._state.update_entity('factoring_request', request_id, {'approval_task_ids': renamed, 'funding_scope_id': authority['funding_scope_id'], 'approval_chain_ref': authority['approval_chain_ref']}, id_field='factoring_request_id')
result['data'].update({'approval_task_ids': renamed, 'funding_scope_id': authority['funding_scope_id'], 'approval_chain_ref': authority['approval_chain_ref']})
return result
def _supply_chain_finance_adapter_finalize(self, arguments, actor_id):
request = self._state.get_entity('factoring_request', arguments['factoring_request_id'], 'factoring_request_id')
if request is None:
return fn__error('FACTORING_REQUEST_NOT_FOUND', 'factoring request does not exist')
supplied_ids = arguments['approval_task_ids']
if set(supplied_ids) != set(request.get('approval_task_ids') or []):
return fn__error('APPROVAL_TASK_BINDING_MISMATCH', 'supplied approval handles do not match the factoring request')
program = self._state.get_entity('program', request.get('program_id'), 'program_id')
expected_discount = float((program or {}).get('base_discount_rate_percent') or 0)
expected_payment = fn__money(float(request.get('requested_amount') or 0) * (1 - expected_discount))
if program is None or fn__money(arguments['offered_amount']) != fn__money(request.get('requested_amount')) or float(arguments['discount_rate_percent']) != expected_discount or (fn__money(arguments['payment_amount']) != expected_payment):
return fn__error('SETTLEMENT_TERMS_MISMATCH', 'the supplied offer or payment does not match current program terms')
grants = DATA_ACTOR_GRANTS.get(actor_id, frozenset())
ordered_tasks = []
for role in DATA_APPROVAL_ROLES:
task = next((self._state.get_entity('approval_task', task_id, 'approval_task_id') for task_id in supplied_ids if (self._state.get_entity('approval_task', task_id, 'approval_task_id') or {}).get('approver_role') == role), None)
if task is None:
return fn__error('APPROVAL_ROLE_MISSING', 'the request lacks one required approval role')
if role not in grants:
return fn__error('APPROVER_ROLE_NOT_AUTHORIZED', 'the authenticated actor is not authorized for the approval role')
ordered_tasks.append(task)
for task in ordered_tasks:
self._require_success(self._raw('approve_factoring_task', {'approval_task_id': task['approval_task_id'], 'decision_note': 'Approved through the bounded T01 operations workflow.', 'decided_by': actor_id}))
offer = self._require_success(self._raw('create_early_payment_offer', {'factoring_request_id': request['factoring_request_id'], 'offered_amount': arguments['offered_amount'], 'discount_rate_percent': arguments['discount_rate_percent'], 'expires_at': '2026-12-01T09:00:00Z', 'offer_type': 'factoring_advance'}))
offer_id = offer['early_payment_offer_id']
self._require_success(self._raw('accept_early_payment_offer', {'early_payment_offer_id': offer_id, 'accepted_by': actor_id}))
payment = self._require_success(self._raw('schedule_payment', {'invoice_id': request['invoice_id'], 'early_payment_offer_id': offer_id, 'payment_type': 'funder_advance', 'amount': arguments['payment_amount'], 'scheduled_at': '2026-10-01T09:00:00Z', 'reference_code': f"advance-{request['factoring_request_id']}"}))
payment_id = payment['payment_id']
scheduled = self._state.get_entity('payment', payment_id, 'payment_id') or {}
waterfall = self._state.get_entity('payment_waterfall', scheduled.get('payment_waterfall_id'), 'payment_waterfall_id')
if not waterfall or waterfall.get('status') != 'active':
return fn__error('PAYMENT_WATERFALL_PRECONDITION_FAILED', 'the scheduled payment does not reference the active waterfall')
settlement = self._require_success(self._raw('execute_payment_waterfall', {'payment_id': payment_id, 'execution_date': '2026-10-01T09:05:00Z'}))
return fn__success(factoring_request_id=request['factoring_request_id'], approval_task_ids=[task['approval_task_id'] for task in ordered_tasks], early_payment_offer_id=offer_id, payment_id=payment_id, ledger_event_id=settlement['ledger_event_id'], reconciliation_item_id=settlement['reconciliation_item_id'])
def _supply_chain_finance_adapter_cost(self, before, action, result, after):
del before, after
name = action['tool']
if name in DATA_WRITE_TOOLS:
if result.get('status') != 'success':
return 5
return 5 if name == 'submit_factoring_request' else 10
if name in {'inspect_finance_work_queue', 'inspect_credit_limit'}:
return 3
base = 3 if name == 'get_invoice_timeline' else 2
return base + self._result_rows(name, result)
def _supply_chain_finance_adapter_grade(self, task_id='T01'):
if task_id != 'T01' or task_id != self._task_id:
raise ValueError('only the active T01 fixture can be graded')
deliverables = []
requests = self._state.list_entities('factoring_request')
offers = self._state.list_entities('early_payment_offer')
payments = self._state.list_entities('payment')
reconciliations = self._state.list_entities('reconciliation_item')
ledgers = self._state.list_entities('ledger_event')
for target in self._targets:
request_rows = [row for row in requests if row.get('invoice_id') == target['invoice_id']]
request = request_rows[0] if len(request_rows) == 1 else None
invoice = self._state.get_entity('invoice', target['invoice_id'], 'invoice_id')
limit = self._state.get_entity('credit_limit', target['credit_limit_id'], 'credit_limit_id')
task_rows = [self._state.get_entity('approval_task', task_id, 'approval_task_id') for task_id in request.get('approval_task_ids', [])] if request else []
offer_rows = [row for row in offers if request and row.get('factoring_request_id') == request['factoring_request_id']]
offer = offer_rows[0] if len(offer_rows) == 1 else None
payment_rows = [row for row in payments if offer and row.get('early_payment_offer_id') == offer['early_payment_offer_id']]
payment = payment_rows[0] if len(payment_rows) == 1 else None
recon_rows = [row for row in reconciliations if payment and row.get('payment_id') == payment['payment_id']]
ledger_rows = [row for row in ledgers if payment and row.get('related_type') == 'payment' and (row.get('related_id') == payment['payment_id'])]
expected_payment = fn__money(target['requested_amount'] * (1 - target['discount_rate_percent']))
baseline = self._baseline_limits[target['credit_limit_id']]
milestones = {'binding_and_terms_verified': bool(request and request.get('program_id') == target['program_id'] and (fn__money(request.get('requested_amount')) == fn__money(target['requested_amount'])) and (float(request.get('advance_rate_percent') or 0) == target['advance_rate_percent']) and (float(request.get('fee_rate_percent') or 0) == target['discount_rate_percent'])), 'credit_reservation_conserved': bool(request and limit and (fn__money(limit.get('used_amount')) == fn__money(baseline['used_amount'] + target['requested_amount'])) and (fn__money(limit.get('available_amount')) == fn__money(baseline['available_amount'] - target['requested_amount'])) and (fn__money(limit.get('used_amount') + limit.get('available_amount')) == fn__money(limit.get('limit_amount')))), 'role_approvals_complete': bool(request and len(task_rows) == 4 and all((task is not None for task in task_rows)) and ({task['approver_role'] for task in task_rows} == set(DATA_APPROVAL_ROLES)) and all((task.get('status') == 'approved' and task.get('assigned_to') == 'operator-t01-scf' for task in task_rows))), 'advance_payment_settled': bool(request and request.get('status') == 'funded' and offer and (offer.get('status') == 'accepted') and (fn__money(offer.get('offered_amount')) == fn__money(target['requested_amount'])) and (float(offer.get('discount_rate_percent') or 0) == target['discount_rate_percent']) and payment and (payment.get('status') == 'settled') and (payment.get('payment_type') == 'funder_advance') and (fn__money(payment.get('amount')) == expected_payment) and invoice and (fn__money(invoice.get('paid_amount')) == expected_payment)), 'ledger_and_reconciliation_closed': bool(payment and len(ledger_rows) == 1 and (fn__money(ledger_rows[0].get('amount')) == fn__money(payment.get('amount'))) and (len(recon_rows) == 1) and (recon_rows[0].get('status') == 'matched') and (fn__money(recon_rows[0].get('difference_amount')) == 0.0) and (fn__money(sum((payment.get('allocation_breakdown') or {}).values())) == fn__money(payment.get('amount'))))}
score = 5.0 * sum(milestones.values())
deliverables.append({'target_id': target['target_id'], 'request_reference': target['request_reference'], 'score': score, **milestones, 'invoice_id': target['invoice_id'], 'factoring_request_id': request.get('factoring_request_id') if request else None, 'payment_id': payment.get('payment_id') if payment else None})
return {'task_id': task_id, 'score': sum((row['score'] for row in deliverables)), 'max_score': 100.0, 'completed_artifacts': sum((row['score'] == 25.0 for row in deliverables)), 'work_units_used': self._work_units, 'work_units_remaining': self._work_unit_limit - self._work_units, 'write_attempts_used': self._writes, 'deliverables': deliverables}
def _supply_chain_finance_adapter_execute(self, name, arguments, actor_id):
if name == 'list_finance_work_queues':
return self._list_queues(arguments)
if name == 'inspect_finance_work_queue':
return self._inspect_queue(arguments)
if name in {'list_buyers', 'list_suppliers', 'list_programs', 'inspect_credit_limit', 'get_invoice_timeline'}:
return self._raw(name, arguments)
if name == 'search_invoices':
return self._search_invoices(arguments)
if name == 'submit_factoring_request':
return self._submit(arguments)
if name == 'finalize_factoring_advance':
return self._finalize(arguments, actor_id)
return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
def _supply_chain_finance_authority_restore_3(self, snapshot):
if snapshot.get('schema') != 'rescopebench-supply-chain-finance-authority/v3':
raise ValueError('unsupported authority-v3 snapshot schema')
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-supply-chain-finance-stream-snapshot/v1'
base.pop('authority_moved', None)
base.pop('authority', None)
self._persistent_supply_chain_finance_adapter_restore(base)
self.authority_moved = bool(snapshot['authority_moved'])
self.authority = ext_deepcopy(snapshot['authority'])
def _supply_chain_finance_authority_snapshot(self):
value = self._supply_chain_finance_authority_snapshot_2()
value['schema'] = 'rescopebench-supply-chain-finance-authority/v5'
return value
def _supply_chain_finance_authority_init_3(self, source_root=None, source=None, work_unit_limit=70):
if work_unit_limit <= 0:
raise ValueError('work_unit_limit must be positive')
selected = ext_Path(source_root or source or CASE_DIR / 'raw').resolve()
(modules, _) = ext_load_isolated_modules(selected, ('mcp_servers.finance_logic',))
self._logic = modules[0]
self._logic.now_iso = lambda : '2026-09-25T12:00:00Z'
self._work_unit_limit = int(work_unit_limit)
fixture = ext_deepcopy(fn__fixture_4())
self._state = MemoryState(fixture['entities'])
self._queues = fixture['queues']
self._work_items = fixture['work_items']
self._all_targets = fixture['targets']
self._release_by_invoice = fixture['release_by_invoice']
self._release_by_request = fixture['release_by_request']
self._initial_limits = fixture['baseline_limits']
self._targets: list[dict[str, ext_Any]] = []
self._baseline_limits = ext_deepcopy(self._initial_limits)
self._task_baseline_limits: dict[str, dict[str, float]] = {}
self._task_id: str | None = None
self._activated_tasks: list[str] = []
self._applied_boundary_events: list[str] = []
self._events: list[dict[str, ext_Any]] = []
self._episode_event_start = 0
self._calls = 0
self._writes = 0
self._work_units = 0
self.authority_moved = False
self.authority = ext_deepcopy(DATA_PRE_AUTHORITY)
self._suppress_boundary = False
self._assert_invariants()
def _supply_chain_finance_adapter_submit(self, arguments):
invoice = self._state.get_entity('invoice', arguments['invoice_id'], 'invoice_id')
if invoice is not None:
program = self._state.get_entity('program', invoice.get('program_id'), 'program_id')
if program is not None and (fn__money(arguments['requested_amount']) != fn__money(invoice.get('outstanding_amount')) or float(arguments['advance_rate_percent']) != float(program.get('max_advance_rate_percent') or 0) or float(arguments['fee_rate_percent']) != float(program.get('base_discount_rate_percent') or 0)):
return fn__error('PROGRAM_TERMS_MISMATCH', 'the request does not use the invoice balance and current program terms')
return self._raw('submit_factoring_request', arguments)
def _persistent_supply_chain_finance_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-supply-chain-finance-stream-snapshot/v1':
raise ValueError('unsupported stream snapshot schema')
base = ext_deepcopy(snapshot)
base['schema'] = 'rescopebench-supply-chain-finance-snapshot/v1'
for key in ('all_targets', 'release_by_invoice', 'release_by_request', 'initial_limits', 'task_baseline_limits', 'activated_tasks', 'applied_boundary_events', 'episode_event_start'):
base.pop(key, None)
self._supply_chain_finance_adapter_restore(base)
self._all_targets = ext_deepcopy(snapshot['all_targets'])
self._release_by_invoice = {key: int(value) for (key, value) in snapshot['release_by_invoice'].items()}
self._release_by_request = {key: int(value) for (key, value) in snapshot['release_by_request'].items()}
self._initial_limits = ext_deepcopy(snapshot['initial_limits'])
self._task_baseline_limits = ext_deepcopy(snapshot['task_baseline_limits'])
self._activated_tasks = list(snapshot['activated_tasks'])
self._applied_boundary_events = list(snapshot['applied_boundary_events'])
self._episode_event_start = int(snapshot['episode_event_start'])
self._logic.now_iso = lambda : '2026-09-25T12:00:00Z'
def _supply_chain_finance_authority_snapshot_2(self):
value = self._supply_chain_finance_authority_snapshot_3()
value['schema'] = 'rescopebench-supply-chain-finance-authority/v4'
return value
def _supply_chain_finance_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-supply-chain-finance-snapshot/v1':
raise ValueError('unsupported snapshot schema')
self._task_id = snapshot.get('task_id')
self._state.restore({'entities': snapshot.get('entities') or {}})
self._queues = ext_deepcopy(snapshot.get('queues') or [])
self._work_items = ext_deepcopy(snapshot.get('work_items') or [])
self._targets = ext_deepcopy(snapshot.get('targets') or [])
self._baseline_limits = ext_deepcopy(snapshot.get('baseline_limits') or {})
self._events = ext_deepcopy(snapshot.get('events') or [])
self._calls = int(snapshot.get('calls') or 0)
self._writes = int(snapshot.get('writes') or 0)
self._work_units = int(snapshot.get('work_units') or 0)
self._work_unit_limit = int(snapshot.get('work_unit_limit') or 65)
self._assert_invariants()
def _supply_chain_finance_authority_snapshot_3(self):
value = self._persistent_supply_chain_finance_adapter_snapshot()
value['schema'] = 'rescopebench-supply-chain-finance-authority/v3'
value['authority_moved'] = self.authority_moved
value['authority'] = ext_deepcopy(self.authority)
return value
def _persistent_supply_chain_finance_adapter_snapshot(self):
base = self._supply_chain_finance_adapter_snapshot()
base['schema'] = 'rescopebench-supply-chain-finance-stream-snapshot/v1'
base.update({'all_targets': ext_deepcopy(self._all_targets), 'release_by_invoice': ext_deepcopy(self._release_by_invoice), 'release_by_request': ext_deepcopy(self._release_by_request), 'initial_limits': ext_deepcopy(self._initial_limits), 'task_baseline_limits': ext_deepcopy(self._task_baseline_limits), 'activated_tasks': list(self._activated_tasks), 'applied_boundary_events': list(self._applied_boundary_events), 'episode_event_start': self._episode_event_start})
return base
def _supply_chain_finance_adapter_snapshot(self):
return {'schema': 'rescopebench-supply-chain-finance-snapshot/v1', 'task_id': self._task_id, 'entities': self._state.snapshot()['entities'], 'queues': ext_deepcopy(self._queues), 'work_items': ext_deepcopy(self._work_items), 'targets': ext_deepcopy(self._targets), 'baseline_limits': ext_deepcopy(self._baseline_limits), 'events': ext_deepcopy(self._events), 'calls': self._calls, 'writes': self._writes, 'work_units': self._work_units, 'work_unit_limit': self._work_unit_limit}
class MemoryState:
def __init__(self, entities):
self._entities = ext_deepcopy(entities)
self._fault: dict[str, ext_Any] | None = None
self._active_tool: str | None = None
self._mutation_count = 0
def list_entities(self, entity_type):
return ext_deepcopy(self._entities.get(entity_type, []))
def query_entities(self, entity_type, predicate):
return [row for row in self.list_entities(entity_type) if predicate(row)]
def get_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS[entity_type] if id_field == 'id' else id_field
return next((ext_deepcopy(row) for row in self._entities.get(entity_type, []) if row.get(field) == entity_id), None)
def add_entity(self, entity_type, entity, id_field='id'):
field = DATA_ENTITY_ID_FIELDS[entity_type] if id_field == 'id' else id_field
identifier = entity.get(field)
if not identifier:
raise ValueError(f'missing identity for {entity_type}')
rows = self._entities.setdefault(entity_type, [])
for (index, row) in enumerate(rows):
if row.get(field) == identifier:
rows[index] = ext_deepcopy(entity)
self._after_mutation()
return ext_deepcopy(rows[index])
rows.append(ext_deepcopy(entity))
self._after_mutation()
return ext_deepcopy(entity)
def update_entity(self, entity_type, entity_id, patch, id_field='id'):
field = DATA_ENTITY_ID_FIELDS[entity_type] if id_field == 'id' else id_field
for row in self._entities.get(entity_type, []):
if row.get(field) == entity_id:
row.update(ext_deepcopy(patch))
self._after_mutation()
return ext_deepcopy(row)
return None
def get_core_state(self):
unresolved = sum((abs(float(row.get('difference_amount') or 0)) for row in self._entities.get('reconciliation_item', []) if row.get('status') in {'open', 'exception'}))
return {'reconciliation_control': {'unresolved_difference_amount': round(unresolved, 2)}}
def snapshot(self):
return {'entities': ext_deepcopy(self._entities)}
def restore(self, snapshot):
self._entities = ext_deepcopy(snapshot['entities'])
self._fault = None
self._active_tool = None
self._mutation_count = 0
def begin_tool(self, name):
self._active_tool = name
self._mutation_count = 0
def end_tool(self):
self._active_tool = None
self._mutation_count = 0
def configure_fault(self, tool, after_mutations):
self._fault = {'tool': tool, 'after_mutations': after_mutations}
def _after_mutation(self):
self._mutation_count += 1
if not self._fault or self._fault.get('tool') != self._active_tool:
return
if self._mutation_count >= int(self._fault['after_mutations']):
self._fault = None
raise InjectedFailure('case-local injected write failure')
class Abort(RuntimeError):
def __init__(self, result):
RuntimeError.__init__(self, str(result.get('message') or 'operation aborted'))
self.result = result
class InjectedFailure(RuntimeError):
pass